MySQL插入循环只插入一行

时间:2013-07-27 00:59:44

标签: php mysql insert mysqli while-loop

我正在从一个旧表到Wordpress注释表进行一次性数据导入(因此开销不是问题)。我循环遍历旧表,使用php调整新表的一些数据,然后执行每个插入。它只会插入第一行。如果我再次运行代码,它会插入相同的第一行,所以我认为没有主键问题。

require('wp-config.php');

$con=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME); 

$result = mysqli_query($con,"SELECT *
    FROM user_import u, wp_posts p, wp_postmeta m
    WHERE p.ID = m.post_id
    AND m.meta_key = 'fanfic_id'
    AND m.meta_value = u.fanfic_id");

while($row = mysqli_fetch_array($result))
  {
    $nick=$row['user_nickname'];
    $ip=$row['user_ip_address'];
    $date=strToTime($row['user_fanfic_date']);
    $date2=strftime('%Y-%m-%d 12:00:00',$date);
    $gmt=strftime('%Y-%m-%d 12:00:00', $date);
    $datemine = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));

    $fanfic_id=$row['fanfic_id'];

    $getPostID="SELECT post_id FROM wp_postmeta WHERE meta_key='fanfic_id' and meta_value=$fanfic_id";

    $result2 = mysqli_query($con,$getPostID );

    while($row2 = mysqli_fetch_array($result2)){
      $post_id=$row2['post_id'];

    }

    $review=$row['user_fanfic_review'];
    $sql="INSERT INTO wp_comments(comment_approved, user_id, comment_post_id, comment_author, comment_author_ip, comment_date, comment_date_gmt, comment_content)
      VALUES(1, 0, $post_id,'$nick','$ip', '$date2', '$gmt', '$review') ";

    $result = mysqli_query($con,$sql);

  }

mysqli_close($con);

2 个答案:

答案 0 :(得分:3)

我相信因为这条线

$sql="INSERT INTO wp_comments(comment_approved, user_id, comment_post_id, comment_author, comment_author_ip, comment_date, comment_date_gmt, comment_content)
  VALUES(1, 0, $post_id,'$nick','$ip', '$date2', '$gmt', '$review') ";
$result = mysqli_query($con,$sql); // <--- this line.

因为您将SELECT的$result重新分配给INSERT的结果。你能把这条线改成这个吗?

 mysqli_query($con,$sql);

答案 1 :(得分:0)

此时存在问题:

$getPostID="SELECT post_id FROM wp_postmeta WHERE meta_key='fanfic_id' and meta_value=$fanfic_id";

$result2 = mysqli_query($con,$getPostID );

while($row2 = mysqli_fetch_array($result2)){
 $post_id=$row2['post_id'];
}

你在做什么总是在循环中获得相同的post_id。这意味着每当第一个while循环while($row = mysqli_fetch_array($result))运行第二个while时,同时获取相同的数据并继续插入操作。

P.S。考虑将$wpdb对象用于wordpress数据库操作http://codex.wordpress.org/Class_Reference/wpdb