我的代码应该打印出它找到的所有用户的用户名,但它不会打印出“User Found:”一次。请帮我解决一下;这是我的代码,谢谢!
<?php
echo'
<form method="post">
<input name="newSearch" id="newSearch" class="inputs" placeholder="Search for a user...">
<input type="submit" id="submit_search" name="submit_search" class="button" value="Search">
</form>';
if ($_POST['submit_search']) {
$search = $_POST['newSearch'];
$getUser = mysql_query("SELECT * FROM Users WHERE Username LIKE '%$search%'");
while($id=mysql_fetch_assoc($getUser)){
$gU = mysql_fetch_object($getUser);
echo "User Found: ", $gU->Username, "<br />";
}
}
?>
答案 0 :(得分:1)
尝试以下任何一项,
while($id=mysql_fetch_assoc($getUser)){
echo "User Found: ". $id["Username"]. "<br />";
}
OR,
while($gU = mysql_fetch_object($getUser)){
echo "User Found: ". $gU->Username . "<br />";
}
上述任何代码都可以帮助您度过难关。 :)
答案 1 :(得分:0)
echo "User Found: " . $gU->Username . "<br />"
应该是:
echo "User Found: " . $id["Username"] . "<br />"
编辑:
您应该选择使用数组或对象,请查看:http://stackoverflow.com/questions/1536813/mysql-fetch-array-mysql-fetch-assoc-mysql-fetch-object
了解差异。我还建议你放弃折旧代码。
使用对象:
while($id=mysql_fetch_object($getUser)){
echo "User Found: " . $id->Username . "<br />";
}
使用数组:
while($id=mysql_fetch_assoc($getUser)){
echo "User Found: " . $id["username"] . "<br />";
}
答案 2 :(得分:0)
您在循环的每次迭代中都会经历两条记录。 mysql_fetch_assoc
和mysql_fetch_object
各自抓取一条记录并将指针增加到记录集中。你几乎肯定想要。
你几乎肯定想要:
while($gU=mysql_fetch_object($getUser)){
echo "User Found: " . $gU->Username . "<br />";
}
或
while($gU=mysql_fetch_assocc($getUser)){
echo "User Found: " . $gU["Username"] . "<br />";
}