...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
June 22, 2011

How can I ensure two floated items stay side-by-side even if there isn’t enough width for both of them?

Question by David H

I have the following HTML:

<div  >
  <div >
    <div style="float: left;">
      <input type="checkbox" value="False" />
    </div>
    <div style="float: left;" >         XXXXXXXXXXXXXXXXXXXXXXXXXXXXX </div>
  </div>
</div>

It displays the XXX to the right of the checkbox. However, if I reduce the screen width, the XXX goes under the checkbox.

Is there any way that I can “lock” the XXX text inside the DIV so the XXXX always appears to the right and on the same line?

(Note that I want to keep using DIV as later on I do some jQuery things with the DIVs.)

Answer by Starx

That is what float:left is supposed to do. It will remain in the left side as much as possible. If the element before is also floated to the left side, it will try to float to left, together with it, if the space is available. That’s why when you resize your screen and there is not enought space for the div to float to the together with previous element, it will float to the left, down the previous element.

Read more

PHP method chaining

Question by Headspin

So i was wondering if there is a way to method chain, when the initial method is a static function. Here is what I mean:

    class foo
    {
        public static function a()
        {
            $foo = new foo;
            return $foo->bar(); 
        }

        public function bar()
        {
            return $this;
        }

        public function b()
        {
            return 1;
        }
    }

    print foo::a()->b();

EDIT
print foo::a()->b(); not print foo:a()->b();

Answer by Starx

Static Methods or Other Methods, as long as the method is returning an object either self or some other, the methods can be chained, with the same method you are attempting.

class foo {
   public function __construct() {
   }
   public function create() {
       // create something;
       return $this;
   }
   public function performSomethingElse() {
      // perform something
      return $this;
   }
}
$object = new foo;

$object -> create() -> performSomethingElse();
Read more
June 21, 2011

which file is the js error in and how to correct it?

Question by zhuanzhou

enter image description here

http://www.idcspy.com/asp-hosting.html

when loads over the page , at the bottom of the IE broswer window. it shows an alert(the page has an error), it’s an javascript error.but i don’t know which js file has the error in and how to correct it. thank you,

Answer by Starx

Use Developer tools, to find and debug the error

IE: Press F12
Firefox: Downlaod addon known as Firbug
Chrome: Right click -> Inspect Element to get started or (Ctrl + Shift + J)
Read more
June 17, 2011

Bottom div to expand according to screen resolution

Question by weblearner

<div class="main">
    <div class="topContent">
         content goes here
    </div> 
</div>
<div class="footer">
</div>

My code is like this, I want the footer to expand as the resolution of the screen gets bigger. Is it possible?

My whole site should be above the fold always with no scroll and the footer should expand to fit the screen resolution.

Answer by RubenHerman

If you want the footer to take the whole screen-height, don’t use a height.
If you want to use an other height according to your screen resolution, you’ll need javascript/jquery

Give an id to the footer (example: footer) and try this:

<script type="text/javascript">
//Determine screen resolution
screenheight = screen.height;
d = document.getElementById('footer');
if (screenheight == 1024)
{
    d.style.height="500px";
}
else
{
    d.style.height="600px";
}
</script>

Answer by Starx

Percentage scale, works with relative to screen’s resolutions, so you just have to specify the height as percentage.

#footer { height: 10%; }
Read more
June 14, 2011

100% DIV width is not really 100%

Question by Kevin

When I have a <div> with width: 100%, it is not really 100%:

<div id="div">testtesttesttesttest</div>

...

#div {
  width: 100%;
  background-color: red;
}

Now when you resize the window, so there is a horizontal scrollbar, and you scroll to the right, then the background is vanished. How can I remain the background in this case?

Here you can see the problem in action:
http://beta.ovoweb.net/?i=3

Now when you resize the window and scroll to the right, you can’t see the background anymore. How to fix this?

Answer by jsumners

The 100% value is 100% of the parent’s width or the view port. See the documentation.

Answer by Starx

Width: 100%, is highly affected by its margin and margin and padding of its parent (body in your case). SO, reset them first

Something like

body {
    margin: 0;
    padding: 0;
}
#div {
  margin: 0;
  width: 100%;
  background-color: red;
}

DEMO

Read more

Should this function be public or private?

Question by Roman

I am verifying the email in database in form validation in CodeIgniter by using callback in rule. For example

$this -> form_validation -> set_rules( 'email', 'Email address', 'trim|valid_email|callback_email_exists' );

The email_exists function is:

public function email_exists($email)
    {
        $this -> load -> model('account_model');
        $exists = $this -> account_model -> email_registered( $email );
        if ( $exists == true )
        {
            $this -> form_validation -> set_message ( 'email_exists', 'Email already exists.');
            return false;
        }
        return true;        
    }

It works fine. However, shouldn’t the above email_exists function be a private function instead of public?
I try to make it private like private function _email_exists($email) and i call back it by callback__email_exists

However I get the error:

Fatal error: Call to private method Account::_email_exists() from context 'CI_Form_validation' in ....(line number)

Can someone tell me what’s wrong?

Answer by Itay Moav

If you need to call it from outside the object (whether as callback or directly) it should be public

Answer by Starx

You are validating the email, on the basis of your model account_model, so this makes the function more centered to the private boundary. You will not achieve anything significant, by making this function public, instead you can make this function what it is

A PRIVATE FUNCTION TO CHECK EMAILS FOR MODEL account_model
Read more
June 8, 2011

Best way to process forms

Question by Gatura

What is the best way to process PHP forms, using $_SERVER['PHP_SELF'] or using a separate file for processing?

Answer by Starx

This is a very vague question. Answers depends on several factor

  • Architecture

What architecture are you using, it is a basic PHP, or OOP, or MVC?

  • Manaegiblity

How do you prefer to manage your coding? Do you prefer HTML and PHP coding mixed in a same page?

  • Flexibility

How much flexibilty does your coding needs to be? Should it be able to increase and decrease form elements and its processing on Demand?

  • Coupled

How much tightly/loosely coupled, your form and PHP codes are? Does the modules handling Form submit, work independent of form type?

Update

Create a seperate folder, where you will process the post of your page similar to this

mypage.php
process/mypage.php

mypage.php will contain the form with action field as follows

<form action="<?php echo "process/".$_SERVER['PHP_SELF']; ?>">

By using the PHP_SELF in this case will make the code reusable, with out making changes to it, on other forms also.

Now you can handle your POST request on process/mypage.php and redirect to /mypage.php, once it is done.

Read more

why does jquery's .load() ignore <script>?

Question by Lai Yu-Hsuan

I have a every common page a.html which looks like this:

<html>
  <head>
    <script type="text/javascript" src="xyz.js" > </script>
  </head>
  <body>
    <div> ... </div>
  </body>
</html>

In b.html, I use jquery’s .load() function to a div.

$("#myDiv").load("a.html")  

It works. The xyz.js’s content is loaded along with a.html. But why isn’t there a <script> tag? I open firebug to see the source. There is a’s but no a’s <script>.

I want the <script> because I need it to find relative path.
(this question)

Edit: I tried to use .get() and .html(). Didn’t help.

Edit2: The title is not very appropriate. The xyz.js runs. But no <script>.

Answer by Pointy

The “.load()” function purposefully strips out <script> tags from the loaded content. When you give it a plain URL to load, it will execute the scripts after loading the content and adding it to the DOM. However, if you use the trick of adding a selector after the URL in the first argument:

$('#foo').load("http://some.domain.com/blah #special-div");

then it strips the <script> tags but it does not execute them.

Why? I don’t know.

Now, please note that loading an entire page from the <html> tag on down into an element of another page is going to result in some sort of Frankenstein monster of a DOM, if a browser will do it at all. Generally, when you use “.load()” to grab fragments of content to update a page, your server should respond with a piece of a page, not the whole thing. The jQuery deal with allowing a selector after the actual URL is intended to let you strip out a chunk of a page, which is really cool, but it has that drawback that the scripts won’t be executed in that case.

Answer by Starx

Because, it cannot run the script inside the <SCRIPT> tag. jQuery has .getScript() to call for scripts only. Check here

Read more

Where do i begin programming in php?

Question by angel

i am a programer i have programed in C#, asp.net, Visual basic, Java, j2me, and now i want to learn php, i downloaded dreamweaver i choosed php
and i watch only code html i dont know how to put textbox, radiobutton, and more controls, in the another (not java) i choose the control and i move it… it is easy doing it, of this form, i didn’t see nothing as this, in dreamweaver, another question, how do you add class in php? for a programing OO …
add clases and methods (in php i believe they are called functions)
if dreamweaver is bad, what program do you recommend me?

Answer by itsols

Yes, you can use DreamWeaver for PHP development. But don’t expect the same ‘look and feel’ of IDEs like MS C# or VB.

For example, you can create your forms in design view on DreamWeaver by dragging elements onto it, and then add the code by going into code-view. I don’t recall the actual wording used on DreamWeaver but there’s one view with a designer and the other with HTML code.

For example, if you create a textbox on the form, the code behind it will be something like this:

<input type="text" name="txtEmployeeID" />

Now, if you want to print some variable from within the code, you could include it in the code view like this:

<input type="text" name="txtEmployeeID" value="<?php echo $EmployeeID; ?>" />

You can actually incorporate PHP code within the html page simply by enclosing the code within the php tags like above.

But this is only a very elementary example. You can actually use ANY editor and what you use would also depend on the OS you have. For example, on Ubuntu I use GEdit, with a few plugins that help easily read PHP code using a nice colour scheme. But for a beginner, this may not be the ideal thing.

I don’t mean to advertise myself, but I have a simple video of GEdit in use on YouTube. If you’re interested, you may check it out on my channel “marhaonline”.

Answer by Starx

My recommendation will be going with Zend Studio. It is developed especially for PHP Development, where as others, are created for multiple purposes.

Did I mentiond It is also an award winning IDE also?…
Check Here


You are also asking about putting textbox, and radio buttons. This is more HTML based, rather than PHP, if this is major concern then, it should go with netbeans or dreamweaver, they provide better and user friendly UI for this.

In the latest dreamweaver,
There is a panel called Insert Panel (Ctrl + F2 on Windows), it gives all the HTML elements, including form elements (Just select “FORM” from the drop down box”), which you can also drag and drop.

Read more

MYSQL SELECT and JSON_ENCODE

Question by Gabriel Santos

I need to select a key from a json_encodED array from mysql..

SELECT * FROM json_field_table WHERE {var from JSON encoded array} = {expected value}

or something..
How I can do this?

PS.: Poor English, I know..

Answer by Marc B

You’d have to use substring matching. MySQL doesn’t have anything to deal with JSON data and treats it like it does any other piece of random text.

SELECT ... WHERE the_json_field LIKE '%"var":"value"%';

Answer by Starx

Well, Gabriel, despite the nature of your question. I am supposing, your problem might be, you need to read a JSON value and based on that values, you need to retrieve the record set from the table. If this is the case, here is your solution.

// A sample json string
$json = '{ "field1": "value1", "field2": "value2" }'; 

// Here we will convert the json string into readable assocative array
$json_array = json_decode($json,true); 

//Next we will use it on a query
$query = "SELECT * json_field_table WHERE `".$json_array['field1']."` = 'Some Value' ";

//Execute the query
$result = mysql_query($query);
Read more
...

Please fill the form - I will response as fast as I can!