0

我有一个名为 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;
};
4

2 回答 2

1

请参阅 INSERT INTO ... ON DUPLICATE KEY UPDATE ... 语法:

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

于 2013-09-21T17:40:58.073 回答
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)");
于 2013-09-21T17:43:00.460 回答