PHP sql 查询无法替换更新所有行

PHP sql query not working to replace update all rows

提问人:Skipper 提问时间:11/17/2023 更新时间:11/17/2023 访问量:41

问:

尝试更新插入的特定state_id的表行有效,但出现错误,它没有使用正确的city_name....

所以这就是我们尝试过的,请记住我们仍在学习 PHP,所以任何帮助将不胜感激

它发生的情况是它对每一行使用相同的city_name而不是实际的行?

$selectquery = "SELECT * FROM `cities` WHERE `state_id` = 9";
$stmt = $conn->prepare($selectquery);
$stmt->execute();

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$city_name = !empty($row['city_name']) ? $row['city_name'] : '';

$new_key = "".$city_name." Businesses, ".$city_name." Business, ".$city_name." Tourism, .....";
$new_desc = "Find the best ".$city_name." Businesses. Find the best ".$city_name." Restaurants, ....";

$st3 = $pdo->prepare('UPDATE cities SET meta_desc = :desc, meta_key = :key WHERE state_id = 9');
$st3->execute([':desc' => $new_desc, ':key' => $new_key]);
}

为什么它没有遍历每一个?

php mysqli pdo sql-update

评论

1赞 aynber 11/17/2023
你是,你只是在每个循环中用相同的数据覆盖每个城市,所以你只能看到最后一个循环中的值。您可能希望更新使用城市 ID,而不是州。
0赞 Skipper 11/17/2023
您能给我们举个例子吗?当我们尝试这样做时,但它仍然为每一行使用了错误的city_name,如果有帮助,城市将按state_id分组
1赞 aynber 11/17/2023
好吧,如果每个城市都有一个 id,那么你会这样做 - 使用正确的列名,并确保在循环中获取正确的城市 id。将其作为参数传递,因为每行都不同WHERE id = :city_id
0赞 Skipper 11/17/2023
谢谢,我用这个得到了它 $st 3 = $pdo->prepare('UPDATE cities SET meta_desc = :d esc, meta_key = :key WHERE city_id = :id AND = 9');$st 3->执行([':d esc' => $new_desc, ':key' => $new_key, ':id' => $city_id]);state_id

答:

3赞 Skipper 11/17/2023 #1

多亏了@aynber的一些指导,我们得到了它,我们使用了以下内容

$selectquery = "SELECT * FROM `cities` WHERE `state_id` = 9";
    $stmt = $conn->prepare($selectquery);
    $stmt->execute();
    
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $city_name = !empty($row['city_name']) ? $row['city_name'] : '';
    $city_id = !empty($row['city_id']) ? $row['city_id'] : '';
    
    $new_key = "".$city_name." Businesses, ".$city_name." Business, ".$city_name." Tourism, P...";
    $new_desc = "Find the best ".$city_name." Businesses. Find the best ".$city_name." Restaurants, ...";
    
    $st3 = $pdo->prepare('UPDATE cities SET meta_desc = :desc, meta_key = :key WHERE city_id = :id AND `state_id` = 9');
    $st3->execute([':desc' => $new_desc, ':key' => $new_key, ':id' => $city_id]);
    }

我给你竖起大拇指,但不知道怎么做?

评论

0赞 ADyson 11/17/2023
仅供参考,可能只是......等。将空字符串放在文本的开头不会做任何事情(因为它是空的!$new_key = "".$city_name$new_key = $city_name