我有一个名为MyArray的数组我希望将其数据插入到mysql中,但首先需要检查它是否已存在于mysql中。任何人都可以告诉我如何循环数组以及如何引用数组中的每个变量然后将这些数据插入到mysql中?
$MyArray[] = array(
"usernameVar" => htmlspecialchars($usernameVar),
"profPic" => htmlspecialchars($profPic),
"idVar" => htmlspecialchars($idVar),
"standardResolution" => htmlspecialchars($standardResolution),
"imagePageLink" => htmlspecialchars($imagePageLink),
"createdTimeVal" => htmlspecialchars($createdTimeVal),
"imageTags" => htmlspecialchars($imageTags),
);
$MyArray = array_reverse( $MyArray );
//now i need to loop through array and insert non duplicate data in to mysql
$result = mysql_query("SELECT imageUrl FROM mytable WHERE imageUrl = '$standardResolution'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if(mysql_num_rows($result) == 0) {
$j++;
echo "<a href='".$imagePageLink."'><img src='".$standardResolution."' width='150' height='150' border='0'></a><br> ";
// row not found, do stuff...
echo "New Users(".$i."):";
echo "<br>User Name(".$i."):".$usernameVar;
$result2 = mysql_query("INSERT INTO mytable (ID, username, profile_picture, instaId, imageUrl,imagePageURL, CreatedTime, imageTags, date) VALUES('$ID','$usernameVar','$ProfilePicVar','$idVar','$standardResolution','$imagePageLink','$createdTimeVal','$imageTags',NOW())");
if (!$result2) {
die('Invalid query: ' . mysql_error());
}
}
else
{
$m++;
// do other stuff...
echo "Already Added Users(".$i."):";
echo "<br>User Name(".$i."):".$usernameVar;
};
答案 0 :(得分:1)
请参阅INSERT INTO ... ON DUPLICATE KEY UPDATE ...语法:
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
答案 1 :(得分:0)
您可以使用PHP中的foreach遍历数组:
foreach($MyArray as $key=>$value){
....
}
从数组中插入有点复杂,但原则上,你遍历数组中的每个变量并创建一个字符串。
foreach($MyArray as $key=>$value){
$names .= $key.",";
$values .= "'$value',";
}
$names = substr($names, 0, strlen($names) - 1);
$values = substr($values, 0, strlen($values) - 1);
然后做:
mysql_query("INSERT INTO table ($names) VALUES($values)");