gpt4 book ai didi

php mysql插入具有唯一id的报告

转载 作者:行者123 更新时间:2023-11-29 10:44:37 24 4
gpt4 key购买 nike

我正在尝试使用唯一的 ID 将新条目插入到我的数据库中。我的代码中的某个地方有错误,但我找不到它。你能帮忙吗?

自动增量不是选项

    $newConversationID = uniqid();

$checkID = $DBcon->query("SELECT * FROM tbl_conversations WHERE conversation_id=$newConversationID");
$countID = $checkID->num_rows;


while($countID) {

if ($countID==0) {
$DBcon->query("INSERT INTO tbl_conversations (conversation_id,user_id, date) VALUES('$newConversationID','$fromID',UNIX_TIMESTAMP())");break;
} else {

$newConversationID = uniqid();

$checkID = $DBcon->query("SELECT * FROM tbl_conversations WHERE conversation_id=$newConversationID");
$countID = $checkID->num_rows;

}

}

最佳答案

是的,错误出现在 where($countId) 中。假设您没有使用该键找到相似的行,您将在 $countId 中得到零,零等于 FALSE。所以 where 子句永远不会运行。

因此,如果新的 uniqueid 与该表中的任何现有键都不匹配,则 while 循环将不会运行!

如果新的 uniqueid 确实与现有行匹配,则 while 循环将运行,但只会执行 ELSE 条件,这实际上不会做任何有用的事情。

I am assuming you want to loop until you create a valid new uniqid and then store that row.

$qfind = "SELECT COUNT(conversion_id) FROM tbl_conversations WHERE conversion_id = ?";
$search = $mysqli->prepare($qfind);
$qinsert = "INSERT INTO tbl_conversations (conversion_id) VALUES(?)";
$insert = $mysqli->prepare($qinsert);

//loop till we end up with a new unique id
while(true) {
$id = uniqid();
$search->bind_param('s', $id);
$search->execute();
$result = $search->get_result();
$row = $result->fetch_array(MYSQLI_NUM);

if ($row[0] == 0) {
// we have a new unique index so store the row
$insert->bind_param('s', $id);
$insert->execute();

// we are all done here so break out of the while loop
break;
}
}

关于php mysql插入具有唯一id的报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44861456/

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