How to write PHP $ _POST vars in mysql_query function?

When accessing my database, I have a user filling out a form, and on the landing page, the posted values ​​are used in the resulting MySQL query.

$query = mysql_query("SELECT pass FROM database WHERE user='$_POST[user]'");

However, for one reason or another, MySQL does not like it when I use the $ _POST variable in a command, and it only works if I define (for example) $user = $_POST['user'];, and then put $ user directly in the SQL command.

On the other hand, I can use the $ _POST values ​​in INSERT statements where column names are not required:

$query = mysql_query("INSERT INTO database VALUES ('foo', 'bar', '$_POST[user]'");

If I try the INSERT statement where the attributes are defined (e.g. user='foo'), the same problem appears.

What am I doing wrong in my SQL query, which results in a command error at startup, but works with a specific formatting method for the INSERT command?

Hopefully this is not "hard luck, it looks like you need to assign all of your published values." Heh.

+3
source share
5 answers

First, watch out for SQL injections !

Now, to answer your question, try doing this instead:

$query = mysql_query("SELECT `pass` FROM `database` WHERE `user` LIKE '" . mysql_escape_string($_POST['user']) . "';");

You did a couple of wrong things:

  • using an operator =instead of an operatorLIKE
  • without inserting a value into the SQL query with '
  • does not include user index in array $_POSTwith'

PS: mysql_real_escape_string() mysql_escape_string()!

+10

, , .

, .

-, {} . .

$query = mysql_query("SELECT pass FROM database WHERE user='{$_POST[user]}'")

, , , SQL-. , , $_POST ['user'] "", , - "?

mysql_real_escape_string POST , , PHP PDO .

, , - sprintf.

$query=mysql_query(sprintf("SELECT pass FROM database WHERE user='%s'",mysql_real_escape_string($_POST['user'])));
+3
  • PDO - API .
  • mysql_*(), (mysql_real_escape_string()) (, )
  • , . :

    $query = mysql_query("INSERT INTO database VALUES ('foo', 'bar', " . mysql_real_escape_string($_POST['user']) . ", " . mysql_real_escape_string($_POST['user']) . ", " . mysql_real_escape_string($_POST['user']) . ", " . mysql_real_escape_string($_POST['user']) . ")");
    
    $query = sprinf('INSERT INTO database VALUES ("foo", "bar", "%s", "%s", "%s")',
    mysql_real_escape(...), ...);
    

    , , ?

+2

, mysql_error() ? , mysql_error() , , .

MySQL, POST var, , , , . GET, POST . , , , .

, , SQL , , .

+1

$query = mysql_query("SELECT pass FROM database WHERE user=" . mysql_real_escape_string($_POST['user']));

$query = mysql_query("INSERT INTO database VALUES ('foo', 'bar', " . mysql_real_escape_string($_POST['user']) . ")");

, $_GET $_POST

0

Source: https://habr.com/ru/post/1729300/


All Articles