如何使用php检查MySQL数据库中是否已存在值

时间:2015-03-06 16:59:45

标签: php mysql database

我知道代码,但由于某些原因我不知道为什么它不会起作用 有人可以帮助我:( 代码

<?php
$servername = "server";
$username = "Dbname";
$password = "password";
$dbname = "name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
}
$j=$_SERVER['REMOTE_ADDR'];

$sql123 = "SELECT FROM Ip1 (IP) WHERE IP='$j'";
if(($sql123)>0)
   {
    echo"name already exists";
   }
 else
    {
   //insert query goes here
   $ipl = $_SERVER['REMOTE_ADDR'];
         $sql = "INSERT INTO Ip1 (IP)
         VALUES ('$ipl')";
        if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
        } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
           }
    }
$conn->close();
?>

即使数据库中存在相同的ip,它也始终显示“已成功创建新记录”! 我试过((mysqli_num_rows($ conn-&gt; query($ sql123)))&gt; 0){... 我得到这个警告:mysqli_num_rows()期望参数1是mysqli_result,给定布尔值

3 个答案:

答案 0 :(得分:3)

$sql123只是一个字符串,您不进行查询$conn->query($sql123)

$res = $conn->query($sql123);
if($res && mysqli_num_rows($res)>0){...

取代

if(($sql123)>0){...

答案 1 :(得分:0)

以这种方式使用您的查询:

$sql123 = "SELECT COUNT(*) as total_num FROM Ip1 (IP) WHERE IP='$j'";
$result = $conn->query($sql123);

if(($result['total_num']) > 0){
   echo"name already exists";
}

答案 2 :(得分:0)

您没有执行查询,您必须计算返回的结果。

尝试更改

if(($sql123)>0)

if((mysqli_num_rows($conn->query($sql123)))>0)

//编辑:

此外,您的查询需要更改为:

$sql123 = "SELECT IP FROM Ip1 WHERE IP='$j'";