0

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

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

<?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'>";

}
?>
4

2 回答 2

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'>";

}
?>
于 2013-11-08T16:14:32.653 回答
0

将您的查询变量替换为SELECT INSTEADINSERT

$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 !";
}
于 2013-11-08T16:05:54.023 回答