行名称基于mysql中的列ID


Row name based on column ID in mysql

我有一个小问题。我是mysql的新手,我正在创建一些猫的基本数据库。我通过这个代码向数据库添加了100个职位:

 $result_set = $pdo->prepare("INSERT INTO koty2 (name, age, breed, author, tag, image) VALUES (:name, :age, :breed, :author, :tag, :image)");
 $result_set->execute(array(
':name' => $name,
':age' => $age,
':breed' => $breed,
':author' => $author,
':tag' => $tag,
':image' => $image
 ));
 for ($i=0; $i<100; $i++) {
 $result_set->execute(array(
':name' => $name,
':age' => $age,
':breed' => $breed,
':author' => $author,
':tag' => $tag,
':image' => $image
 ));

我尝试了多种方法将$name添加到具有行ID的数据库中,该行ID会自动递增,因此它将是"Name+ID"。到目前为止,我失败了。有人能告诉我怎么做吗?

谢谢。

一个解决方案是,您可以首先插入要插入的数据,获得最后插入的ID,然后通过连接名称和ID来更新名称。参见以下代码:

    // insert first
    $result_set = $pdo->prepare("INSERT INTO koty2 (name, age, breed, author, tag, image) VALUES (:name, :age, :breed, :author, :tag, :image)");
    $result_set->execute(array(
        ':name' => $name,
        ':age' => $age,
        ':breed' => $breed,
        ':author' => $author,
        ':tag' => $tag,
        ':image' => $image
    ));
    // get the inserted ID
    $last_ins_id = $pdo->lastInsertId();
    // update the inserted name
    $update_row = $pdo->prepare("UPDATE koty2 SET name = :name WHERE ID = :id");
    $update_row->execute(array(
        ':name' => $name . $last_ins_id,
        ':id' => $last_ins_id
    ));

我不确定这是否是最好的解决方案,但这种逻辑仍然可以完成

的工作

如果您想在每次插入新Cat(xD)时获得插入的自动递增ID,您可以使用:

$pdo->lastInsertId(); 

http://php.net/manual/en/pdo.lastinsertid.php

这将呼应整列"$Name$CatID"做你想做的事:

$stmt = $pdo->query("SELECT name, catID FROM koty2");
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
  print "Name: <p>{$row[0] $row[1]}</p>";
}

有关详细信息,请查看:http://php.net/manual/en/pdostatement.fetch.php