[英]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.