Jump to content

Recommended Posts

I'm trying to write a script (cronjob) that will fluctuate the prices of all the items at a random level (+/- .03% or so), but when I ran this, it changed all the prices to match row #1 and wiped out everything else. (in other words, everything is now the same price as row #1)

 

Thanks for any help!

 

$query = $db->execute("select `price` from `items`");
$item = $query->fetchrow();
$price1 = ceil($item['price']*1.1);
$price2 = floor($item['price']*.9);
$newprice = mt_rand($price1, $price2);
$q = $db->execute("update `items` SET `price`=$newprice");

Link to comment
https://forums.phpfreaks.com/topic/196678-fluctuation-of-prices/
Share on other sites

Hopefully, there is some unique ID for each row of the table.  You need to include that ID in the SELECT statement, loop through each row that is returned, and add a WHERE clause to the UPDATE.  Your current UPDATE has no WHERE clause so it is updating every row in the table with the same price.

Each has a unique ID, yeah. So, how would I include that in?

 

WHERE `id`=?" to the end of it?

 

I now have (just the rows that changed):

 

$query = $db->execute("select `id`, `price` from `items`");
$q = $db->execute("update `items`, `id` SET `price`=$newprice" );

Hmm... close.

 

It'll change the 1st row, but it doesn't change any of the following rows.

 

$query=$db->execute("select `id`,`price` from `items`");
$item = $query->fetchrow();
$id=$item["id"];
$price1 = ceil($item['price']*1.03);
$price2 = floor($item['price']*.97);
$newprice = mt_rand($price1, $price2);
$q=$db->execute("update `items` SET `price`=$newprice WHERE `id`=$id");

$query=$db->execute("select `id`,`price` from `items`");
while($item = $query->fetchrow())
{
$id=$item["id"];
$price1 = ceil($item['price']*1.03);
$price2 = floor($item['price']*.97);
$newprice = mt_rand($price1, $price2);
$q=$db->execute("update `items` SET `price`=$newprice WHERE `id`=$id");
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.