简体   繁体   English

mysql中基于列ID的行名

[英]Row name based on column ID in mysql

I have a little problem.我有一个小问题。 I'm very new to mysql and I'm creating some sort of basic database of cats.我对 mysql 很陌生,我正在创建某种基本的猫数据库。 I'm adding 100 positions to database through that code:我正在通过该代码向数据库添加 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
 ));

I tried multiple ways of adding the $name to the database with row's ID which is auto incremented - so it would be "Name+ID" .我尝试了多种方法将 $name 添加到数据库中,行的 ID 是自动递增的 - 所以它会是"Name+ID" So far I failed.到目前为止我失败了。 Can somebody tell me how to do this?有人能告诉我怎么做吗?

Thank you.谢谢你。

One work around is, you can first insert the data you want to insert, get the last inserted ID, then just update the name by concatenating the name and ID.一种解决方法是,您可以先插入要插入的数据,获取最后插入的 ID,然后通过连接名称和 ID 来更新名称。 See below code:见下面的代码:

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

Im not sure if this is the best solution but this logic will still do the work我不确定这是否是最好的解决方案,但这个逻辑仍然可以工作

If you want to get the inserted auto-incremented ID everytime you insert a new Cat( xD ), you can use:如果要在每次插入新 Cat( xD ) 时获取插入的自动递增 ID,可以使用:

$pdo->lastInsertId(); 

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

This will echo the whole column "$Name $CatID" do what you want:这将回显整个列“$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>";
}

For more, check: http://php.net/manual/en/pdostatement.fetch.php有关更多信息,请查看: http : //php.net/manual/en/pdostatement.fetch.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM