[英]PHP query string with variables in it not working
When I build a query string using variables in PHP, it does not seem to be working. 当我使用PHP中的变量构建查询字符串时,它似乎不起作用。 My current query is:
我当前的查询是:
$u = "admin";
$hash = password_hash("password", PASSWORD_DEFAULT);
$set_login = "INSERT INTO users (username, password) VALUES ({$u}, {$hash})";
*I am executing the query further down in the script *我正在脚本中进一步执行查询
If I replace {$u}
with the string literal it represents, and replace {$hash}
with just a string literal for a password, such as password
, the query works fine. 如果我用它表示的字符串文字替换
{$u}
,而仅用密码的字符串文字替换{$hash}
,例如password
,则查询工作正常。 However, when I introduce variables that is when it breaks. 但是,当我引入变量时,它就会中断。 I've tried breaking up the query string and using the concatenation operator:
我尝试分解查询字符串并使用串联运算符:
$set_login = "INSERT INTO users (username, password) VALUES ( " . $u . ", " . $hash . ")";
This did not work either. 这也不起作用。 I then thought it might be something with the hash, so I modified the code to (for testing):
然后我以为可能是哈希值,所以我将代码修改为(用于测试):
$u = "admin";
$p = "password";
$set_login = "INSERT INTO users (username, password) VALUES ({$u}, {$p})";
This did not work either. 这也不起作用。
The best solution is to use prepared statements , it's very simple. 最好的解决方案是使用准备好的语句 ,这很简单。
here's how you will do it with prepared statements 这是您将如何使用准备好的语句来执行的操作
mysqli mysqli
<?php
$u = "admin";
$hash = password_hash("password", PASSWORD_DEFAULT);
$set_login = "INSERT INTO users (username, password) VALUES (?,?)";
$query = $ConnectionString->prepare($set_login);
$query->bind_param("ss",$u,$hash);
if($query){
echo "success";
}else{
error_log("error".$ConnectionString->error);
}
?>
PDO PDO
<?php
$u = "admin";
$hash = password_hash("password", PASSWORD_DEFAULT);
$query = $ConnectionString->prepare("INSERT INTO users (username, password) VALUES (?,?)")->execute(array($u,$hash));
if ($query) {
echo "success";
} else {
error_log("error" . $ConnectionString->errorInfo());
}
?>
Some useful resources. 一些有用的资源。
PDO Connection PDO Tutorials Mysqli Prepared PDO连接 PDO教程 Mysqli准备
NB: AS Jay have indicated in his comment make sure your password field size in the database is at least 60 Characters
注意:AS Jay在其评论中指出,请确保您数据库中的密码字段大小至少为60个字符
In your query the problem is that you did not wrapper the strings around quotes 在您的查询中的问题是,您没有包装引号周围的字符串
Your query should be: 您的查询应为:
$set_login = "INSERT INTO admin (uname, upass) VALUES ('{$u}', '{$hash}')";
But this is not the best recommended way of doing quires, you should use one of the methods above using prepared statements. 但这不是建议的最佳执行方式,您应该使用上述方法之一使用预准备语句。
Here's why you should : Bobby Tables 这就是您应该这样做的原因: 鲍比桌
INSERT INTO users (username, password) VALUES ('{$u}', '{$hash}')
Don't forget to wrap string with a quotation mark 别忘了用引号将字符串引起来
But as mentioned in comments, it's bad idea to put data directly, use prepared statements 但是正如评论中提到的那样,直接放置数据,使用准备好的语句是个坏主意
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.