简体   繁体   中英

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. I'm adding 100 positions to database through that code:

 $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" . 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. 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:

$pdo->lastInsertId(); 

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

This will echo the whole column "$Name $CatID" do what you want:

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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