我有下面的代码。当我使用不带WHERE
子句的代码时,表中的所有用户都会按预期显示。但是当使用WHERE
子句时,不会显示任何内容。
可能是什么原因以及如何解决?
谢谢!
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();
}
}
答案 0 :(得分:0)
您的代码存在许多重大缺陷,其中一些可能导致问题,有些则不然。但是,它们都必须得到纠正
不要使用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);
如果仍然无效,请以这种方式验证
$sql = "SELECT `user_name` FROM `users` WHERE user_name='$user'";
var_dump($sql);
然后尝试在console / phpmyadmin中运行以找出数据/值的错误