multiple arrays foreach loop mysql
I have this :
foreach($textnode as $key => $value) {
$value = stripslashes($value);
$value = mysql_real_escape_string($value, $con);
mysql_query("INSERT INTO paragraphs (textnodes, url)
VALUES ('$va开发者_如何学Clue', '$url')");
}
My table has three columns (textnodes, ytext, and url)
textnode and ytext are both arrays.....can I do this for two arrays?
I think what you want is to use a normal for loop instead:
for($i=0;$i<sizeof($textnode);$i++){
$textnode[$i] = stripslashes($textnode[$i]);
$textnode[$i] = mysql_real_escape_string($textnode[$i], $con);
$ytext[$i] = stripslashes($ytext[$i]);
$ytext[$i] = mysql_real_escape_string($ytext[$i], $con);
mysql_query("INSERT INTO paragraphs (paragraphs, ytext, url)
VALUES ('$textnode[$i]', '$ytext[$i]', '$url')");
}
That way you can loop through both at once (not 100% sure that's what you were asking, but it's my best guess).
I haven't tested the code above but it should work. However the style it follows and the style you've shown above isn't very good. Here are a few improvements that could be made:
Instead of making a separate query for each insert, do all the inserts in one query. This is better because there is only overhead for 1 query instead of $i queries.
Abstract away the DB. Currently it seems that you are mixing business logic with DB logic. I can see this because you are escaping strings of text with specific purposes (textnode and ytext and url) and inserting them with a mysql query. Instead it would be prudent to abstract away the query so that the business logic isn't coupled with the db logic.
A smaller note - you shouldn't have to call stripslashes. If you are using magic quotes, disable it immediately instead, as it is deprecated and is considered a bad practice now.
Have you tried serialize?
It converts your array into a "storable" form (string). When you select from your table again unserialize
will convert the string back into an array.
Just guessing, your question is somewhat unclear ...
精彩评论