我应该如何在mysql_query函数中编写PHP $ _POST vars? [英] How should I write PHP $_POST vars in a mysql_query function?

查看:71
本文介绍了我应该如何在mysql_query函数中编写PHP $ _POST vars?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在访问我的数据库时,我让用户填写了一个表单,并且在目标页面中,发布的值用于结果MySQL查询中.

In accessing my database, I have the user fill out a form, and in the target page, the posted values are used in the resulting MySQL query.

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

但是,由于某种原因,MySQL不喜欢我在命令中使用$ _POST变量,并且仅当我定义(例如)$user = $_POST['user'];,然后将$ user直接放入SQL时,MySQL才有效命令.

However, for some reason or another, MySQL doesn't like my using a $_POST variable in the command, and it only works if I define (for example) $user = $_POST['user'];, and then put $user directly in the SQL command.

另一方面,我可以在不需要特定列名的INSERT语句中使用$ _POST值:

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

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

如果我尝试定义属性的INSERT语句(例如user='foo'),则会出现相同的问题.

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

我在SQL查询中做错了什么,导致命令在运行时出错,但是可以使用格式化INSERT命令的特定方法?

What am I doing wrong in my SQL query that causes the command to error out when run, but works with the specific method of formatting an INSERT command?

希望这不是运气不好,看起来您必须分配所有已发布的值".嘿.

Hopefully, it's not "tough luck, looks like you have to assign all of your posted values". Heh.

推荐答案

首先, 注意SQL注入

First of, 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']) . "';");

您做错了几件事:

  • 使用=运算符而不是LIKE运算符
  • 不使用'
  • 将值包含在SQL查询中
  • 不使用'
  • 将用户索引包含在$_POST数组中
  • using the = operator instead of LIKE operator
  • not enclosing the value in the SQL query with '
  • not enclosing the user index in the $_POST array with '

PS:您应该使用 mysql_real_escape_string() 代替 mysql_escape_string()

这篇关于我应该如何在mysql_query函数中编写PHP $ _POST vars?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆