Jump to content

MySQL Update with Array


fishboy

Recommended Posts

Hi all,

 

I'm fairly new to php/MySQL and am trying update 1900 records using an array. I want to change an image file pointer based on looping through a list of product IDs. Here's a code example:

 

<?php

$con = mysql_connect("mydbserver","dbuname","dbpass");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("dbname", $con);

$prod_id = array("id1","id2");

foreach($prod_id as $value);
{
$query = "Update products SET products_image = 'image.gif' WHERE products_id = $value";
$rt=mysql_query($query);
echo mysql_error();

if($rt){echo " It worked! ";}
else {echo " It failed! ";} 
}

mysql_close($con);

?>

 

I receive an "It worked!" message, but the db is not updated.  Any help is appreciated! Thanks!

Link to comment
https://forums.phpfreaks.com/topic/121760-mysql-update-with-array/
Share on other sites

it's best to get into the habit of single-quoting all values (strings and numbers) in SQL:

 

$query = "Update products SET products_image = 'image.gif' WHERE products_id = '$value'";

 

Thanks; I wondered about that. Made the change and got the same result.

okay. i would echo out the SQL to make sure it's what i expect:

 

$query = "Update products SET products_image = 'image.gif' WHERE products_id = '$value'";
echo "query: $query<BR>";
$rt=mysql_query($query) or die("query failed: $query");

 

...then copy/paste the query into phpMyAdmin (or whatever) to see if it updates as expected.

okay, my code now works like this:

<?php

$con = mysql_connect("mydbserver","dbuname","dbpass");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("dbname", $con);

$prod_id = array("id1","id2");

foreach($prod_id as $value);
{
$query = "Update products SET products_image = 'image.gif' WHERE products_id = '$value'";
echo "query: $query<BR>";
$rt=mysql_query($query) or die("query failed: $query");

if($rt){echo " It worked! ";}
else {echo " It failed! ";} 
}

mysql_close($con);

?>

 

I tested with just two items in the array, as it is above, and I get an "It worked!" message, but it only updated the second item.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.