Jump to content

displaying all check boxes from database even those that have not been selected


webdeveloper123
Go to solution Solved by Barand,

Recommended Posts

I am creating a edit form. On the insert form there are 3 check boxes, each relating to what type of Vehicle the user has. What I want to do is on the edit form, all 3 check boxes should be displayed regardless of how many check boxes were "checked" initially. So If the user selected 2 of the 3 boxes, all 3 should be shown but only those 2 are checked.

I've actually got some of the code but there is a small problem in there. I am getting multiple check boxes. So if 1 check box was checked, that works fine, I get 3 check boxes, with the correct one ticked. But for 2 boxes initially ticked, I get 6 boxes and for 3 boxes inititally ticked I get 9 boxes.

Here is my code:
 

<?php
  if (!empty($VehSelection)) {
  foreach($table as $key => $value) {
    $VehSelection= $value["VehSelection"]; 
    ?>

    <?php 
    if ($VehSelection == 'Yacht') { ?>
      <input type="checkbox" id="yacht" name="vehicle[]" value="Yacht" checked/>
  <label for="yacht" class="boxstyle"> I have a yacht</label> <br><?php } else {
    ?> <input type="checkbox" id="yacht" name="vehicle[]" value="Yacht">
    <label for="yacht" class="boxstyle"> I have a yacht</label><br> <?php

    } ?>


    <?php 
    if ($VehSelection == 'SuperCar') { ?>
      <input type="checkbox" id="superCar" name="vehicle[]" value="SuperCar" checked/>
  <label for="superCar" class="boxstyle"> I have a super car</label><br> <?php } else {
    ?> <input type="checkbox" id="superCar" name="vehicle[]" value="SuperCar">
    <label for="superCar" class="boxstyle"> I have a super car</label><br> <?php

    } ?>


        <?php 
    if ($VehSelection == 'Plane') { ?>
      <input type="checkbox" id="plane" name="vehicle[]" value="Plane" checked/>
  <label for="plane" class="boxstyle"> I have a plane</label> <br><?php } else {
    ?> <input type="checkbox" id="plane" name="vehicle[]" value="Plane">
    <label for="plane" class="boxstyle"> I have a plane</label></br> <?php

    } ?>

    
  <?php 

   }}

?>

Thank you

Link to comment
Share on other sites

Not enough to work with here.

The 3 values.  Are they separate data items in your db?  If so you shouldn't have any problem.  That makes me think that they are 3 static values that you always want to appear but only check the ones in use for this key.

I think you want to always produce the output for each choice but only check when the value is in your array.

And stop switching in and out of php mode.  You don't have to do it.

Link to comment
Share on other sites

Try this.

//************************************
if (!empty($VehSelection)) 
	foreach($table as $key => $value)
		$VehSelection= $value["VehSelection"];
//***********************
$chk = '';
if ($VehSelection == 'Yacht')
	$chk = 'checked';
echo "<label class='boxstyle'>
		<input type='checkbox' name='vehicle[]' value='Yacht' $chk>
		I have a yacht
		</label>
		<br>";
//***********************
$chk = '';
if ($VehSelection == 'SuperCar')
	$chk = 'checked';
echo "<label class='boxstyle'> 
			<input type='checkbox' name='vehicle[]' value='SuperCar' $chk>
			I have a super car
			</label>
			<br>";
//***********************
$chk = '';
if ($VehSelection == 'Plane')
	$chk = 'checked';
echo "<label class='boxstyle'> 
	<input type='checkbox' name='vehicle[]' value='Plane' $chk>
	I have a plane
	</label>
	<br>";

It is untested of course but it does what you ask I think.  Note the lack of a single switch out of php mode.  And the lack of id values which you don't need if not using JS to access them.

Edited by ginerjm
Link to comment
Share on other sites

The thing is if one check box was ticked initially, the loop runs once. If 2 were checked, the loop runs twice and 3 check boxes ticked it runs 3 times. That's what I think is happening. But If I take it out the loop then I only get 1 check box ticked when say for example that user had ticked 2 or 3

Link to comment
Share on other sites

if you find yourself writing out code for each possible value, it's a sign that you are doing something the hardest possible way. just to add a value, you would need to edit the code and add another repeated block of code.

the list of (currently 3) choices should be defined in a data structure (database table, array), with a numerical id (auto-increment primary index) and a name/label. it is this definition that you would loop over to produce the output.

if you are pre-checking existing choices when you are looping to produce the output, either based on some stored choice ids or due to submitted ids from a form, you would test if the current id being output is in an array (see php's in_array()) of the existing choices to determine if the 'checked' attribute should be output.

Link to comment
Share on other sites

Maybe the following will help:

 

<?php
    session_start();
    //unset($_SESSION['vehicle']);
    //die();

    if (!isset($_SESSION)) {
        $_SESSION['vehicle'] = null; // Pretend coming from a database table:
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $_SESSION['vehicle'] = $_POST['vehicle'];
        //echo "<pre>" . print_r($_POST['vehicle'], 1) . "</pre>";
    }

?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=yes, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Checkboxes</title>
</head>
<body>
<form method="post">
    <label for="yacht" class="vehicle"><?= $_SESSION['vehicle']['yacht'] ? 'I own a Yacht' : 'Yacht'?></label>
    <input id="yacht" type="checkbox" name="vehicle[yacht]" value="yacht" <?php echo ($_SESSION['vehicle']['yacht']) ? 'checked' : NULL; ?>>
    <br>
    <label for="sportsCar" class="vehicle"><?= $_SESSION['vehicle']['sportsCar'] ? 'I own a Porsche 911' : 'Sports Car'?></label>
    <input id="sportsCar" type="checkbox" name="vehicle[sportsCar]" value="sportsCar" <?php echo ($_SESSION['vehicle']['sportsCar']) ? 'checked' : NULL; ?>>
    <br>
    <label for="plane" class="vehicle" ><?= $_SESSION['vehicle']['plane'] ? 'I own a Cessna Jet' : 'Plane'?></label>
    <input id="plane" type="checkbox" name="vehicle[plane]" value="plane" <?php echo ($_SESSION['vehicle']['plane']) ? 'checked' : NULL; ?>>
    <br>
    <button class="submitButton" type="submit" name="submit" value="enter">submit</button>
</form>

</body>
</html>

 

Link to comment
Share on other sites

This is the method I would use

** DATA *********************************************************************************************************

user_demo                                     user_transport                 transport_type
+---------+----------+-------+----------+     +---------+------------+       +------------+-------------+
| user_id | username | fname | lname    |     | user_id | trans_type |       | trans_type | description |
+---------+----------+-------+----------+     +---------+------------+       +------------+-------------+
|       1 | norderl  | Laura | Norder   |     |       1 |          1 |       |          1 | Yacht       |
|       2 | tomd     | Tom   | DiCanari |     |       1 |          2 |       |          2 | SuperCar    |
|       3 | cheggs   | Scott | Chegg    |     |       3 |          1 |       |          3 | Plane       |
|       4 | dowtp    | Peter | Dowt     |     |       3 |          2 |       +------------+-------------+
|       5 | robika   | Anna  | Robik    |     |       3 |          3 |
+---------+----------+-------+----------+     |       4 |          1 |
                                              |       4 |          3 |
                                              |       5 |          2 |
                                              +---------+------------+


** QUERY ********************************************************************************************************

        SELECT u.user_id
             , u.fname
             , u.lname
             , tt.description
             , tt.trans_type
             , CASE WHEN ut.user_id IS NULL
                    THEN 0
                    ELSE 1
                    END AS checked
        FROM user_demo u
             CROSS JOIN                                             -- get all combinations of user/transport type
             transport_type tt
             LEFT JOIN                                              -- get which ones are used by each user
             user_transport ut ON u.user_id = ut.user_id 
                               AND tt.trans_type = ut.trans_type
        ORDER BY lname, trans_type;


 ** RESULTS *****************************************************************************************************
 
        +---------+-------+----------+-------------+------------+---------+
        | user_id | fname | lname    | description | trans_type | checked |
        +---------+-------+----------+-------------+------------+---------+
        |       3 | Scott | Chegg    | Yacht       |          1 |       1 |
        |       3 | Scott | Chegg    | SuperCar    |          2 |       1 |
        |       3 | Scott | Chegg    | Plane       |          3 |       1 |
        |       2 | Tom   | DiCanari | Yacht       |          1 |       0 |
        |       2 | Tom   | DiCanari | SuperCar    |          2 |       0 |
        |       2 | Tom   | DiCanari | Plane       |          3 |       0 |
        |       4 | Peter | Dowt     | Yacht       |          1 |       1 |
        |       4 | Peter | Dowt     | SuperCar    |          2 |       0 |
        |       4 | Peter | Dowt     | Plane       |          3 |       1 |
        |       1 | Laura | Norder   | Yacht       |          1 |       1 |
        |       1 | Laura | Norder   | SuperCar    |          2 |       1 |
        |       1 | Laura | Norder   | Plane       |          3 |       0 |
        |       5 | Anna  | Robik    | Yacht       |          1 |       0 |
        |       5 | Anna  | Robik    | SuperCar    |          2 |       1 |
        |       5 | Anna  | Robik    | Plane       |          3 |       0 |
        +---------+-------+----------+-------------+------------+---------+

Now you can just list the query results in your form, using the "checked" field to tell you if the check box should be checked or not.

Link to comment
Share on other sites

I do have a database Barand, it looks like this:

Form (FormId, Name, Lastname, age, birthday, email, FavLanguage, Vehicle)

Vehicle (VehicleId, FormId (FK), VehSelection)

Sample data from Form table:

Sample data from Form Table:

191 tom smith 33 09-06-1997 tom@smith.com CSS NULL

192 Frank Lampard 39 10-06-1992 frank@everton.com CSS NULL

193 John Atkins  23 11-07-2006 john@gmail.com JavaScript NULL

 

Sample data from Vehicle table

216 191 Plane

217 192 Yacht

218 192 SuperCar

219 192 Plane

220 193 SuperCar

221 193 Plane

 

What I want to acheive:

On every "Edit form" page, 3 check boxes always on display, and the relevant ones checked for that record. That way a user can come back a week later and decide "Actually I haven't got a plane anymore, but I do have a yacht. Untick plane, tick yacht and update.

 

Edited by webdeveloper123
Link to comment
Share on other sites

7 minutes ago, webdeveloper123 said:

I do have a database, it looks like this:

what you are missing, relevant to both my reply above and the reply by @Barand, is a table where the (currently 3) vehicle choices are DEFINED. it is this definition that will allow you to produce the checkbox markup without writing out code for every possible value.

see the following example form processing/form code, related to the method stated in my reply above (there are comments in the code at the point where you would query for and retrieve the existing data to be edited) -

<?php

// you would query to get the following data from whereever it is stored
// assuming that $table in the OP's code is an array of fetched data defining the checkbox choices
$table = [];
// the index is the id
// do you really want the 'I have a' text with every entry? how about just a heading to select the vehicles the user has?
$table[1] = ['name'=>'I have a yacht'];
$table[2] = ['name'=>'I have a super car'];
$table[3] = ['name'=>'I have a plane'];

$post = []; // array to hold a trimmed working copy of the form data
$errors = []; // array to hold user/validation errors

// recursive function to trim data
function _trim($val){
	if(is_array($val)){
		return array_map('_trim',$val);
	} else {
		return trim($val);
	}
}

// post method form processing code
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
	// trim all the data at once
	$post = array_map('_trim',$_POST);
	
	// validate the data here, storing validation errors in $errors, using the field name as the array index

	
	// if no errors, use the submitted data
	if(empty($errors))
	{
		// insert new data or update existing data here...
		
	}
}

// get method business logic - get/produce data need to display the dynamic content on the page
// if editing existing saved choices, there would be a get input to validate, then used to query
// for and retrieve the existing choice data, but only if the form has never been submitted ($post
// is empty), storing the fetched data in $post, in a sub-array named 'vehicle', in the same format
// as the form will submit it as.


// html document starts here...
?>

<form method='post'>
<?php
// display the checkboxes, with any existing choices pre-checked
foreach($table as $id=>$arr)
{
	$chk = in_array($id,$post['vehicle'] ?? []) ? ' checked' : '';
	// note: if you put the <label></label> around the form field, you don't need to generate unique ids to make it work
	echo "<label class='boxstyle'><input type='checkbox' name='vehicle[]' value='$id'$chk> {$arr['name']}</label><br>\n";
}
?>
<input type='submit'>
</form>

 

  • Like 1
Link to comment
Share on other sites

Just a little tip on the trim function....

If you use a guard clause you can get rid of the else and clean up the function just a bit. Also, when you call the function, there is no need to call it with array_map. The $_POST data is already being run through array_map. No need to do it twice. 😀

 

<?php
function _trim($val)
{
    if (!is_array($val)) {
        return trim($val);
    }
    return array_map('_trim', $val);
}

$post = _trim($_POST); 

 

Link to comment
Share on other sites

Thanks benanamen & mac_gyver but that's a little too advanced for me, only been doing php for 4 months now.

The code I previously posted was not very good, here is a better version:

<?php
  if (!empty($VehSelection)) {
  foreach($table as $key => $value) {
    $VehSelection= $value["VehSelection"];
    ?>
     <input type="checkbox" id="yacht" name="vehicle[]" value="Yacht" <?php echo ($VehSelection == 'Yacht') ? 'checked' : ''; ?> />
  <label for="yacht" class="boxstyle"> I have a yacht</label><br>
  <input type="checkbox" id="superCar" name="vehicle[]" value="SuperCar" <?php echo ($VehSelection == 'SuperCar') ? 'checked' : ''; ?> />
  <label for="superCar" class="boxstyle"> I have a super car</label><br>
  <input type="checkbox" id="plane" name="vehicle[]" value="Plane" <?php echo ($VehSelection == 'Plane') ? 'checked' : ''; ?> />
  <label for="plane" class="boxstyle"> I have a plane</label><br><br><br>
   
  <?php 
  }}

?>

This works, but If there are 2 problems. With one value(say for example "Plane"), it will generate 3 check boxes with "Plane" ticked(which is great, that works!). But with 2 values, (say "SuperCar" and "Yacht" it will print me 6 check boxes) and with all 3 values, it will print me 9 check boxes. Can anyone figure out where i'm going wrong please?

Edited by webdeveloper123
Link to comment
Share on other sites

4 minutes ago, webdeveloper123 said:

This works

no it doesn't. if it did it, it would always produce 3 checkboxes with the existing choices pre-checked.

you need to break down problems into the individual steps need, then design, write, test, and debug the code for each step, before going on to the next step. you need to get to the point where you can first, always, produce the 3 checkboxes.

the code i posted above is a very simple stand-alone working example. i assumed that $table is somehow the definition of the checkboxes, which what you do need to loop over to produce the output. however, it is apparently the existing choices, which is not the data you need to be looping over. if you run my code, you can observe and learn how it works. there will initially be 3 unchecked checkboxes, because there's no code to query for the existing choices. if you check any/combination of the boxes and submit the form, the boxes will retain their checked state. this is a feature you will need as part of general-purpose form  processing/form code, where there can be other form fields, and you don't want to reset all the fields back their initial values should there be a validation error in any of the fields.

once you understand how to dynamically produce the 3 checkboxes, you can move onto the next step of querying for and retrieving the existing choices to initially use to pre-check the checkboxes with.

Link to comment
Share on other sites

On 4/8/2022 at 8:54 PM, Barand said:

Now you can just list the query results in your form, using the "checked" field to tell you if the check box should be checked or not.

For completeness, my processing would be

if ($_SERVER['REQUEST_METHOD']=='POST') {
    try {
        $db->beginTransaction();
        $stmt1 = $db->prepare("DELETE FROM user_transport
                               WHERE user_id = ?
                              ");
        $stmt1->execute( [ $_POST['uid'] ] );
        if (isset($_POST['trans'])) {
            $stmt2 =  $db->prepare("INSERT INTO user_transport (user_id, trans_type)
                      VALUES (?, ?)
                     ");
                     
            foreach ($_POST['trans'] as $tid) {
                $stmt2->execute( [ $_POST['uid'], $tid ] );
            }
        }
        $db->commit();
    }
    catch(PDOException $e) {
        $db->rollBack();
        throw $e;
    }
    header("Refresh: 0");
    exit;
}

$res = $db->query("SELECT u.user_id
                     , u.fname
                     , u.lname
                     , tt.description
                     , tt.trans_type
                     , CASE WHEN ut.user_id IS NULL
                            THEN 0
                            ELSE 1
                            END AS checked
                FROM user_demo u
                     CROSS JOIN                                          
                     transport_type tt
                     LEFT JOIN                                           
                     user_transport ut ON u.user_id = ut.user_id 
                                       AND tt.trans_type = ut.trans_type
                ORDER BY lname, trans_type
                ");
$data = [];
// store results in a conveniently structured array
foreach ($res as $r) {
    if (!isset($data[$r['user_id']])) {
        $data[$r['user_id']] = [  'name' => "{$r['fname']} {$r['lname']}",
                                  'trans' => []
                               ];
    }
    $data[$r['user_id']]['trans'][$r['trans_type']] = ['desc' => $r['description'], 'check' => $r['checked']];
}
// echo '<pre>' . print_r($data, 1) . '</pre>';     # view array structure
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="generator" content="PhpED 19.5 (Build 19523, 64bit)">
<title>Example</title>
<meta name="author" content="Barand">
<meta name="creation-date" content="04/09/2022">
<style type='text/css'>
    table {
        border-collapse: collapse;
        margin: 20px auto;
        width: 60%;
    }
    td, th {
        padding: 8px;
    }
</style>
</head>
<body>
    <table border='1'>
        <tr>
            <th>Name</th>
            <th>Transport types</th>
            <th>&nbsp;</th>
        </tr>
        
        <?php
            // output the array
            foreach ($data as $uid => $udata) {
                echo "<tr>
                <form method='post'>
                        <td>{$udata['name']}</td>
                        <td>";
                foreach ($udata['trans'] as $ttype => $tdata) {
                    $chk = $tdata['check'] ? 'checked' : '';
                    echo "<label><input type='checkbox' name='trans[]' value='$ttype' $chk>{$tdata['desc']}</label><br>";
                }
                echo "</td>
                      <td>
                           <input type='hidden' name='uid' value='$uid'>
                           <input type='submit' value='Update'>
                      </td>
                      </form>
                      </tr>
                     ";
            }
        ?>
    </table>
</body>
</html>

Results

image.png.081fd30ed32dc620d692d1cb0fc7b896.png

Edited by Barand
  • Like 1
Link to comment
Share on other sites

2 hours ago, webdeveloper123 said:

but this would involve changing my entire database structure

Given you current structure that could only be a good thing to do.

  • Your date storage format is useless. Can't be processed or sorted. Always store in yyyy-mm-dd format (type DATE)
  • You shouldn't store age, it needs continual updating and can be easily derived from a correctly formatted date (SELECT timestampdiff(YEAR, curdate(), birthday) as age )
  • Description like "SuperCar" should appear once in a database and not be used as FKs. Only ids should occur in more that one table.
  • If one of your people buys a "Hot Air Balloon" it won't appear on the form to add the option as no-one currenly has one. (In my design I merely add another record to "Vehicle_type" table - job done.)
2 hours ago, webdeveloper123 said:

Is there a simple fix you can see in my code above?

I have rewritten my query and code to use your database structure. I had to use a subquery to get the available vehicle types instead of my table)

// connect to DB here


if ($_SERVER['REQUEST_METHOD']=='POST') {
    // echo '<pre>' . print_r($_POST, 1) . '</pre>';
    try {
        $db->beginTransaction();
        $stmt1 = $db->prepare("DELETE FROM vehicle
                               WHERE formid = ?
                              ");
        $stmt1->execute( [ $_POST['formid'] ] );
        if (isset($_POST['trans'])) {
            $stmt2 =  $db->prepare("INSERT INTO vehicle (formid, vehselection)
                      VALUES (?, ?)
                     ");
                     
            foreach ($_POST['trans'] as $veh) {
                $stmt2->execute( [ $_POST['formid'], $veh ] );
            }
        }
        $db->commit();
    }
    catch(PDOException $e) {
        $db->rollBack();
        throw $e;
    }
    header("Refresh: 0");
    exit;
}

$res = $db->query("SELECT  f.formid
                         , f.name
                         , f.lastname
                         , fv.vehselection
                         , CASE WHEN v.vehselection IS NULL
                                THEN 0
                                ELSE 1
                                END AS checked
                    FROM form f
                         CROSS JOIN                                          
                         (
                            SELECT DISTINCT vehselection 
                            FROM vehicle
                         ) fv 
                         LEFT JOIN                                           
                         vehicle v ON f.formid = v.formid 
                                           AND v.vehselection = fv.vehselection
                    ORDER BY lastname, vehselection
                ");
$data = [];
// store results in a conveniently structured array
foreach ($res as $r) {
    if (!isset($data[$r['formid']])) {
        $data[$r['formid']] = [  'name' => "{$r['name']} {$r['lastname']}",
                                  'trans' => []
                               ];
    }
    $data[$r['formid']]['trans'][$r['vehselection']] = $r['checked'];
}
//echo '<pre>' . print_r($data, 1) . '</pre>';     # view array structure
//exit;
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="generator" content="PhpED 19.5 (Build 19523, 64bit)">
<title>Example</title>
<meta name="author" content="Barand">
<meta name="creation-date" content="04/09/2022">
<style type='text/css'>
    table {
        border-collapse: collapse;
        margin: 20px auto;
        width: 60%;
    }
    td, th {
        padding: 8px;
    }
</style>
</head>
<body>
    <table border='1'>
        <tr>
            <th>Name</th>
            <th>Transport types</th>
            <th>&nbsp;</th>
        </tr>
        
        <?php
            // output the array
            foreach ($data as $fid => $udata) {
                echo "<tr>
                <form method='post'>
                        <td>{$udata['name']}</td>
                        <td>";
                foreach ($udata['trans'] as $ttype => $check) {
                    $chk = $check ? 'checked' : '';
                    echo "<label><input type='checkbox' name='trans[]' value='$ttype' $chk>$ttype</label><br>";
                }
                echo "</td>
                      <td>
                           <input type='hidden' name='formid' value='$fid'>
                           <input type='submit' value='Update'>
                      </td>
                      </form>
                      </tr>
                     ";
            }
        ?>
    </table>
</body>
</html>

image.png.9ec40e8a37e6bf961594b1fc660ff502.png

Edited by Barand
  • Haha 1
Link to comment
Share on other sites

41 minutes ago, Barand said:

Your date storage format is useless

I wanted to store in UK date format

41 minutes ago, Barand said:

You shouldn't store age

I agree, I was going to fix that later, I only realised long after I created the db

43 minutes ago, Barand said:

Description like "SuperCar" should appear once

I agree, again I was a bit rusty when I created my database, but it's only an example to practice php/mysql so If it was a professional solution I would change it

 

44 minutes ago, Barand said:

If one of your people buys a "Hot Air Balloon"

Again, I agree but this is just an exercise to practice programming, the form won't change to that extent.

With your example it is all in PDO, and I am doing MySqli. I know your solution is more professional and elegant but I just want to fix this part and get to the next stage. Is there something you can do with my existing code...surely it's not that bad that It cannot be used, even though it might not be great, it surely can still be used?

Link to comment
Share on other sites

6 hours ago, webdeveloper123 said:

this would involve changing my entire database structure

no. it only involves adding one table, a table that defines the checkbox choices, which i specifically mentioned in a reply.

in @Barand's reply that shows the table structures, the user_demo table and your form table perform the same purpose (his table only has columns necessary for the demonstration), his user_transport and your vehicle table perform the same purpose and even look the same (after you fix storing an id instead of an abbreviated name), and the transport_type table is the checkbox choices defining table.

2 hours ago, webdeveloper123 said:

Am I using the wrong type of loop?

no, the type of loop is correct, what it is looping over is not. if you look at both the code that he and i have posted, at the point of producing the checkbox markup, you will see that  everyone is using a foreach loop, but we are both looping over the definition of the checkbox choices, adding the checked attribute when there is an existing, checked choice. in your code, you are looping over an array of the existing, checked choices. what can that array contain? from zero to three rows of data, resulting in zero to three sets of markup. does that make sense to you? the first three lines of your code make no sense toward getting this task to work. you are testing if some unknown variable is not empty, looping over an array of data, that is apparently the existing checked data, then setting the first variable to be an element of the data you are looping over.

 

4 hours ago, Barand said:

I had to use a subquery to get the available vehicle types instead of my table

actually, that won't work unless there is already at least one checked choice for each one in the vehicle table.

Link to comment
Share on other sites

17 hours ago, mac_gyver said:

you are testing if some unknown variable is not empty,

It's not a unknown variable. I have a SQL Select statement which for the result set I do this after:

$result = mysqli_query($link, $queryselect);

$table = [];

while ( $row = mysqli_fetch_assoc( $result ) ) {
   $table[] = $row; 
}

Then I do this:

if ( count($table) == 0) {
 exit;

}
else
{
 

  $first_name = $table[0]["FirstName"];
  $last_name = $table[0]["LastName"];
  $email = $table[0]["Email"];
  $age = $table[0]["Age"];
  $birthday = $table[0]["Birthdate"];
  $favlanguage = $table[0]["FavLanguage"];
  $VehSelection= $table[0]["VehSelection"];
}

But I am looking and mac_gyvers and Barands foreach loop and trying to come up with something

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.