SQL select count代码不起作用

时间:2013-07-03 16:39:09

标签: php mysql sql select count

我刚刚启动SQL和PHP,并且变得有点卡住了。我试图计算用户名对用户表的匹配数,以便我可以确定它是否对登录有效。我一直收到错误“警告:mysql_fetch_array()期望参数1是资源,布尔值在第13行的/home/tommybur/public_html/pass/loginsettings.php中给出” 我看过其他一些有类似问题但无法获得任何解决方案的人。 我的代码在这里:

<?php
session_start();
$con=mysqli_connect("Database Stuff");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
$specuser=$_REQUEST['usr'];

$result = mysqli_query($con,"Select count(UserID)  UserID from Users where UserID = [$specuser]");

$number = mysql_fetch_array($result);
echo "Matching number of records in Users table = ". $number."<br>";

echo "$number";
if ($number < 1) {
echo "Username is wrong";
  }
  else {
  echo "Username is correct";
  }
  ?>

有人能指出我正确的方向吗?

谢谢, 托米

2 个答案:

答案 0 :(得分:1)

我假设您要将count(UserID)设为UserID,如果是,则需要在选择ascount(UserID)之间添加UserID声明:

$result = mysqli_query($con,"Select count(UserID) as UserID from Users where UserID = [$specuser]");

$number = mysqli_fetch_array($result);
echo "Matching number of records in Users table = ". $number."<br>";

另外需要指出的是UserID = [$specuser]。您的UserID列不是数字吗?您是否故意在[]附近添加$specuser

如果您的查询有记录,mysql_fetch_array也返回一个数组,否则返回false。请参阅此处的文档:http://php.net/manual/en/function.mysql-fetch-array.php。您应该执行以下操作:

echo "Matching number of records in Users table = ". $number[0]."<br>";

答案 1 :(得分:0)

尝试此查询

SELECT COUNT(UserID) as UserID FROM Users WHERE UserID = '$specuser'

此外,您应该从SQL注入中转义数据库,因为您从$ _REQUEST获取$ specuser

  

$ specuser = mysqli_real_escape_string($ con,$ _REQUEST ['usr']);

。阅读本文 - &gt; mysqli_real_escape_string