<?php
$tid = $_GET['tid'];
$id = $_SESSION['userid'];
$sql1 = "SELECT * FROM topics WHERE id='$tid' LIMIT 1";
$res1 = mysqli_query($connect, $sql1) or die(mysqli_error($connect));
while ($row = mysqli_fetch_array($res1, MYSQLI_ASSOC)) {
$title = $row['topic_title'];
$creator = $row['topic_creator'];
}
$sql = "SELECT * FROM users WHERE id='$creator' LIMIT 1";
$user_query = mysqli_query($connect, $sql) or die(mysqli_error($connect));
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$name = $row["first"].$row["last"];
}
echo $name;
?>
我对PHP有点新,但我做的事情与此完全相同,但这次我收到了错误。这里的一切都有效,除了$ name。我检查了我的SQL表并确保用户存在,并且有第一个和最后一个区域。我不知道还有什么可能是错的。
注意:未定义的变量:第**行 * 中的名称
谢谢。
答案 0 :(得分:0)
请尝试使用以下代码:
<?php
$tid = $_GET['tid'];
$id = $_SESSION['userid'];
$tid = mysqli_escape_string($connect, $tid);
$sql1 = "SELECT * FROM topics WHERE id='{$tid}' LIMIT 1";
$res1 = mysqli_query($connect, $sql1) or die(mysqli_error($connect));
// Check for rows first.
if($res1 and mysqli_num_rows($res1)){
// Use if as while is pointless on LIMIT 1
if($row = mysqli_fetch_array($res1, MYSQLI_ASSOC)) {
$title = $row['topic_title'];
$creator = $row['topic_creator'];
$creator = mysqli_escape_string($connect, $creator);
$sql = "SELECT * FROM users WHERE id='{$creator}' LIMIT 1";
$user_query = mysqli_query($connect, $sql) or die(mysqli_error($connect));
// Check for rows first.
if($user_query and mysqli_num_rows($user_query)){
// Use if as while is pointless on LIMIT 1
if ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$name = $row["first"].$row["last"]; // NO HIT!
}
echo $name;
}else{
echo 'no rows found (query 2).';
}
}
}else{
echo 'no rows found (query 1).';
}
?>
变量$name
未定义,因为未达到$name = ...;
行。因此,请确保$sql
查询实际返回结果。必须定义$name
。