检查数据库中的特定条目

时间:2014-09-29 18:53:23

标签: php mysql

我想检查数据库中是否存在特定条目。如果存在那么条件,如果不存在那么条件。我尝试了这段代码但却出错了

<?php
$con=mysqli_connect("localhost","root","","student");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$classname = mysqli_real_escape_string($con, $_POST['class']);

$result = mysql_query("SELECT * FROM subjectinfo WHERE class = '{$classname}'", $con);

if(mysql_num_rows($result) == 0)
    {
    echo "No Such Entry In Table. Please ADD it First.";

    }
    else
    {
    echo "Entry Available";
    }       
}
mysqli_close($con);
?> 

错误:

  

警告:mysql_query()要求参数2为资源,第11行的C:\ xampp \ htdocs \ pages \ test.php中给出的对象

     

警告:mysql_num_rows()期望参数1为资源,在第13行的C:\ xampp \ htdocs \ pages \ test.php中给出null   表中没有这样的条目。请先添加。

2 个答案:

答案 0 :(得分:1)

喜欢你的评论。确保你不要混淆mysqli和mysql。不推荐使用mysql,因此最好使用mysqli。

$con=mysqli_connect("localhost","root","","student");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$classname = mysqli_real_escape_string($con, $_POST['class']);

$result = mysqli_query($con, "SELECT * FROM subjectinfo WHERE class = '{$classname}'");

if(mysqli_num_rows($result) == 0)
    {
    echo "No Such Entry In Table. Please ADD it First.";

    }
    else
    {
    echo "Entry Available";
    }       
}
mysqli_close($con);
?> 

答案 1 :(得分:1)

您正在混合MySQL API - mysql_ + mysqli_它们不会混合在一起。此外,您的数据库连接在查询中向后。首先是连接。

下面:

<?php
$con=mysqli_connect("localhost","root","","student");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$classname = mysqli_real_escape_string($con, $_POST['class']);

$result = mysqli_query($con,"SELECT * FROM subjectinfo WHERE class = '{$classname}'");

if(mysqli_num_rows($result) == 0)
    {
    echo "No Such Entry In Table. Please ADD it First.";

    }
    else
    {
    echo "Entry Available";
    }       
}
mysqli_close($con);
?> 

同时使用or die(mysqli_error($con))mysqli_query()

另外,将error reporting添加到文件的顶部,这将有助于在生产测试期间。

error_reporting(E_ALL);
ini_set('display_errors', 1);

使用prepared statementsPDO with prepared statements了解它们更安全


洞察力:

确保您的表单元素确实已命名。

即:

<input type="text" name="class">

否则,您将收到Undefined index class...警告。