why does one work, but the other doesn't?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
someguyhere
Forum Contributor
Posts: 181
Joined: Sun Jul 27, 2008 3:24 pm

why does one work, but the other doesn't?

Post by someguyhere »

This one works:

Code: Select all

			$query = "SELECT * FROM wp_network_members WHERE f_name = '$_POST[f_name]' AND l_name = '$_POST[l_name]'";
This one doesn't:

Code: Select all

			$query = "SELECT * FROM wp_network_members WHERE f_name = '$_POST['f_name']' AND l_name = '$_POST['l_name']'";
I was told that I need to use single quotes within the POST variable, but when I do here, I get the following error:

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in xxxxx on line 244
Peec
Forum Commoner
Posts: 33
Joined: Fri Feb 22, 2008 3:58 am

Re: why does one work, but the other doesn't?

Post by Peec »

You must escape the string.

Eg.
'Test post var: '.$_POST['var'].' , yup thats the value.':

In ur case "select .... where blah ='".$_POST['test']."' OR ...";
Single quotes is faster because php will not look for variables and does not need to parse the string before assigning it to a variable.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: why does one work, but the other doesn't?

Post by VladSun »

You need a string concatenation (Peec's code), or a proper PHP variable expansion:

Code: Select all

 $query = "SELECT * FROM wp_network_members WHERE f_name = '{$_POST['f_name']}' AND l_name = '{$_POST['l_name']}'";
http://php.net/manual/en/language.types.array.php
Array do's and don'ts
Why is $foo[bar] wrong?

Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts:
<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>

This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in future define constants which, unfortunately for such code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply