2013-09-21 20 views
0

我有一個名爲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; 
}; 
+0

你應該使用'mysql_real_escape_string()',而不是'用htmlspecialchars()'因爲[它是不是安全的MYSQL操作(http://stackoverflow.com/questions/7355639 /的確,用htmlspecialchars保護,這對MySQL的查詢)。 –

+0

你的意思是因爲sql注入使用htmlspecialchars是不安全的? – user1788736

+0

是的。 SQL注入可能是最常見的網站黑客之一。如果你很脆弱,有人會發現並攻擊你。 –

回答

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)"); 
+0

不要忘了['implode()'](http://us1.php.net/manual/en/function.implode.php)和['mysql_real_escape_string()'](http://us1.php .NET /手動/ EN/mysqli.real-逃生string.php)! –

+0

但如何將usernameVar,profPic,Idvar,standardResolution,imagePageLink,createdTimeVal,imageTags從數組中作爲變量,所以我在他們的select和insert語句中引用它們?在上面的例子中,名稱和值是什麼意思? – user1788736

+0

$ names和$ variables只是空字符串。 @MisterMelancholy我通常不使用implode,因爲它必須遵循相同的規則而不管數據類型 - 使用上面的代碼,您可以輕鬆地將其擴展爲支持不帶''的數值。 –