我有一個名爲MyArray的數組我想將其數據插入到MySQL中,但首先需要檢查它是否已存在於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;
};
你應該使用'mysql_real_escape_string()',而不是'用htmlspecialchars()'因爲[它是不是安全的MYSQL操作(http://stackoverflow.com/questions/7355639 /的確,用htmlspecialchars保護,這對MySQL的查詢)。 –
你的意思是因爲sql注入使用htmlspecialchars是不安全的? – user1788736
是的。 SQL注入可能是最常見的網站黑客之一。如果你很脆弱,有人會發現並攻擊你。 –