检查ID是否已存在于数据库中,如果不是再次插入ID

时间:2017-03-02 20:55:19

标签: php mysql function mysqli

当我使用空数据库运行页面时,它将正确插入数据。当我再次运行页面时,它会显示数据库中已有ID,但无论如何它都会插入它。不确定如何或为什么,但我已经尝试了if语句中的每一个布尔组合,并且无法正确地选择它。

//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database: 
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

//Ask the database for some sweet, sweet data: 
$stmt1 = "SELECT orderID FROM orders";
$result = $mysqli->query($stmt1);

//flag (we want to believe that there are no similar IDS so lets make it true):
$flag = true;

//while we got some data, display that shit
while ($row = $result->fetch_assoc()) {
    //asign data to variable:
    $rowOrderID = $row['orderID'];

    //Does it match? if it does set the flag to false so it doesnt get inserted. 
    if ($rowOrderID == $orderID) {
        echo "Row ID" . $row["orderID"] . " Passed ID: " . $orderID . "<br>";
        echo "This order is already in the database" . "<br>";
        $flag = false;
    }
}
//hand the flag over to who ever needs it
return flag;
}

if (checkOrderID($orderID) == true) {
    //some mysql insert logic here

}

2 个答案:

答案 0 :(得分:3)

你为什么要这么复杂?做这样的事情:

$con=mysqli_connect("localhost","root","","price");
$check_query = mysqli_query($con,"SELECT * FROM orders WHERE orderID = $orderID");
if (mysqli_num_rows($check_query) == 0) {
    //mysql insert logic here
}

(当然注意到你也会有你的连接逻辑)


注意:您正在以面向对象的方式使用Mysqli,但在此示例中,我没有使用面向对象的数据库连接方式。必须将连接变量$con传递给mysqli_query()方法。

另外......随机附注,但为root mysql用户提供密码通常是个好主意。

答案 1 :(得分:1)

这里有更好和更短,但请尝试全局使用数据库连接,而不是在您的方法中,并尝试使用预准备语句。但除了那些你可以使用以下代码。

//pass in an ID to compare:
function checkOrderID($orderID) {
    //Connect to the database: I suggest use global DB connection 
    $mysqli = new mysqli("localhost", "root", "", "price");
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    //gets recodrs based on $orderID passed to this method
    $stmt1 = "SELECT * FROM orders where orderID=$orderID"; //Try to use prepared statement
    $result = $mysqli->query($stmt1);
    //Store number of rows found
    $row_count = $result->num_rows;
    if($row_count>0){
        return true;
    }
    else{
        return false;
    }
}
相关问题