mysqli不执行Select语句
I have the code bellow. When I use this code without the WHERE
clause, all the users from the table are displayed, as expected. But when the WHERE
clause is used, nothing is displayed.
我有下面的代码。当我在没有WHERE子句的情况下使用此代码时,将按预期显示表中的所有用户。但是当使用WHERE子句时,不会显示任何内容。
What could be the cause and how can I fix it?
可能是什么原因以及如何解决?
Thank you!
function requestUser($user) {
$DBHost = "localhost";
$DBUser = "dbUser";
$DBPass = "dbPass";
$DBName = "dbName";
$db = new mysqli($DBHost, $DBUser, $DBPass, $DBName);
if ($db -> connect_errno > 0) {
$lbOK = false;
}
else {
$lbOK = $db -> set_charset('utf8');
}
if ($lbOK) {
$id = NULL;
$user_name = NULL;
$user = htmlentities($user, ENT_QUOTES);
$lcSQL = "SELECT `user_name` FROM `users` WHERE user_name=?";
$stmt = $db -> prepare($lcSQL);
$ok = $stmt -> bind_param('s', $user);
$ok = $stmt -> execute();
$ok = $stmt -> bind_result($user_name);
while ($row = $stmt -> fetch()){
echo $user_name;
}
$stmt->close();
}
}
1 个解决方案
#1
0
There are many major faults with your code, some of them can be responsible for the problem, and some not. But nevertheless, they all have to be corrected
您的代码存在许多主要缺陷,其中一些可能是问题的原因,而另一些则不是。但是,他们都必须得到纠正
- Never connect co database inside of an application function. Connect somewhere in the bootstrap file, once, and use that single connection throughout all the application.
- Do not use htmlentities with whatever database interactions. It may easily spoil the data
- Always check for the the errors
Do not use mysqli, it is unusable. Use PDO instead.
不要使用mysqli,它是无法使用的。请改用PDO。
$dsn = "mysql:host=DBHost;dbname=DBName;charset=utf8"; $opt = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ); $pdo = new PDO($dsn,$DBUser, $DBPass, $opt); function requestUser($user) { global $db; $sql = "SELECT `user_name` FROM `users` WHERE user_name=?"; $stmt = $db->prepare($sql); $stmt->execute(array($user)); return $stmt->fetchColumn(); } echo requestUser($user);
切勿在应用程序功能内部连接co数据库。在引导程序文件中的某处连接一次,并在整个应用程序中使用该单个连接。
不要将htmlentities与任何数据库交互一起使用。它可能很容易破坏数据
始终检查错误
if it still doesn't work, verify it this way
如果它仍然不起作用,请以这种方式验证
$sql = "SELECT `user_name` FROM `users` WHERE user_name='$user'";
var_dump($sql);
and then try to run in console/phpmyadmin to find out what's wrong with your data/value
然后尝试在console / phpmyadmin中运行以找出您的数据/值有什么问题
更多相关文章
- php评论回复无限极嵌套如何实现?已写基本代码,期待高手解惑
- thinkphp友情链接代码
- 如何在php中找到更轻或更暗版本的十六进制代码的十六进制代码
- PHP 网站保存快捷方式的实现代码
- 正则表达式匹配wordpress类似的短代码,用于自闭和封闭。
- php文件显示代码在Chrome
- 怎么知道php代码运行时调用了那个类、那个方法呢?
- PHP / Ajax:如何在成功登录后启动会话(剩余代码工作)
- 将SQL查询的SELECT子句解析为PHP数组