Search code examples
phpsessionnotice

How-to include if(isset inside a query


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)){
}
}
?>

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)){
    ?>