什么是跳过MySQL INSERT的正确方法

时间:2012-09-17 19:30:08

标签: php mysql foreach

我有一个foreach语句循环遍历JSON数据并将内容插入MySQL。如果为$ author字符串显示特定的用户名,我想跳过插入。以下方法是正确的还是在数据库级别处理更好?

foreach ($response['data'] as $data) {      
        $id = $data['id'];
        $created_time = $data['created_time'];
        $thumbnail = $data['images']['low_resolution']['url'];
        $author = $data['user']['username'];
        $caption = mysql_real_escape_string($data['caption']['text']);
        $link = $data['link'];
        $likes = $data['likes']['count'];

        if ($author == 'USERNAME') {
            mysql_close($con);
        } else {

        $query = "INSERT IGNORE INTO pbr (id, created_time, thumbnail, author, caption, link, likes, hash) VALUES ('$id', '$created_time', '$thumbnail', '$author', '$caption', '$link', '$likes', '$hash')";
        $result = mysql_query($query) or die(mysql_error());        

    mysql_close($con);
        }
    }

1 个答案:

答案 0 :(得分:3)

为什么在每次循环迭代时关闭SQL连接?

为什么不简单地做:

if ($author == 'USERNAME')
  continue; // next iteration

$query = "INSERT IGNORE INTO pbr (id, created_time, thumbnail, author, caption, link, likes, hash)
  VALUES ('$id', '$created_time', '$thumbnail', '$author', '$caption', '$link', '$likes', '$hash')";
$result = mysql_query($query) or die(mysql_error());

BTW你应该将参数绑定到你的查询,或者至少使用 mysql_real_escape_string()否则会出现包含引号的值的问题(目前,你只对变量 $ caption ,我猜 $ link $ thumbnail $ username 也可以包含单引号。