MySQL not inserting all rows
I'm moving posts from my WP blog into a custom website. I made a script to pull out needed columns from the WP SQL-dump, and then loop it into a newly created tabl开发者_运维知识库e. Both the WP table and my database and the custom table uses UTF-8. I've counted the rows I'm getting, both before and after executing the loop inserting the new info. The number of posts is 427, and this is the correct number of posts. However, in the database only 234 posts get inserted, and I suspect it is MySQL not being able to insert certain posts, but I have no idea why. Here is the code:
<?php
$con = mysql_connect('localhost', 'root', 'PASSWORD');
$select = mysql_select_db('blog');
mysql_query("
CREATE TABLE posts (
id int(9) NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
title varchar(250) NOT NULL,
content longtext NOT NULL,
date varchar(90) NOT NULL,
deleted int(1) NOT NULL
)") or die(mysql_error());
$query = mysql_query("SELECT post_date, post_title, post_content FROM sspe_posts WHERE post_type = 'post' AND post_status = 'publish'");
$i = 0;
while ($row = mysql_fetch_array($query)) {
$oldPosts[$i]['title'] = $row['post_title'];
$oldPosts[$i]['date'] = $row['post_date'];
$oldPosts[$i]['content'] = $row['post_content'];
$i++;
}
$size = count($oldPosts);
for ($x = 0; $x < $size; $x++) {
$title = $oldPosts[$x]['title'];
$content = $oldPosts[$x]['content'];
$date = $oldPosts[$x]['date'];
$query = mysql_query("INSERT INTO posts (title, content, date, deleted) VALUES ('$title', '$content', '$date', 0)");
}
echo $x;
Michael is right about your script not checking whether the query succeeded or failed.
You also have "treat" the parameters you're putting as string literals into the statement with mysql_real_escape_string()
for ($x = 0; $x < $size; $x++) {
$title = mysql_real_escape_string($oldPosts[$x]['title']);
$content = mysql_real_escape_string($oldPosts[$x]['content']);
$date = mysql_real_escape_string($oldPosts[$x]['date']);
$query = "
INSERT INTO
posts
(title, content, date, deleted)
VALUES
('$title', '$content', '$date', 0)
";
$result = mysql_query($query);
if ( !$result ) {
die(mysql_error()."\n".$query);
}
}
But you problem is easier solved with something like
INSERT INTO
posts
(title, content, date, deleted)
SELECT
post_title, post_content, post_date, 0
FROM
sspe_posts
WHERE
post_type = 'post'
AND post_status = 'publish'
see http://dev.mysql.com/doc/refman/5.0/en/insert-select.html
If you can lock your table without troubles I think it's better to run:
$query = mysql_query("INSERT INTO posts (title, content, date, deleted)
SELECT post_date, post_title, post_content, 0 FROM sspe_posts
WHERE post_type = 'post' AND post_status = 'publish'");
And you will avoid loop.
精彩评论