2

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

1 回答 1

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());

顺便说一句,您应该将参数绑定到您的查询,或者至少使用mysql_real_escape_string()否则会遇到包含引号的值的问题(目前,您只对变量$caption这样做,我猜$link$thumbnail$username可以包含单个引号)。

于 2012-09-17T19:33:27.613 回答