2013-07-27 157 views
0

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

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

你为什么不使用wordpress数据库对象'$ wpdb'? http://codex.wordpress.org/Class_Reference/wpdb – Konsole

+0

'$ getPostID'查询是否返回多行?因为你在循环中获取结果,但每次都覆盖相同的变量。 – Barmar

+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到插入的结果。你能改变这条线吗?

mysqli_query($con,$sql); 
+0

或者叫这个'$ result3',这样你就可以测试它的成功。 – Barmar

+0

@Barmar,真的。但是,在他的代码中,他没有检查它是否成功,所以我只是寻求最小代码。 :D – invisal

+0

该值从不使用。除非在使用mysqli_query()的结果的循环中稍后添加更多代码,否则应该将其更改为invisal建议的内容。 – Landstander

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))运行第二个时,获取相同的数据并继续插入操作。

P.S.考虑使用$wpdb对象进行wordpress数据库操作http://codex.wordpress.org/Class_Reference/wpdb

+1

我打算发表相同的答案,但我怀疑这个查询只返回一行。我看到很多人习惯性地在循环中调用'fetch',即使对于唯一的查询。这就是为什么我在发布前在评论中询问了上述内容。 – Barmar