Question

This little piece of code gives Notice: Undefined index: placeno1

I know it can be fixed by using if(isset()), but I have no idea how to place this on the correct matter in this $query line.

Tried a lot, but can't get it right.

<?php 
$query = mysql_query("SELECT `id` FROM `place` WHERE `placeno` = '".$_SESSION['placeno'.$i]."' LIMIT 1");
while($row = mysql_fetch_object($query)){
?>

Solution is

<?php 
if(isset($_SESSION['placeno'.$i])) {
$query = mysql_query("SELECT `id` FROM `place` WHERE `placeno` = '".$_SESSION['placeno'.$i]."' LIMIT 1");
while($row = mysql_fetch_object($query)){
}
}
?>
Était-ce utile?

La solution

Undefined index is a array notice. So possible notice source is 'placeno'.$i. You need to check it on every loop.

I am assuming you are looping this code with for() loop. That is where $i is coming from.

<?php 
if (isset($_SESSION['placeno'.$i])) {
    $query = mysql_query("SELECT `id` FROM `place` WHERE `placeno` = '".$_SESSION['placeno'.$i]."' LIMIT 1");
    while($row = mysql_fetch_object($query)){
    }
}
?>

If it's a loop, you can stop the loop like this:

<?php 
if (!isset($_SESSION['placeno'.$i])) {
    break;
}
$query = mysql_query("SELECT `id` FROM `place` WHERE `placeno` = '".$_SESSION['placeno'.$i]."' LIMIT 1");
while($row = mysql_fetch_object($query)){
?>

Autres conseils

Use ternary operator:

 $query = mysql_query("SELECT `id` FROM `place` 
      WHERE `placeno` = '".isset($_SESSION['placeno'.$i])?$_SESSION['placeno'.$i]:""."' 
      LIMIT 1");
  while($row = mysql_fetch_object($query)){

... and sanitizing and mysqli_ functions :P

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top