gpt4 book ai didi

php - 检查 ID 是否已经在数据库中,如果是,请不要再次插入它

转载 作者:行者123 更新时间:2023-11-29 04:35:43 25 4
gpt4 key购买 nike

当我运行带有空数据库的页面时,它会正确插入数据。当我再次运行该页面时,它显示数据库中已经有一个 ID,但它还是插入了它。不知道如何或为什么,但我已经尝试了 if 语句中 bool 值的所有组合,但无法正确选择。

//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

}

最佳答案

你为什么要搞得这么复杂。只需做这样的事情:

$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 用户设置一个密码。

关于php - 检查 ID 是否已经在数据库中,如果是,请不要再次插入它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42565766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com