WP Learner
WP Learner

Reputation: 830

UPDATE query inside a while loop php

I need to grab images from an URL then change the URL into another. Here is my code for that. But it is not working as I expected. It is do change only one image. Others won't.

Here is my code,

<?php

include_once('db-conn.php');

$query = "SELECT my_image_url AS image FROM my_image";
$result = mysqli_query($mysqli, $query) or trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($mysqli), E_USER_ERROR);

if($result) {
    while($row = mysqli_fetch_assoc($result)) {
        $img_url = $row['image'];
        $content = file_get_contents($img_url);
        $img_name = basename($img_url);
        file_put_contents($img_name, $content);
        $query = "UPDATE `my_image` SET `my_image_url` = 'http://localhost/img/".$img_name."'";
        $result2 = mysqli_query($mysqli, $query) or trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($mysqli), E_USER_ERROR);
    }
}

?>

Upvotes: 0

Views: 1247

Answers (2)

jitendrapurohit
jitendrapurohit

Reputation: 9675

Change the query to the below one so as to update the column for the grabbed value

$query = "UPDATE `my_image` 
  SET `my_image_url` = 'http://localhost/img/".$img_name."' 
  WHERE `my_image_url` = {$img_url}";

Upvotes: 1

roullie
roullie

Reputation: 2820

you should add a condition to your update query

$query = "UPDATE `my_image` SET `my_image_url` = 'http://localhost/img/".$img_name."' where (YOUR CONDITION HERE)";

Upvotes: 0

Related Questions