[英]MySQL and PHP: Getting a SUM from a row in column A based on a DATE from column A joined by an ID in column B?
[英]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 是自動遞增的 - 所以它會是"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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.