嗨我有sql查询结果存储在数据库中。我必须检查是否有任何行包含字符串' N;'然后下一个sql语句应该执行。我有很多这样的字符串,这就是为什么要执行我的下一个sql语句。我尝试过以下代码但是当我尝试运行代码时它会进入无限循环。谢谢。 这是我的PHP代码:
while ($row = mysql_fetch_assoc($result)) {
$config= $row['configuration'];
if($config=='N;')
{
$sql="SELECT DISTINCT ad_news_texte.id, ad_news_texte.headline, ad_news.datum_archiv FROM autodo.ad_news_texte INNER JOIN autodo.ad_news_oe ON ad_news_texte.news_id = ad_news_oe.id_ad_news INNER JOIN autodo.ad_news ON ad_news_oe.id_ad_news = ad_news.id WHERE ad_news.datum_archiv BETWEEN curdate( ) - INTERVAL DAYOFWEEK( curdate( ) ) +28 DAY AND curdate( )";
$result = mysql_query($query, $myConnection);
}
else{
$html .= '<table id="news">
<a href="news.php?id=">
<p class="welcome-subheadline"> '. $config .'</p></a>
</table>';
}
}
答案 0 :(得分:2)
您在循环条件中使用$result
,并且还在循环中重新定义它。这里的行为很可能是未定义的。这样看(伪代码):
$result = perform some query
while($result has some rows) {
do some stuff
$result = perform some other query
}
while
路由正在使用该$result
值来跟踪它的位置以及它正在做什么。但是在循环内部,您将使用某些新查询的结果替换它。所以基本上,发生的事情是while
循环无法跟踪它(在您的情况下)导致无限循环的位置。
解决方案是重写循环,以便您不会破坏PHP用于跟踪的值。你如何做到这可能取决于循环周围的代码和循环本身,所以我不确定什么是最好的。这是一个解决方案(再次使用伪代码):
$keepLooping = true
while($keepLooping) {
$result = perform some query
do some stuff
if ($result meets some exit condition) {
$keepLooping = false;
}
}
答案 1 :(得分:1)
好的,我错过了一些信息,但无论如何我都会尝试解决你的问题:
如果您的sql fetch与循环中的sql语句相同,那么代码应该如下所示:(在这种情况下,我没有看到if语句的原因)
$sql="SELECT DISTINCT ad_news_texte.id, ad_news_texte.headline, ad_news.datum_archiv FROM autodo.ad_news_texte INNER JOIN autodo.ad_news_oe ON ad_news_texte.news_id = ad_news_oe.id_ad_news INNER JOIN autodo.ad_news ON ad_news_oe.id_ad_news = ad_news.id WHERE ad_news.datum_archiv BETWEEN curdate( ) - INTERVAL DAYOFWEEK( curdate( ) ) +28 DAY AND curdate( )";
$result = mysql_query($sql, $myConnection);
while ($row = mysql_fetch_assoc($result)) {
$config= $row['configuration'];
if($config=='N;')
{
// If the sql is the same no need for another fetch
}
else{
$html .= '<table id="news">
<a href="news.php?id=">
<p class="welcome-subheadline"> '. $config .'</p></a>
</table>';
}
}
在第二种情况下,当sql语句不同时,代码应该如下所示:
$result = mysql_query($sql, $myConnection);
while ($row = mysql_fetch_assoc($result)) {
$config= $row['configuration'];
if($config=='N;')
{
$sql2="SELECT DISTINCT ad_news_texte.id, ad_news_texte.headline, ad_news.datum_archiv FROM autodo.ad_news_texte INNER JOIN autodo.ad_news_oe ON ad_news_texte.news_id = ad_news_oe.id_ad_news INNER JOIN autodo.ad_news ON ad_news_oe.id_ad_news = ad_news.id WHERE ad_news.datum_archiv BETWEEN curdate( ) - INTERVAL DAYOFWEEK( curdate( ) ) +28 DAY AND curdate( )";
$result2 = mysql_query($sql2, $myConnection);
while ($row2 = mysql_fetch_assoc($result2)) {
//The rest of the code
}
}
else{
$html .= '<table id="news">
<a href="news.php?id=">
<p class="welcome-subheadline"> '. $config .'</p></a>
</table>';
}
}