0

I'm upgrading my website and want to move from having multiple pages with identical code to a single page that performs all user actions. I can do his well enough however because the user can request any unpredictable content some <div> tags will be empty and MySQL will throw the undefined offset error because there isn't enough content in the database to fill the fetch_array(). Some example code..

<?php
$dbhost  = 'localhost';   
$dbname  = 'd_dundaah';   
$dbuser  = 'max';   
$dbpass  = '';  

$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($conn->connect_error) die($conn->connect_error);

$query = "SELECT * FROM events WHERE day='mon'";

$result = $conn->query($query);
if (!$result) die($conn->error);

$rows = $result->num_rows;
$j = 0;

$heading_array='';
$paragraph_array='';

while ($j < $rows )
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_ASSOC);

$event_heading = $row['heading'];
$event_paragraph = $row['paragraph'];

$heading_array[]=$event_heading;
$paragraph_array[]=$event_paragraph;

++$j;
}

$result->close();
$conn->close();

?>

Then when calling the data, if mon has only one row of data the offset error will be called. How do I get MySQL to ignore this?

<div class="one">
 <h1><?php echo $heading1[0];?></h1>
 <p><?php echo $paragraph1[0];?></p>
</div>
<!--ignore this 'two' if none existent in database-->
<div class="two">
 <h1><?php echo $heading1[1];?></h1>
 <p><?php echo $paragraph1[1];?></p>
</div>

Thank you.

Max Njoroge
  • 489
  • 3
  • 21
  • Use `!empty` or `isset` - [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – jitendrapurohit Oct 19 '16 at 11:47

2 Answers2

3

isset() is you friend here. It returns true if the specified index exists and false otherwise.

You can for example use it like this.

if(isset($heading1[1])){
    // Do something here, only if $heading1[1] exists
}
Björn Fyrvall
  • 231
  • 1
  • 7
1

Change your HTML to:

<?php if (isset($heading1[1]) && isset($paragprah[1]))  : ?>
<div class="two">
  <h1><?php echo $heading1[1];?></h1>
  <p><?php echo $paragraph1[1];?></p>
</div>
<?php endif; ?>

Or safer, to prevent empty array:

<?php if (isset($heading1[1]) && !empty($heading1[1]) && isset($paragprah[1]) && !empty($paragprah[1]))  : ?>
<div class="two">
  <h1><?php echo $heading1[1];?></h1>
  <p><?php echo $paragraph1[1];?></p>
</div>
<?php endif; ?>
pleinx
  • 616
  • 3
  • 8