0

I'm trying to make a cronjob, that deletes everything from a table then refills it with random values from another table, my problem is it is only inserting 1 row, when I want it to insert 24 different ones that it grabs from the other table. any help will be very much appreciated. btw I know mysql is deprecated.

$result = mysql_query("SELECT * FROM market ORDER BY RAND() LIMIT 24"); while($row = mysql_fetch_array( $result )) { mysql_query("TRUNCATE TABLE market2"); mysql_query("INSERT INTO `market2` (`id`, `pokemon`, `price`, `type`) VALUES ('".$row['id']."', '".$row['pokemon']."', '".$row['type']."', '".$row['price']."') "); } 

Is the fixed version for anyone else that has this question.

$result = mysql_query("SELECT * FROM market ORDER BY RAND() LIMIT 24"); mysql_query("TRUNCATE TABLE market2"); while($row = mysql_fetch_array( $result )) { mysql_query("INSERT INTO `market2` (`id`, `pokemon`, `price`, `type`) VALUES ('".$row['id']."', '".$row['pokemon']."', '".$row['type']."', '".$row['price']."') "); } 
2
  • You need to loop through $row and insert each time. It would be much better with a prepared statement though - one query sent to MySQL, and loop through just the variables instead. Commented Jan 22, 2014 at 21:14
  • 2
    put the truncate statement before your while Commented Jan 22, 2014 at 21:18

1 Answer 1

2

regardless on whether I agree to your methodology, your problem is that you are truncating with each loop. To fix please use the following:

$result = mysql_query("SELECT * FROM market ORDER BY RAND() LIMIT 24"); mysql_query("TRUNCATE TABLE market2"); while($row = mysql_fetch_array( $result )) { mysql_query("INSERT INTO `market2` (`id`, `pokemon`, `price`, `type`) VALUES ('".$row['id']."', '".$row['pokemon']."', '".$row['type']."', '".$row['price']."') "); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.