我正在查询数据库以返回员工编号,以便我可以使用它来验证表单中的条目。我将结果转储到一个数组中,然后当有人在表单上输入一个数字时,我验证它存在...但它不起作用,但从未找到该数字。我认为这是我创建阵列的方式。
$sql1 = "SELECT num FROM staff";
$data = array();
$result1 = mysql_query($sql1, $conn) or die("db select error: " . $sql1);
while($row1 = mysql_fetch_assoc($result1)){
$data[]= $row1;
}
var_dump($data);
$needle = 7034252;
if(in_array($needle,$data) )
echo $needle . " found";
else
echo $needle . " not found";
答案 0 :(得分:4)
$ data是一个多维数组,尽管in_array需要一维数组。 你的意思是:
$sql1 = "SELECT num FROM staff";
$data = array();
$result1 = mysql_query($sql1, $conn) or die("db select error: " . $sql1);
while($row1 = mysql_fetch_assoc($result1)){
$data[]= $row1['num'];
}
var_dump($data);
$needle = 7034252;
if(in_array($needle,$data) )
echo $needle . " found";
else
echo $needle . " not found";
这段代码可能更短(也更有效):
$needle = 7034252;
$sql = "SELECT COUNT(*) FROM staff WHERE num = " . mysql_real_escape_string($needle);
if (mysql_result(sql, 0) > 0)
echo $needle . " found";
else
echo $needle . " not found";
答案 1 :(得分:-1)
没有经过测试,但你为什么不尝试这样的东西?
$sql1 = "SELECT num FROM staff";
$result1 = mysql_query($sql1, $conn) or die("db select error: " . $sql1);
$needle = 7034252;
while($row1 = mysql_fetch_assoc($result1))
{
if ($needle == $row1['num'])
{
echo $needle . " found";
}
}