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

时间:2017-07-01 13:24:30

标签: php mysql unique-id

我正在尝试使用唯一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;

        }

    }

2 个答案:

答案 0 :(得分:2)

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

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

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

  

我假设你要循环,直到你创建一个有效的新uniqid,然后存储该行。

$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;
    }
}

答案 1 :(得分:-1)

我认为你有一个逻辑错误

让我们假设代码

$countID = $checkID->num_rows;

返回1

所以条件如果不执行

以及

$countID = $checkID->num_rows;

返回1而迭代器wille不执行