This is actually my very first code. Im trying to add new posts to my Wordpress Site.
Mysql query will return 4035 rows that have all the details to insert the new post.
The problem : Loop wont ever stop! It will reach 4035 row and then start all over from the 1st row
Things I tried to make it stop:
- Added -
if ($loopstimes > 4400) {break;}
- Limited mysql query to 4050 rows
The weird parts:
- When i limit mysql query to
LIMIT 900
, Everything works PERFECTLY. The loop stops when 900 post are added, if i add 950, the script will add 943 posts and then will give meFatal error "Maximum execution time reached"
. Then the script stops. - I increase the "Maximum execution time" to 300 Sec and increase the memory from 128 to 256MB, i use my query without LIMIT and then the Loop wont ever stop.
Is my code problematic? Or is server issue?
<?PHP
$username = "xxxx";
$password = "xxxx";
$hostname = "localhost";
$loopstimes = 0;
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("xxxx_xxxx",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
// Query to get all names
$result = mysql_query("SELECT DISTINCT names_list.* ... LIMIT 4050");
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
//fetch the data from the database
while ($row = mysql_fetch_array($result)) {
$p_name= $row["p_name"];
$category= $row["gcategory"];
$subcategory= $row["subcategory"];
$ase_date= $row["ase_date"];
//Fix the (') to prepare it for mysql query
$pp_name = $p_name;
$newp_name = str_replace("'","''",$p_name);
//Query to count results
$minprice = mysql_query("SELECT ... WHERE Product_p_name = '$newp_name' AND ORDER BY product_price_usd");
$countss = mysql_num_rows($minprice);
if($minprice === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$rowm = mysql_fetch_array($minprice);
$minprice = '$'.$rowm["product_price_usd"];
// Create post object
$my_post = array(
'post_title' => 'My title...',
'post_status' => 'publish',
'post_author' => 1
);
// Insert the post into the database
$post_id = wp_insert_post( $my_post );
// Add Advanced Custom field values
update_field( "field_552fc3f84b43r", $p_name, $post_id );
//Regex the date to keep just the year
if (preg_match("/20.*/", $ase_date, $matches)) {
$ase_year = $matches[0];
}
//Insert Tags for Custom Taxonomies
wp_set_post_terms( $post_id, $audio_subcategory, 'subcategory-cpt', false );
wp_set_post_terms( $post_id, $fex_pro_rg, 'fex-pro-cpt', false );
$loopstimes++;
if ($loopstimes > 4400) {break;}
echo 'Post added!, '.$post_id.'<br>';
echo $loopstimes;
}
//close the connection
mysql_close($dbhandle);
echo 'Finish';
?>