0

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);
    }
}

?>
4
  • Do you mean it updates all images, or just one? If all you need a where clause. Commented Dec 28, 2015 at 5:27
  • Use where condition in your update query to update particulate row Commented Dec 28, 2015 at 5:27
  • You probably want SELECT my_image_url AS image, id FROM my_image then use the id to update the particular row. You also should use prepared statements, this could potentially get you injected. Commented Dec 28, 2015 at 5:28
  • Thanks for the comments, Yes I need a condition here. Now it is working fine after the condition (where clause). Commented Dec 28, 2015 at 6:04

2 Answers 2

1

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}";
Sign up to request clarification or add additional context in comments.

1 Comment

I made a small change here, I used '".$img_url."' instead of {$img_url}. Now it is working correctly.
0

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)";

1 Comment

Explain why so.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.