【发布时间】:2023-03-23 09:40:02
【问题描述】:
这实际上是我的第一个代码。我正在尝试向我的 Wordpress 网站添加新帖子。
Mysql 查询将返回 4035 行,其中包含插入新帖子的所有详细信息。
问题:循环永远不会停止! 它将到达 4035 行,然后从第一行重新开始
我试图让它停止的事情:
- 已添加 -
if ($loopstimes > 4400) {break;} - 将 mysql 查询限制为 4050 行
奇怪的部分:
- 当我将 mysql 查询限制为
LIMIT 900时,一切正常完美。当添加 900 个帖子时循环停止,如果我添加 950,脚本将添加 943 个帖子,然后会给我Fatal error "Maximum execution time reached"。然后脚本停止。 - 我将“最大执行时间”增加到 300 秒,并将内存从 128 增加到 256MB,我使用没有 LIMIT 的查询,然后循环永远不会停止。
我的代码有问题吗?还是服务器问题?
<?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';
?>
【问题讨论】:
-
请stop using
mysql_*functions。它们不再被维护并且是officially deprecated。改为了解prepared statements,并使用PDO。 -
首先尝试使用mysqli_*,因为mysql_*现在被贬低了。
-
Chuck Norris 在早餐时吃
mysql_*函数。 -
没有看到提供
while循环的 SQL 语句,我不确定我们是否真的能回答这个问题