Reputation: 1
I'm trying to write a Top-10 list with categories but it doesn't work in the way i want it to. There's an array with a dynamic number (n) of items and want to loop each item in this array 10 times to write n*10 rows into a MySQL table. ($i also increments the games rank). If I echo, print_r or var_dump the code it works, but when I try to write it to the MySQL table it doesn't work.
Here's the code:
for ($i = 1; $i <= 10; $i++) {
foreach($titles as $val) {
$query .= "INSERT INTO charts (game_place, game_name, game_preweek, game_developer, game_release, game_link, game_image, game_category, charts_updated) VALUES (".$i.", '', '', '', '', '', '', '".$val."', '".time()."');";
mysql_query($query);
};
};
Does somebody know the answer to my problem?
Upvotes: 0
Views: 875
Reputation: 7795
$query = "INSERT INTO `charts`` (`game_place`, `game_category`, `charts_updated`) VALUES ";
foreach ($titles as $key => $val){
for ($i=1; $i<=10; $i++){
$query .= "(".$i.", '".$val."', ".time()."),";
}
}
$query = substr($query, 0, -1);//remove last comma
mysql_query($query);
Upvotes: 0
Reputation: 10732
$query .= "INSERT ....`
You're adding each new query onto the end of the previous query. That's going to produce invalid SQL after the first iteration. You just need to assign the query as:
$query = "INSERT ....`
You should also look at using PDO or mysqli_ instead - this sort of thing is an ideal use for a prepared statement.
Upvotes: 4