无法执行mysqli_num_rows

时间:2013-11-08 15:59:18

标签: php mysqli

我有一个插入动物名称的php文件,并检查动物是否在数据库中。但是,当数据已存在时,我无法输出messege。它总是输出msg“插入值”和这个msg

  

警告:mysqli_num_rows()期望参数1为mysqli_result,第12行的C:\ xampp \ htdocs \ test \ test-insert.php中给出布尔值

<?php
$host='localhost';
$user='root';
$password='root';
$dbname='pet';
$connect=mysqli_connect($host,$user,$password,$dbname) or die("can not connect to server");
if(@$_GET['submit']=='yes' && $_POST['animal']!="")
{
    $animal=mysqli_real_escape_string($connect,trim($_POST['animal']));
    $query="INSERT INTO animal (animal) VALUES ('$animal')";
    $result=mysqli_query($connect,$query) or die("can not execute query".mysqli_error($connect));
    if(mysqli_num_rows($result))
    {
        echo "value is already exist !";
    }
    else
    {
        echo "value is inserted ";
        echo "<p>$query</p>";
    }
}
else // 1st form display
{
    echo "<form action='$_SERVER[PHP_SELF]?submit=yes' method='POST'>
            <input type='text' name='animal'>
            <input type='submit' name='submit' value='insert name'>";

}
?>

2 个答案:

答案 0 :(得分:2)

<?php
$host='localhost';
$user='root';
$password='root';
$dbname='pet';
$connect=mysqli_connect($host,$user,$password,$dbname) or die("can not connect to server");
if(@$_GET['submit']=='yes' && $_POST['animal']!="")
{
    $animal=mysqli_real_escape_string($connect,trim($_POST['animal']));
    $checkquery="SELECT * FROM animal WHERE animal='".$animal."'";
    $checkresult=mysqli_query($connect,$checkquery) or die("can not execute query".mysqli_error($connect));
    if(mysqli_num_rows($checkresult))
    {
        echo "value is already exist !";
    }
    else
    {
        $query="INSERT INTO animal (animal) VALUES ('$animal')";
        $result=mysqli_query($connect,$query) or die("can not execute query".mysqli_error($connect));
        echo "value is inserted ";
        echo "<p>$query</p>";
    }
}
else // 1st form display
{
   echo "<form action='$_SERVER[PHP_SELF]?submit=yes' method='POST'>
        <input type='text' name='animal'>
        <input type='submit' name='submit' value='insert name'>";

}
?>

答案 1 :(得分:0)

将您的查询变量替换为SELECT

INSERT INSTEAD
$query = "SELECT * FROM animal"
$result = mysqli_query($connect,$query) or die("can not execute query".mysqli_error($connect));
if(mysqli_num_rows($result))
{
    echo "value is already exist !";
}