我对这一切都很陌生,试图弄清楚为什么事情有效,为什么事情没有。
所以我的目标是使用一个简单的搜索表单来显示所有具有相同名字的数据库用户。
此代码输出表“users”中用户的所有名称,并且有效。
<?php
include 'connect.php'; //working connection to the DB
$sql="SELECT name FROM users ORDER BY name ASC";
$sqlresult=mysqli_query($con,$sql);
$afct=mysqli_affected_rows($con);
while($user=mysqli_fetch_array($sqlresult,MYSQLI_ASSOC)){
$num[]=$user['name'];
$num++;
}
$i=1;
while($i < $afct)
{
echo $i.': '.$num[$i];
echo'<br>';
$i++;
}
?>
所以现在我想添加一个存储用户输入的变量,以匹配用户的名字。
<?php
include 'connect.php'; //working connection to the DB
$input = 'Marcus'; // later will be $input = $_GET(['name']);
$sql="SELECT name FROM users WHERE name='".$input."' ORDER BY name ASC";
//tried with "SELECT * FROM users WHERE name='".$input."'" ORDER BY name ASC";
//also
$sqlresult=mysqli_query($con,$sql);
$afct=mysqli_affected_rows($con);
while($user=mysqli_fetch_array($sqlresult,MYSQLI_ASSOC)){
$num[]=$user['name'];
$num++;
}
$i=1;
while($i < $afct)
{
echo $i.': '.$num[$i];
echo'<br>';
$i++;
}
?>
所有剂量输出一个空白和性感的页面。提前谢谢。
//马库斯
答案 0 :(得分:0)
我认为由于$i=1
尝试while($i <= $afct)
答案 1 :(得分:0)
问题是你将$i
初始化为1. PHP中的数组索引从0开始,就像几乎所有其他编程语言一样。由于您的第二个查询仅返回1行,因此唯一的元素将是$num[0]
。因此,您应该将$i
初始化为0。
或使用foreach
:
foreach ($num as $i => $name) {
echo "$i: $name<br>";
}
你的第一个脚本也错了,你只是没注意到它跳过了表中的一个用户。