Как печатать из нескольких запросов, если один запрос содержит результат Null?

Я новичок в PHP. У меня проблема с печатью моих данных в моем браузере. У меня пять запросов. Мои четыре запроса основаны на результатах первого запроса

1-й запрос:

 $opinion_id = "SELECT `client_id` FROM `pacra_client_opinion_relations` WHERE `opinion_id` = 379";
$result = mysql_query($opinion_id) or die;
$row = mysql_fetch_assoc($result);
$client_id = $row['client_id'];

Этот запрос извлекает client_id и на основе client_id мои оставшиеся запросы будут работать.

Запрос 2:

$q_opinion="SELECT r.client_id,c.id,t.id,a.id,o.id,c.name as opinion, r.notification_date, t.title as ttitle,a.title as atitle,o.title as otitle, l.title as ltitle, s.title as stitle, pr.opinion_id, pc.id, pr.client_id as pr_client, pc.address, pc.liaison_one, city.id, pc.head_office_id, city.city, pc.title as cname
FROM og_ratings r 
    inner join
(
  select max(notification_date) notification_date,
    client_id
  from og_ratings
  group by client_id
  ) r2
  on r.notification_date = r2.notification_date
  and r.client_id = r2.client_id
LEFT JOIN og_companies c
ON r.client_id = c.id
LEFT JOIN og_rating_types t
ON r.rating_type_id = t.id
LEFT JOIN og_actions a
ON r.pacra_action = a.id
LEFT JOIN og_outlooks o
ON r.pacra_outlook = o.id
LEFT JOIN og_lterms l
ON r.pacra_lterm = l.id
LEFT JOIN og_sterms s
ON r.pacra_sterm = s.id
LEFT JOIN pacra_client_opinion_relations pr
ON pr.opinion_id = c.id
LEFT JOIN pacra_clients pc
ON pc.id = pr.client_id
LEFT JOIN city
ON city.id = pc.head_office_id
WHERE r.client_id  IN (SELECT opinion_id FROM pacra_client_opinion_relations WHERE client_id = $client_id)
";

Запрос 3:

$q_opinion1 = "SELECT r.client_id,c.id,t.id,a.id,o.id,c.name as opinion, r.notification_date, t.title as ttitle,a.title as atitle,o.title as otitle, l.title as ltitle, s.title as stitle, pr.opinion_id, pc.id, pr.client_id as pr_client, pc.address, pc.liaison_one, city.id, pc.head_office_id, city.city, pc.title as cname
FROM og_ratings r 
    inner join
(
  select max(notification_date) notification_date,
    client_id
  from og_ratings
  group by client_id
  ) r2
  on r.notification_date = r2.notification_date
  and r.client_id = r2.client_id
LEFT JOIN og_companies c
ON r.client_id = c.id
LEFT JOIN og_rating_types t
ON r.rating_type_id = t.id
LEFT JOIN og_actions a
ON r.pacra_action = a.id
LEFT JOIN og_outlooks o
ON r.pacra_outlook = o.id
LEFT JOIN og_lterms l
ON r.pacra_lterm = l.id
LEFT JOIN og_sterms s
ON r.pacra_sterm = s.id
LEFT JOIN pacra_client_opinion_relations pr
ON pr.opinion_id = c.id
LEFT JOIN pacra_clients pc
ON pc.id = pr.client_id
LEFT JOIN city
ON city.id = pc.head_office_id
WHERE r.client_id  IN (SELECT client_id FROM og_ratings WHERE client_id = 379)";

Запрос 4:

$q_opinion2="SELECT
   r.client_id,c.id,t.id,a.id,o.id,c.name as opinion, r.notification_date, t.title as ttitle,a.title as atitle,o.title as otitle, l.title as ltitle, s.title as stitle, pr.opinion_id, pc.id, pr.client_id as pr_client, pc.address, pc.liaison_one, city.id, pc.head_office_id, city.city, pc.title as cname
FROM
  og_ratings r 


  INNER JOIN (
    SELECT client_id, max(notification_date) notification_2nd_date
    FROM og_ratings
    WHERE client_id IN (SELECT `opinion_id` FROM `pacra_client_opinion_relations` WHERE `client_id` = $client_id) AND
      (client_id, notification_date) NOT IN (
        SELECT client_id, max(notification_date)
        FROM og_ratings GROUP BY client_id
          ORDER BY  client_id DESC)
    GROUP BY client_id
      ORDER BY  client_id DESC
   ) r2
  ON r.notification_date = r2.notification_2nd_date
     AND r.client_id = r2.client_id
  LEFT JOIN og_companies c ON r.client_id = c.id
  LEFT JOIN og_rating_types t ON r.rating_type_id = t.id
  LEFT JOIN og_actions a ON r.pacra_action = a.id
  LEFT JOIN og_outlooks o ON r.pacra_outlook = o.id
  LEFT JOIN og_lterms l ON r.pacra_lterm = l.id
  LEFT JOIN og_sterms s ON r.pacra_sterm = s.id
  LEFT JOIN pacra_client_opinion_relations pr ON pr.opinion_id = c.id
  LEFT JOIN pacra_clients pc ON pc.id = pr.client_id
  LEFT JOIN city ON city.id = pc.head_office_id
WHERE
  r.client_id IN (
    SELECT opinion_id FROM pacra_client_opinion_relations
    WHERE client_id = $client_id
  )";

Запрос 5:

$q_opinion3="SELECT
   r.client_id,c.id,t.id,a.id,o.id,c.name as opinion, r.notification_date, t.title as ttitle,a.title as atitle,o.title as otitle, l.title as ltitle, s.title as stitle, pr.opinion_id, pc.id, pr.client_id as pr_client, pc.address, pc.liaison_one, city.id, pc.head_office_id, city.city, pc.title as cname
FROM
  og_ratings r 


  INNER JOIN (
    SELECT client_id, max(notification_date) notification_2nd_date
    FROM og_ratings
    WHERE client_id IN (SELECT client_id FROM og_ratings WHERE client_id = 379) AND
      (client_id, notification_date) NOT IN (
        SELECT client_id, max(notification_date)
        FROM og_ratings GROUP BY client_id
          ORDER BY  client_id DESC)
    GROUP BY client_id
      ORDER BY  client_id DESC
   ) r2
  ON r.notification_date = r2.notification_2nd_date
     AND r.client_id = r2.client_id
  LEFT JOIN og_companies c ON r.client_id = c.id
  LEFT JOIN og_rating_types t ON r.rating_type_id = t.id
  LEFT JOIN og_actions a ON r.pacra_action = a.id
  LEFT JOIN og_outlooks o ON r.pacra_outlook = o.id
  LEFT JOIN og_lterms l ON r.pacra_lterm = l.id
  LEFT JOIN og_sterms s ON r.pacra_sterm = s.id
  LEFT JOIN pacra_client_opinion_relations pr ON pr.opinion_id = c.id
  LEFT JOIN pacra_clients pc ON pc.id = pr.client_id
  LEFT JOIN city ON city.id = pc.head_office_id
WHERE
  r.client_id IN (
    SELECT client_id FROM og_ratings WHERE client_id = 379)
  )";

Если query 1 запрос Bring client_id, тогда будут выполняться query 2 и query 4, но если нет client_id, то будут выполняться query 3 и query 5.

if ($client_id == NULL)
{
    $query = $q_opinion1;
    $query1 = $q_opinion3;
    }
    else{
$query = $q_opinion;
$query1 = $q_opinion2;
    }
  $result1 = mysql_query($query) or die;
  $result2 = mysql_query($query1) or die;

Оставшийся PHP-код

$opinion = array();

while($row1 = mysql_fetch_assoc($result1))
{        
    $opinion[]= $row1['opinion'];
    $action[]= $row1['atitle'];
    $long_term[]= $row1['ltitle'];
    $outlook[]= $row1['otitle'];
    $rating_type[]= $row1['ttitle'];
    $short_term[]= $row1['stitle'];


}
while($row2 = mysql_fetch_assoc($result2))
{
    $p_long_term[]= $row2['ltitle'];
    $p_short_term[]= $row2['stitle'];
}
?>

И мой код HTML

<table width="657">
        <tr>
            <td width="225"> <strong>Opinion</strong></td>
            <td width="62"> <strong>Action</strong></td>
            <td colspan="4"><strong>Ratings</strong></td>
            <td width="54"><strong>Outlook</strong></td>
            <td width="67"><strong>Rating Type</strong></td>
        </tr>
        <tr>
          <td width="225">&nbsp;</td>
          <td width="62">&nbsp;</td>
          <td colspan="2"><b>Long Term</b></td>
          <td colspan="2"><b>Short Term</b></td>
          <td width="54">&nbsp;</td>
          <td width="67">&nbsp;</td>
        </tr>
        <tr>
          <td width="225">&nbsp;</td>
          <td width="62">&nbsp;</td>
          <td width="52"><b>Current</b></td>
          <td width="45"><b>Previous</b></td>
          <td width="49"><b>Current</b></td>
          <td width="51"><b>Previous</b></td>
          <td width="54">&nbsp;</td>
          <td width="67">&nbsp;</td>
        </tr>
        <?php
        for ($i=0; $i<count($opinion); $i++) {
    //if ($opinion[$i] == "")continue;
        ?>


    <tr>
           <td><?php echo $opinion[$i]?></td>
          <td><?php echo $action[$i] ?></td>
          <td><?php echo $long_term[$i] ?></td>
          <td><?php echo $p_long_term[$i]?></td>
          <td><?php echo $short_term[$i] ?></td>
          <td><?php echo $p_short_term[$i] ?></td>
          <td><?php echo $outlook[$i] ?></td>
          <td><?php echo $rating_type[$i] ?></td>
        </tr>

        <?php
        }
?>
 </table>

Теперь проблема заключается в том, что

Иногда мой query 5 содержит нулевой результат. И из-за этой проблемы мои данные query 3 не печатаются. Я хочу, чтобы, если в моем запросе содержится результат Null, остальная часть данных будет напечатана на моей странице.

Ответ 1

Кажется, вы перебираете массив мнений и используете индекс для выбора соответствующего значения в $p_long_term [] и $p_short_term [] массивах. Эти массивы будут пустыми, если запрос 5 завершится с ошибкой.

<tr>
       <td><?php echo $opinion[$i]?></td>
      <td><?php echo $action[$i] ?></td>
      <td><?php echo $long_term[$i] ?></td>
      <td><?php echo $p_long_term[$i]?></td>**
      <td><?php echo $short_term[$i] ?></td>
      <td><?php echo $p_short_term[$i] ?></td>
      <td><?php echo $outlook[$i] ?></td>
      <td><?php echo $rating_type[$i] ?></td>
    </tr>

проверьте, существует ли ключ перед эхом.

<td><?php if(array_key_exists ($i, $p_long_term))echo $p_long_term[$i]?></td>
<td><?php if(array_key_exists ($i, $p_short_term))echo $p_short_term[$i] ?></td>

Ответ 2

Проблема заключается в логике во время цикла. Вы повторяете содержимое, отсутствующее в массиве query5. Сначала вы можете попытаться проверить существование элемента, а затем вернуться к выходному потоку.

for ($i=0; $i<count($opinion); $i++) {
    echo '<tr>';
    echo isset($opinion[$i])?  '<td>'. $opinion[$i] .'</td>' : '';
    echo isset($action[$i])?  '<td>'. $action[$i] .'</td>' : '';
    echo isset($long_term[$i])?  '<td>'. $long_term[$i] .'</td>' : '';
    echo isset($p_long_term[$i])?  '<td>'. $p_long_term[$i] .'</td>' : '';
    echo isset($short_term[$i])?  '<td>'. $short_term[$i] .'</td>' : '';
    echo isset($p_short_term[$i])?  '<td>'. $p_short_term[$i] .'</td>' : '';
    echo isset($outlook[$i])?  '<td>'. $outlook[$i] .'</td>' : '';
    echo isset($rating_type[$i])?  '<td>'. $rating_type[$i] .'</td>' : '';
    echo '</tr>';
}

Ответ 3

Используйте этот

$max = max(count($opinion),count($p_long_term));
for ($i=0; $i<$max; $i++) {
    echo '<tr>';
    echo isset($opinion[$i])?  '<td>'. $opinion[$i] .'</td>' : '';
    echo isset($action[$i])?  '<td>'. $action[$i] .'</td>' : '';
    echo isset($long_term[$i])?  '<td>'. $long_term[$i] .'</td>' : '';
    echo isset($p_long_term[$i])?  '<td>'. $p_long_term[$i] .'</td>' : '';
    echo isset($short_term[$i])?  '<td>'. $short_term[$i] .'</td>' : '';
    echo isset($p_short_term[$i])?  '<td>'. $p_short_term[$i] .'</td>' : '';
    echo isset($outlook[$i])?  '<td>'. $outlook[$i] .'</td>' : '';
    echo isset($rating_type[$i])?  '<td>'. $rating_type[$i] .'</td>' : '';
    echo '</tr>';
}