开发者

PHP add many rows to database

I have problem with database. I want to add about 10 new rows after pageload. It should check if there is an article with id (that is actually loading). If its not, add 10 of that id with different tag id.

$sprawdz = "SELECT id_artykulow FROM tag_art WHERE id_artykulow='".$_GET['id']."' " ;
$miasto = mysql_query($sprawdz);   
$a = mysql_num_rows($miasto); 
while ($a<=10){ 
$zm = "SELECT id FROM tag_content ORDER BY RAND() LIMIT 1开发者_如何学编程";
$sw = mysql_query($zm);
while($row3=mysql_fetch_array($sw)){
$zmienna = "INSERT INTO tag_art(id_artykulow, id_tagow) VALUES ('".$_GET['id']."', '".$row3['id']."' ) ";
$cokolwiek = mysql_query($zmienna);
}
$a++; 
}  

There is two tables. One tag_content with id (of the tags), and another tag_art with id_artykulow (= id of the article) and id_tagow (id of the tag taken from tag_content) Don't know why, but it doesn't add 10 rows (it should be for example ten id_artykulow = 10, with different id_tagow). How to fix it?

Thx for help and let me know if u need more informations (like more code etc.)


why do you have 2 while loops? cant you just replace

while ($a<=10){ 
$zm = "SELECT id FROM tag_content ORDER BY RAND() LIMIT 1";

with

if ($a<=10){ 
$zm = "SELECT id FROM tag_content ORDER BY RAND() LIMIT " . (10-$a);

or just let the databse do all the work by:

$query = "INSERT INTO tag_art(id_artykulow, id_tagow) SELECT '".$_GET['id']."', id  FROM tag_content ORDER BY RAND() LIMIT " . (10-$a);

(and i would also recomendate protection agains sql-injections, mysql_real_escape_string())


Or let the database do all the work:

// store id as mysql-variable, but let php force it to an integer first
mysql_query("SET @id = " . (int) $_GET['id']);

// calculate how many new art we need, to get 10, using greatest to avoid negative numbers
mysql_query("SELECT @art_needed := GREATEST(0, 10 - COUNT(*)) FROM tag_art WHERE id_artykulow = @id");

// Need to use prepere to be able to have an mysql-variable as limit
mysql_query("PREPARE art_stmt FROM 'INSERT INTO tag_art(id_artykulow, id_tagow) SELECT ?, id FROM tag_content ORDER BY RAND() LIMIT ?'");

// execute the query using the mysql-variables
mysql_query("EXECUTE art_stmt USING @id, @art_needed");

just reread my old answer, and no longer agrees with "or just let the databse do all the work by" for that answer, the database could do alot more.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜