PHP While Loop in While Loop - php

I've had this problem for a little while and probably didn't ask the question properly last time. Having dabbled again I'm still very much confused and stuck.
I have a MySQL table that I list out a series of checkboxes based on values in this (around 200).
I have another MySQL table where a user will store their preferences, when the list loads I wish for the items that the user had previously selected in the second MySQL table to be checkboxes that have the check mark already assigned indicating previous choice. If you could please take a look at the following and point me in the right direction I'd be grateful.
$result = mysql_query("SELECT `car` FROM `carlist` ORDER BY variety ASC");
$result2 = mysql_query("SELECT `car` FROM `lists` WHERE `username` = 'Palendrone' ORDER BY variety ASC");
if (!$result) {
die("Query to show fields from table failed");
}
if (!$result2) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
}
$fields_num2 = mysql_num_fields($result2);
for($j=0; $j<$fields_num2; $j++)
{
$field2 = mysql_fetch_field($result2);
}
while($row = mysql_fetch_row($result))
{
while($row2 = mysql_fetch_row($result2))
{
if("$row2[0]" <> "$row[0]")
{?><input type="checkbox" value="<?php echo "$row[0]"?>" name="<?php echo "$row[0]"?>" id="<?php echo "$row[0]"?>">
<label for="<?php echo "$row[0]"?>"><?php echo "$row[0]"?></label>
<?php
} else
{?><input type="checkbox" value="<?php echo "$row[0]"?>" name="<?php echo "$row[0]"?>" checked="yes" id="<?php echo "$row[0]"?>">
<label for="<?php echo "$row[0]"?>"><?php echo "$row[0]"?></label>
<?php
}
} /* end while */
} /* end while */
I figured the first While loop to load the main 200 items in, then for each input in that table it cross checks against the users selection table in the second while loop, in that loop I have the if statement working in reverse order so as not to check it then uncheck it.
I was pointed in the way of starting from scratch last week by another user on here, although I've started going through some tutorials I kinda need to get this last part of my project nailed...

I would suggest changing your query strategy - use only one instead of two. You can check the value of second member of select list - lists.car from result of query below for null value. If it is null then checkbox is not selected otherwise it is (it is present in second table).
$result = mysql_query("SELECT `carlist`.`car`, `lists`.`car` FROM `carlist` left join `lists` on (`carlist`.`car` = `lists`.`car` and `lists`.`username` = 'Palendrone') ORDER BY `carlist`.variety ASC");

Related

Sending options from html select box into database

Update: I’m now getting an error telling me that roomID is null and this is why it’s not going into the database. Can you see why it would be null when it should be the option that the user selects in the select box?
I'm working on a hotel booking system as an exercise. I am trying to make a form that will insert a new booking into the database. I have the customer and room IDS in the mySQL database and I have put them into HTML select boxes for the user to select an option.
This works fine until I try to save the new booking to the database. I don't get any errors and it tells me the booking has been saved on my page but if I go into the database it hasn't been saved. I have tried inserting the customerID and roomID values from text boxes so just typing it in instead of the drop down menu and that inserts into the database just fine.
I'm pretty sure the problem is something to do with getting the value out of the select box and into the POST variable but I'm not 100% sure. I've only been coding for 6 months so I don't really know what I'm doing! I've tried to figure it out by looking at other examples on here but nothing seems to work.
Here's my code:
Getting the data to fill the select boxes:
//Locate room names
$query = $query = 'SELECT `roomID` FROM `room`';
$result2 = mysqli_query($DBC,$query);
$rowcount = mysqli_num_rows($result2);
if ($rowcount > 0) {
$row = mysqli_fetch_assoc($result2);}
//Locate customerIDs
$query = $query = 'SELECT `customerID` FROM `customer`';
$result = mysqli_query($DBC,$query);
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
$row = mysqli_fetch_assoc($result);}
Creating Select boxes:
<form method="POST" action="newbooking.php">
<p>
<label for="customerID">Customer ID: </label>
<?php
echo "<select name='customerID'id='customerID' input type='number'>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='customerIDselect'>" . $row['customerID'] . "</option>";
//customerID
$customerID = cleanInput($_POST['customerIDselect']);
}
echo "</select>";
?>
</p>
<p>
<label for="rooms">Room (name, type, beds): </label>
<?php
echo "<select name='roomID'id='roomID' input type='number'>";
// output data of each row
while($row = $result2->fetch_assoc()) {
echo "<option value='roomIDselect'>" . $row['roomID'] . "</option>";
//roomID
$roomID = cleanInput($_POST['roomIDselect']);
}
echo "</select>";
?>
</p>
Inserting data into database:
//save the customer data if the error flag is still clear
if ($error == 0) {
$query = 'INSERT INTO `bookings` (`customerID`,`roomID`,`checkin`,`checkout`, `extras`) VALUES (?,?,?,?,?)';
$stmt = mysqli_prepare($DBC,$query); //prepare the query
mysqli_stmt_bind_param($stmt,'sssss', $customerID, $roomID, $checkin, $checkout, $extras);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "<h2>booking saved</h2>";
} else {
echo "<h2>$msg</h2>".PHP_EOL;
}

How to display multiple names from different Database tables

I"m trying to display names that connected to the same table.
There are 3 different DB tables:
Tables
Guests
Info
First I get the data from the "Table" to get the table id.
Than I get the data from the "Info" table to figure which guests are connected to the table id so I get their id's (can be multiple id's).
And last I get the name of every guest by it's id.
My issue is that I can only get the final name I'm expecting and not all names that are connected to the same table.
The last result needs to display each table and every name that connected to table.
PHP:
$sql_e1 = "SELECT `tid` FROM `table`";
$result_e1 = $con->query($sql_e1);
if ($result_e1->num_rows > 0) {
$i = 0;
while($row0 = $result_e1->fetch_assoc()) {
$table_id = $row0['tid'];
$array[$i]['table_id'] = $table_id;
$sql_e2 = "SELECT `id` FROM `info` WHERE `tid`='".$table_id."'";
$result_e2 = $con->query($sql_e2);
if ($result_e2->num_rows > 0) {
while($row2 = $result_e2->fetch_assoc()) {
$guest_id = $row2['id'];
$array[$i]['guest_id'] = $guest_id;
$sql_e3 = "SELECT `name` FROM `guests` WHERE `id`='".$guest_id."'";
$result_e3 = $con->query($sql_e3);
if ($result_e3->num_rows > 0) {
while($row3 = $result_e3->fetch_assoc()) {
$array[$i]['name'] = $row3['name'];
}
}
}
}
$i++;
}
}
$counter = 0;
HTML:
<?
if (isset($i)) {
while ($counter < $i) {
include 'infodialog.php';
?>
<div class="<? echo $array[$counter]['table_id']; ?>">
<p><? echo $array[$counter]['name']; ?></p>
</div>
<?
$counter++;
} } ?>
If you want to get multiple names in array your code should be:
$array[$i]['name'][] = $row3['name'];
Or according guest ids code should be
$array[$i][$guest_id]['name'][] = $row3['name'];
This will get all the names but you have to change your HTML code according array.
Another solution besides Rohit Rasela's is using JOINS. JOINS will be a much better solution in the long run especially when you start adding a lot of data and speed is important. It's been a while since I've done PHP and MySQL and I haven't tested this but it should work I believe:
MySQL:
SELECT
guests.name as GuestName,
table.tid as TableId,
info.id as InfoId
FROM table AS table
JOIN info AS info ON info.tid = table.tid
JOIN guests AS guests ON guests .id = info.[guest_id_column_name]
This will return a row for each match it finds when it goes through each table and you'll be able to loop through and access the GuestName, TableId and InfoId for each match. If you don't care about the table ids, you can leave them out in the SELECT list. You can add ORDER BY if the order matters.
HTML loop:
while ($row = $result->fetch_assoc()) {
<div>Guest name: <php echo $row['GuestName']; ?></div>
<div>Table Id: <php echo $row['TableId']; ?></div>
<div>Info Id: <php echo $row['InfoId']; ?></div>
}
You can get more information on JOINs at https://www.w3schools.com/sql/sql_join.asp

PHP echo list of users from a database depending on category

Depending on the input from checkboxes I'm trying to echo out users in a database based on category in a table linking the users-table with categories. But I only get one result for each category, even though I know there are several users in each category.
I have spent several dies seaching for the correct way to do this, and based upon the many tutoriels and articles out there I thought this method would work. But it does not.
This is the code that doesn't do what I want it to do:
function printusers($idcheck, $cat){
$sqlString = "SELECT userid FROM user_category WHERE categoryid ='$idcheck'";
$result = mysqli_query($dbLink, $sqlString) or die("Could not search for user id.." . mysqli_error($dbLink));
$row = mysqli_fetch_assoc($result);
// Make the first user on the list visable
mysqli_data_seek($result, 0);
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['userid'];
$sqlString = "SELECT name FROM users WHERE id='$id'";
$result = mysqli_query($dbLink, $sqlString) or die("Could not search for user.." . mysqli_error($dbLink));
$row = mysqli_fetch_assoc($result);
$name = $row['name'];
// echo users
echo "<h2 class=\"browsecategory\">Category: $cat</h2>
<p class=\"user\">Name: $name</p>\n";
}
}
if(isset($_POST['admins'])){
printusers(1, "Administrator");
}
I have also tried replacing the while loop with a foreach loop, like this:
foreach ($result as $row) {
same code as in while loop
}
This method echoed out several empty results. The HTML was there, but there was no information from the database. And the number of reults that were echoed was even higher than the number of results that the database should produce.
This is the HTML. A basic checkbox form:
<form action="results.php" method="POST">
<input type="checkbox" name="admins" id="admins">
<input type="checkbox" name="users" id="users">
<input type="checkbox" name="maillist" id="maillist">
<input type="submit" value="Browse">
</form>

PHP Dynamic drop down list for deleting rows

I am creating a deletion page for the removal of rows in the database. I have everything working up until the actual removal of the rows upon submit. The records display in the drop down without problem, any ideas of a solution are appreciated. (I am using deprecated SQL, I know.)
1ST PART OF PHP (FORM)
$query = 'SELECT event_name FROM event';
$result = mysql_query($query);
echo "<select name='events' value='-'>\n";
echo "<option value='Select event'>Select an event to be deleted\n";
while($row = mysql_fetch_row($result))
{
$eventSelect = $row[0];
echo "<option value='$eventSelect'>$eventSelect</option>\n";
}
echo "</select>"
2ND PART OF PHP (DELETION)
if (isset($_POST['eventSelect']))
{
$eventselection = $_POST['eventSelect'];
$query = "DELETE FROM event WHERE event_name = '$eventselection'";
$result = mysql_query($query);
}

PHP delete row via non PK

I have the user select a member ID, but I want it to delete the corresponding event ID (PK) so the row is just deleted. Can you suggest a simple and effective way of doing this? This is the code I am working on FYI.
Front end.
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
Select member ID to <b> remove total and comment. </b>: <select name="mid">
<?php
while($row = mysqli_fetch_assoc($result))
echo "<option value='{$row['mid']}'>{$row['mid']} </option>";
?>
</select>
<input type="submit" value=">!DELETE!<" />
</form>
<?php
}
else
{
$mid = $_POST['meid'];
$db1 = new dbme();
$db1->openDB();
$numofrows = $db1->delete_total($meid);//basically kill off the entire row
echo "Success. Number of rows affected:
<strong>{$numofrows}<strong>";
Back end method
function delete_total($mid, $meid) {
$sql = "DELETE FROM memberevent WHERE mid = $mid"; // This is the bit I am head scratching, might there be a way to use mid to identify the corresponding PK (meid) to delete so the entire row is killed?
$result = mysqli_query($this->conn, $sql);
if ($result) {
$numofrows = mysqli_affected_rows($this->conn);
return $numofrows;
}
else
$this->error_msg = "could not connect for some wierd reason";
return false ;
}
P.S I am aware it cannot work in its current form.
Here's the memberevent table structure.
meid (PK auto incr INT)
mid (int)
total (varchar)
comments (varchar)
ename (varchar)

Categories