1

我正在查询数据库以返回员工编号,以便我可以使用它来验证表单中的条目。我将结果转储到一个数组中,然后当有人在表单上输入一个数字时,我验证它是否存在......但它不起作用并且永远找不到数字。我认为这是我创建数组的方式。

$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";
4

2 回答 2

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";
于 2012-12-07T20:29:49.020 回答
-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";
   }
}
于 2012-12-07T20:30:10.957 回答