1

This is my first time using PHP and im learning everything from w3school. My question :

1 Loop

I have a database for seat booking which is ex : A1 A2 A3 A4 A5

I try to do some loop to reduce repetition of the same code but fail.

2 Undefined index for checkbox.

I do some checkbox and i got error : undefined index if i submit the form with some of the checkbox not checked. I google but i dont know how to alter my coding with their solution because i do not understand their solution.

Below is my coding.

    <html>

<?php

    $connect = mysql_connect("localhost","root","") or die ("Coulnt connect!");
    mysql_select_db("book") or die ("Couldnt find db");

    $A1 = 'enable';
    $A2 = 'enable';
    $A3 = 'enable';
    $A4 = 'enable';
    $A5 = 'enable';

    $query = mysql_query("SELECT * FROM seats WHERE Seat_Number = 1 AND Alphabet = 'A'");
    $row = mysql_fetch_array($query);
    $check = $row['Availability'];

    if($check >0)
    {
        $A1 = 'disabled';
    }

    $query = mysql_query("SELECT * FROM seats WHERE Seat_Number = 2 AND Alphabet = 'A'");
    $row = mysql_fetch_array($query);
    $check = $row['Availability'];

        if($check >0)
    {
        $A2 = 'disabled';
    }


    $query = mysql_query("SELECT * FROM seats WHERE Seat_Number = 3 AND Alphabet = 'A'");
    $row = mysql_fetch_array($query);
    $check = $row['Availability'];

    if($check >0)
    {
        $A3 = 'disabled';
    }

        $query = mysql_query("SELECT * FROM seats WHERE Seat_Number = 4 AND Alphabet = 'A'");
    $row = mysql_fetch_array($query);
    $check = $row['Availability'];

    if($check >0)
    {
        $A4 = 'disabled';
    }

    $query = mysql_query("SELECT * FROM seats WHERE Seat_Number = 5 AND Alphabet = 'A'");
    $row = mysql_fetch_array($query);
    $check = $row['Availability'];

    if($check >0)
    {
        $A5 = 'disabled';
    }


    if(isset($_POST ['submit']))
    {

        $ch1 = $_POST["ch1"];
        $ch2 = $_POST["ch2"];
        $ch3 = $_POST["ch3"];
        $ch4 = $_POST["ch4"];
        $ch5 = $_POST["ch5"];


        if(isset($_POST['ch1'])) 
        {
            echo 'You have select ch1';
            mysql_query("UPDATE seats SET Availability = 1 WHERE Alphabet = 'A' AND Seat_Number = 1");
        }

        if(isset($_POST['ch2'])) 
        {
            echo 'You have select ch2 <br>';
            mysql_query("UPDATE seats SET Availability = 1 WHERE Alphabet = 'A' AND Seat_Number = 2");
        }

        if(isset($_POST['ch3'])) 
        {
            echo 'You have select ch3 <br>';
            mysql_query("UPDATE seats SET Availability = 1 WHERE Alphabet = 'A' AND Seat_Number = 3");
        }

        if(isset($_POST['ch4'])) 
        {
            echo 'You have select ch4 <br>';
            mysql_query("UPDATE seats SET Availability = 1 WHERE Alphabet = 'A' AND Seat_Number = 4");
        }

        if(isset($_POST['ch5'])) 
        {
            echo 'You have select ch5 <br>';
            mysql_query("UPDATE seats SET Availability = 1 WHERE Alphabet = 'A' AND Seat_Number = 5");
        }

        }

?>

<center>
<body>

<form method="post" >

  <p>

    <input name="ch1" type="checkbox" id="A1" value="A1"<?php echo $A1; ?>/>
    <input name="ch2" type="checkbox" id="A2" value="A2"<?php echo $A2; ?>/>
    <input name="ch3" type="checkbox" id="A3" value="A3"<?php echo $A3; ?>/>
    <input name="ch4" type="checkbox" id="A4" value="A4"<?php echo $A4; ?>/>
    <input name="ch5" type="checkbox" id="A5" value="A5"<?php echo $A5; ?>/>


 </p>

<input type='submit' name='submit' value='Book Selected !' />
<input name="none" type="reset" value="Clear">

</form>
</body>
</center>
</html>
7
  • 3
    im learning everything from w3school - bad idea! Commented Apr 5, 2012 at 15:44
  • 2
    @DaveRandom It's really not so bad for starting off. Commented Apr 5, 2012 at 15:44
  • 1
    @Jleagle Teaching bad habits to a beginner propagates bad habits through to non-beginners. Start as you mean to go on. Commented Apr 5, 2012 at 15:45
  • 1
    Side note: If you're copying / pasting code over and over and changing 2-3 characters, it can be accomplished in much less. Commented Apr 5, 2012 at 15:49
  • the error : undefined index is come from the checkbox that not checked when submit. So as DaveRandom suggest remove the code solve the error. Now can someone help me with the loop? Its tedious to repeat the same code if i have 50 seats. Commented Apr 5, 2012 at 15:58

4 Answers 4

1

here is some help with loops and functions:

    $A1 = 'enable';
    $A2 = 'enable';
    $A3 = 'enable';
    $A4 = 'enable';
    $A5 = 'enable';

    $seats = array(1,2,3,4,5);

    function check_availability($seat)
    {
        $query = mysql_query("SELECT * FROM seats WHERE Seat_Number = $seat AND Alphabet = 'A'");
        $row = mysql_fetch_array($query);
        $check = $row['Availability'];

        if($check >0)
        {
            return 'disabled';
        }
        else{
            return 'available';
        }

    }

what this function does is checking a seat for you and returning disabled or available correspondingly. and here is how we can call it:

foreach($seats as $seat){
         ${'A'.$seat} = check_availability($seat);
    }

this code assigns returned value from function to $A1, $A2, etc... and here is loop for POST:

if(isset($_POST ['submit']))
    {
        for($e=1 ; $e <=5 ; $e++){
            if(isset($_POST['ch'.$e])) 
            {
                echo 'You have select ch'.$e;
                mysql_query("UPDATE seats SET Availability = 1 WHERE Alphabet = 'A' AND Seat_Number = $e");
            }

        }
    }

basically we repeat checking isset() 5 times - var $e starts from being 1, then compairs if it's still less or equal to 5, if not increases by 1

at the same time we using $e to change seat number in mysql query.

Sign up to request clarification or add additional context in comments.

3 Comments

Ok thanks for the code. I test it and it worked. I know that $seats = array(1,2,3,4,5); is to create array for the loop process. But i do not understand the use of variable $seat. Can explain a bit like where the $seat take value from and why use $seat instead of $seats?
for check_availability() function - it don't matter how you call it, we could call it $w, it's purely for code readability. however in foreach loop $seat is 1 item from array $seats, again i could've call it $b. you would probably want to read manul for foreach to understand it better php.net/manual/en/control-structures.foreach.php
Ok thank you for the manual i will read it after this. Thank you all for the code given. Very Appreciated it. :D
0

All you need to do to remove the errors is remove this block:

    $ch1 = $_POST["ch1"];
    $ch2 = $_POST["ch2"];
    $ch3 = $_POST["ch3"];
    $ch4 = $_POST["ch4"];
    $ch5 = $_POST["ch5"];

It doesn't do anything useful anyway - you never use the variables $ch1 etc anywhere in your code.

If you did want to keep the variables, you would move the individual lines to the relevant if (isset()) blocks - if you do this, you won;t try and use the $_POST keys before you have checked if they were set.

8 Comments

assign the value to $ch1 is nicer when doing validation/stripping etc, firstly you don;t get lots of _POST[''] all over the page, secondly accessing a post variable is slower than accessing a variable directly (although that wouldn't be an issue in this example)
@encodes accessing a post variable is slower sounds like premature optimisation to me. Although I take your point.
Source for: accessing a post variable is slower than accessing a variable directly ?
@Blake I suspect that is true, since it is array access which definitely is slower (on a large scale, such as very multidimensional arrays) but only very slightly, so slightly it is irrelevant. Although even that is just conjecture.
@DaveRandom I'm all for php optimization that makes sense, ie: phpbench.com (My favorite section is the loops) -- but more for human readability. Me trying to figure out what the hell someone is referencing takes much more time than the 2 nanoseconds for the computer to eval it. Code for humans to read it, then optimize for computer resources. Not the other way around.
|
0

i think the issue is that you check for a post variable, you need to put it into an isset or something similiar

e.g. $ch1 = null; if(isset($_POST['ch1']){ $ch1 = $_POST['ch1']; }

that way it won't try and access the ch1 part of the array if its not set throwing an undefined index exception. Hope the explanation also helps to see where you went wrong.

you'd need to do for each _POST

2 Comments

Thanks for the reply but this is the most code i found while google. But unfortunately i do not understand it because im to newbie in php and i dont know how to alter my coding with this code.
ok what you are doing in $ch1 = $_POST['ch1'] is taking the value from the POST variable (basically an array of variables from a form), if you try and access an element of an array that doesn't exists then it will cause an error. if ch1 isn't posted $_POST['ch1'] is not set and therefore throws an errro, what you need to do is check if the post variable is set, then if it is assign it to your local variable. php has a function called isset for this, you simply do if(isset($_POST['ch1']){ /*code */} if ch1 isnt set it wont run the /*code */ bit therefore avoiding the error
0

Undefined index for checkbox can be eleminated by simply using

$ch1 = isset($_POST["ch1"])?$_POST['ch1']:null;
$ch2 = isset($_POST["ch2"])?$_POST['ch2']:null;
$ch3 = isset($_POST["ch3"])?$_POST['ch3']:null;
$ch4 = isset($_POST["ch4"])?$_POST['ch4']:null;
$ch5 = isset($_POST["ch5"])?$_POST['ch5']:null;

instead of using

$ch1 = $_POST["ch1"];
$ch2 = $_POST["ch2"];
$ch3 = $_POST["ch3"];
$ch4 = $_POST["ch4"];
$ch5 = $_POST["ch5"];

For your next query about loop, you can use

<?php
$A[1] = 'enable';
$A[2] = 'enable';
$A[3] = 'enable';
$A[4] = 'enable';
$A[5] = 'enable';
for ($i=1, $i<=5, $i++) {
 $query = mysql_query("SELECT * FROM seats WHERE Seat_Number = ". $i ." AND Alphabet = 'A'");
 $row = mysql_fetch_array($query);
 $check = $row['Availability'];

    if($check >0)
    {
        $A[$i] = 'disabled';
    }
}
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.