开发者

Querying MySQL with PHP

What is wrong with this code开发者_如何学运维:

$q = query("select * from users where email = '$_POST['email']' and name = '$_POST['name']'");

Parse error: parse error, expecting T_STRING' orT_VARIABLE' or `T_NUM_STRING' in C:\wamp\www\conn\index.php on line 16

Thanks in advance.


 $q = query("select * from users where email = '{$_POST['email']}' and name = '{$_POST['name']'}");

You missed two quotes. Also:
1) Always escape user input (for security reasons):

$email = mysql_real_escape_string($_POST['email']);
$name = mysql_real_escape_string($_POST['name']);
$q = query("select * from users where email = '{$email}' and name = '{$name}'");

2) Get an editor with code highlighting, so you don't get similar problems in the future. I recommend Notepad++.


You should surround your inline vars with curly braces.

Like this:

$q = query("select * from users where email = '{$_POST['email']}' and name = '{$_POST['name']}'");


  1. You use $_POST directly in the SQL Query which is very bad.
    Use:

    $email = mysql_real_escape_string($_POST['email']);
    $name = mysql_real_escape_string($_POST['name']);
    $q = query("SELECT ... $name ... $email");

  2. I'd recommend using string concatenation instead of embedding variables in strings as it is (imho) easier to read

    $q = query("SELECT ... " . $name . " ... " . $email);

  3. SELECT * is bad (unless you really, really want all fields)


Try this:

$q = query("select * from users where email = '" . $_POST['email'] . "' and name = '" . $_POST['name'] . "'");


You are using double quoting you put quotes around $_POST['email'] and inside it making it get interpreted the wrong way

This would work the right way: $q = query('select * from users where email = '.$_POST['email'].' and name = '.$_POST['name']);

But even if it works it is still wrong to pass post variables right into a query. As a developer you need to learn to 'never trust the users'. So the best thing is to clean it by escaping it like this:

$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$q = query("select * from users where email = $email and name = $name");

or this:

$q = query('select * from users where email = '.mysql_real_escape_string($email).' and name = '.mysql_real_escape_string($name));

(what way you prefer)


Pease don't do it that way. It is a perfect example for SQL injections.

A better Version:

$email = mysql_real_escape_string($_POST['email']);
$name = mysql_real_escape_string($_POST['name']);
$q = query("select * from users where email = '$email' and name = '$name'");


Parse error: parse error, expecting T_STRING' orT_VARIABLE' or `T_NUM_STRING'

Get used to this error. Always means there is a quotation problem.

Get familiar w/ using " and '

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜