如何在数据库中找不到值时断开循环

时间:2016-03-03 05:36:27

标签: php mysql wordpress

<?php

$str = get_the_ID(); //this is  getting id in wordpress index.php page
$value = 0;
$count = 0;
$sql1 = "SELECT * FROM wphg_mr_rating_item_entry where post_id='" . $str . "'";
$result1 = $wpdb->get_results($sql1) or die(mysql_error());

foreach ($result1 as $results1) {
    //if(!empty($results1->rating_item_entry_id)) {
    if (!$wpdb->show_errors($results1->rating_item_entry_id)) {

        $sql = "SELECT * FROM wphg_mr_rating_item_entry_value where rating_item_entry_id='" . $results1->rating_item_entry_id . "'";
        $result = $wpdb->get_results($sql) or die(mysql_error());

        foreach ($result as $results) {
            $sum = $results->value . "<br/>";
            $sum1 = $results->value . "<br/>";
            //$sum[]= array_push($sum,$value);   
            //echo count($sum+=$value);
            //print_r($value);  
            $count+=count($sum1);
            $value+= $sum;
        }
    } else {

        break;
    }
}


echo $value;
echo $count;
$value = $value / $count;
?>

当$ str =&#34;这是id&#34;我们正在使用根据匹配来获取数据。 例如:就像你的id = = 26,其中数据在表中找到,这是正常的。 但如果在这里你的帖子ID数据在数据库中找不到,那么一切都搞砸了。

请帮助我,我想在数据库表中运行数据成功运行时。但如果数据根据id循环中断不匹配,也会继续下一个id。

thnaks

1 个答案:

答案 0 :(得分:0)

<?php 
$str = get_the_ID() ;
 $value=0;
 $count=0;
 $sql1="SELECT * FROM wphg_mr_rating_item_entry where post_id='".$str."'";
   $sql2= $wpdb->get_row( $wpdb->prepare( "SELECT * FROM   wphg_mr_rating_item_entry where post_id= %s",$str)); // take second condition here  before reaching to loop and check your condition . 
   //echo $sql1->post_title; 
     if($sql2!=''){ // if value not equal to null then going for this logic working fine for me.

      $result1 = $wpdb->get_results($sql1) or die(mysql_error()); 
      //var_dump($result1); 
      foreach( $result1 as $results1 ){  
    //if(!empty($results1->rating_item_entry_id)) {
    //if(!$wpdb->show_errors($results1->rating_item_entry_id )) { 

      $sql="SELECT * FROM wphg_mr_rating_item_entry_value where rating_item_entry_id='".$results1->rating_item_entry_id."'";
        $result = $wpdb->get_results($sql) or die(mysql_error());

   foreach( $result as $results){
       $sum =  $results->value."<br/>";
       $sum1 =  $results->value."<br/>";
         //$sum[]= array_push($sum,$value);   
           //echo count($sum+=$value);
           //print_r($value);  
        $count+=count($sum1);
          $value+= $sum;
     //}
     }
     }



   //echo $value;
 //echo $count;
 $value=$value/$count;   
  }
?>  

在达到循环并检查您的状况之前,先在此处采取第二个条件。 如果value不等于null,那么这个逻辑对我来说运行正常。