我的项目中有一切正常。但我不能在屏幕上打印此查询的结果
$sql = "SELECT * FROM appointment WHERE prof_id=(SELECT user_id FROM user WHERE lastname='$prof_last') AND student_id=(SELECT user_id FROM user WHERE username={$_SESSION['username']});";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
echo "<div>$row</div>" ;
具体来说,它向我显示了这个错误:mysqli_fetch_assoc()期望参数1为mysqli_result,boolean given
我到处搜索但无法理解我做错了什么
答案 0 :(得分:0)
mysqli_fetch_assoc
为每行读取返回一个数组,因此$row
是一个数组
列的名称将用作数据库中值的键。
举个例子,如果你做了一个
SELECT a,b,c FROM table
你会做这样的事情来显示数据
$result = mysqli_query($conn, $sql);
// check for errors
// you do have errors so please add this test
if ( !$result ) {
echo $conn->error;
exit;
}
while ( $row = mysqli_fetch_assoc($result) ) {
echo "<div>{$row['a']}</div>" ;
}
现在您需要在该回显线中使用真实的列名
我担心我应该提到你的脚本存在SQL Injection Attack的风险 看看Little Bobby Tables偶然发生了什么 if you are escaping inputs, its not safe! 使用prepared parameterized statements
答案 1 :(得分:0)
您可能需要更改代码。
除非$_SESSION['username']
已被单引号括起,否则您应该写
$sql = "SELECT * FROM appointment " .
"WHERE prof_id=(SELECT user_id FROM user WHERE lastname='$prof_last') " .
" AND student_id=(SELECT user_id FROM user WHERE username='{$_SESSION['username']}');";
$result = mysqli_query($conn, $sql);
if ($result)
{
$row = mysqli_fetch_assoc($result);
echo "<div>$row</div>" ;
}
else
{
// perform error checking as adequate
}
......或者更好的是:
$sql = "SELECT * " .
"FROM appointment a " .
" JOIN user prof ON prof.user_id = a.prof_id " .
" JOIN user stud ON stud.user_id = a.student_id " .
"WHERE " .
" prof.lastname = '$prof_last' " .
" AND stud.username = '{$_SESSION['username']}'; " ;
注意:只有在$prof_last
和{$_SESSION['username']}
经过适当清理后才能安全使用。使用预准备语句和绑定参数总是更好。