insert radio values from within loop into database PHP - php

OK, so this is the last hurdle in the development side of my uni project, which is due VERY soon, I need to pick my daughter up from school in a minute (so I apologise for any delay in response - I assure you that I have not disappeared).
OK, so I am displaying various times (booking slots) to users which have been retrieved from the database. The user can then select the radio button relating the the time slot they wish to book. I have appended a counter so that the radio buttons each have a unique id. Upon clicking the 'book appointment' button the startTime value and slotId values need to be inserted into the bookings table, along with the bookingId from the availability table and userId from the users table, based on the current SESSION.
My problem is that as the radio buttons have different values, I am unsure how to define which radio button has been selected, and therefore how to write the query in which to insert the data relating to each unique radio button.
I know there is going to be an if statement in there somewhere, I am just not sure how to approach it, I have spent ages mulling this over, I am running out of time, the dog is driving me insane and my daughter means that time is very limited, so I really do appreciate any help or guidance offered :)
bookings.php
`
}
?>
<!--Display available slots based on chosen date-->
<?php
if(isset($_POST['getDate'])){
$datepicker = strip_tags($_POST['datepicker']);
$datepicker = $DBcon->real_escape_string($datepicker);
$sql=("SELECT slotId, startTime, endTime, date FROM availability
WHERE date= '".$datepicker."'");
$query_s=mysqli_query($DBcon, $sql);
$row=mysqli_fetch_array($query_s);
if (!$row) {echo 'Error, No bookings available for this date,
please choose another';}
$counter = 1;
while ($row=mysqli_fetch_array($query_s)){
$id = 'slot_id'.$counter;
$counter++;
//echo '<div class="col-lg-3 col-md-3 col-sm-4 col-xs-6">';
?>
<table class="table-responsive">
<form class="form-bookings" method="post" action="<?php echo
htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
<tbody>
<tr>
<td><?php echo $row['startTime'] ?></td>
<td><?php echo $row ['endTime'] ?></td>
<td><input type="radio" name="<?php echo ['slotId']?
>" id="<?php $id ?>" Value="<?php echo ['startTime']?>"></td>
<td><?php echo $id ?></td>
</tr>
</tbody>
<?php
}
}
?>
</form>
</table>
</div>
</div>
</div>`
Bookings Table columns are:
`bookingId
slotId
userId
startTime`

Last edit (09.06.2017):
<?php
/*
* Some general recommendations:
*
* - Always provide semicolons (;) in PHP codes.
* - Maintain lowercase for the HTML attributes.
* - Start/end HTML tags on the same page scope. Same for PHP codes.
* - Don't write text direct in body. Wrap it in span, div, label, etc, first.
* - The HTML tags should also have a coressponding end/close tag.
* Only the ones that requires it (div, span, etc).
* Breaks, inputs, etc don't require this
* - Always validate $_GET, $_POST, $_SESSION, etc, values
* and assign defaults if not valid.
* - Use camelCase when naming PHP variables.
* - Preserve table structure definition. Inject HTML tags only where they belong.
* When using forms (<form>) with tables (<table>), insert them just in TD's (<td>),
* not anywhere else. Or wrap the whole table in a form.
*/
// Code for session starting and includes...
?>
<!DOCTYPE HTML>
<html>
<head>
<title>App/page title</title>
</head>
<body>
<?php
try {
//-------------------------------------------------------
// Read the user ID from session.
//-------------------------------------------------------
$userId = isset($_SESSION['userId']) ? $_SESSION['userId'] : NULL;
/*
* -----------------------------------
* Upon submission by book app button.
* -----------------------------------
*/
$bookApp = isset($_POST['bookApp']) ? $_POST['bookApp'] : NULL;
if (isset($bookApp)) {
$bookingMessages = '';
// Get posted availabilityId.
$receivedAvailabilityId = isset($_POST['availability']) ? $_POST['availability'] : NULL;
// Insert availability_id & user_id into bookings
if (isset($receivedAvailabilityId)) {
/*
* -------------------------------------------
* Insert the booking information into the DB.
* -------------------------------------------
*/
$sqlBookAvailability = "INSERT INTO bookings (availability_id, user_id) VALUES (" . $receivedAvailabilityId . ", " . $userId . ")";
$isAvailabilityBooked = mysqli_query($DBcon, $sqlBookAvailability);
if (!$isAvailabilityBooked) {
throw new Exception('The selected availability could not be booked.');
}
// Get last inserted booking ID upon booking.
$lastInsertedBookingId = mysqli_insert_id($DBcon);
if ($lastInsertedBookingId == 0) {
throw new Exception('The selected availability could not be booked.');
}
$bookingMessages .= "The selected availability were successfully booked. Booking ID: " . $lastInsertedBookingId . ".";
$bookingMessages .= "<br/>";
} else {
$bookingMessages .= "Please choose an availability.";
$bookingMessages .= "<br/>";
}
echo $bookingMessages;
}
/*
* ----------------------------------------
* Upon selection of a date in date picker.
* ----------------------------------------
*/
// Read selected date from date picker.
$getDate = isset($_POST['getDate']) ? $_POST['getDate'] : NULL;
if (isset($getDate)) {
$postDatePicker = isset($_POST['datepicker']) ? $_POST['datepicker'] : NULL;
$strippedDatePicker = strip_tags($postDatePicker);
$datePicker = mysqli_real_escape_string($DBcon, $strippedDatePicker);
/*
* ---------------------------------
* Display available availabilities.
* ---------------------------------
*/
$sqlBookedAvailabilities = "SELECT av.id, av.start_time, av.end_time, av.date
FROM availabilities as av
LEFT JOIN bookings AS bo ON bo.availability_id = av.id
WHERE bo.id IS NULL AND av.date = '" . $datePicker . "'";
$queryBookedAvailabilities = mysqli_query($DBcon, $sqlBookedAvailabilities);
if (!$queryBookedAvailabilities || mysqli_num_rows($queryBookedAvailabilities) == 0) {
echo 'No bookings available for this date, please choose another.';
echo '<br/>';
} else {
?>
<form id="chooseAvailabilities" class="form-bookings" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" autocomplete="off">
<table class="table-responsive">
<tbody>
<?php
// Read availabilities list.
while ($rowAvailability = mysqli_fetch_array($queryBookedAvailabilities)) {
$availabilityId = $rowAvailability['id'];
$availabilityStartTime = $rowAvailability['start_time'];
$availabilityEndTime = $rowAvailability ['end_time'];
?>
<tr>
<td>
<?php echo $availabilityStartTime; ?>
</td>
<td>
<?php echo $availabilityEndTime; ?>
</td>
<td>
<input type="radio" name="availability" id="availability_id<?php echo $availabilityId; ?>" value="<?php echo $availabilityId; ?>">
</td>
<td>
</td>
</tr>
<?php
} // End reading availabilities list.
?>
<tr class="book-appointment-outer-wrapper">
<td colspan="4" class="book-appointment-inner-wrapper">
<button type="submit" class="btn btn-default" name="bookApp">
Book Appointment
</button>
</td>
</tr>
</tbody>
</table>
</form>
<?php
}
} // End reading date from date picker.
$closed = mysqli_close($DBcon);
if (!$closed) {
echo 'The database connection can not be closed!';
}
} catch (Exception $exception) {
echo $exception->getMessage();
exit();
}
?>
</body>
</html>

Related

How to create a form that uses data from multiple lines?

First of all, I'm aware that the title is not very clear, it's because I'm having trouble put the issue I have into words, so if anyone understands what I'm about to describe, please suggest a new title for me to edit.
Now for the main problem, I will do my best to explain it :
The user ( a teacher ) logs in, he then chooses one of the classes he teaches, the website displays a list of the students that are in that class as a table.
the table contains 3 columns : Name , lastName, Present.
Present is a column containing 2 radio buttons : Absent & Present.
I want the teacher to choose one of them for every student, then press "Submit".
The submit will result in the insertion of data into a table that contains the ID of the student that was absent, the current date, and the ID of the class. Here is the code for showing the table :
<?php if (isset($_GET['choice'])) {
$choice = $_GET['choice'];
$showquery = $conn->prepare('select Nom,Prenom,etudiant_ID from etudiant where classe_id = (select classe_id from classe where abreviation= ?)');
$showquery->execute(array($choice));
echo $choice;
echo ("<form>");
echo "<table border='1'>
<tr>
<th>Nom</th>
<th>Prenom</th>
<th> Presence</th>
</tr>";
while ($row = $showquery -> fetch(PDO::FETCH_ASSOC)) {
$counter = $row['etudiant_ID'];
echo "<tr>";
echo "<td>" . $row['Nom'] . "</td>";
echo "<td>" . $row['Prenom'] . "</td>"; ?>
<td> Present <input type="radio" name="presence<?=$counter?>" value='present' checked>
Absent <input type="radio" name="presence<?=$counter?>" value="absent">
</td>
<?php
echo "</tr>";
}
echo "</table>";
echo ("<input name='matiere' placeholder='matiere..' required > ");
echo ("<form>");
} ?>
</main>
Here is an image that could help you better understand :
The table that is inside the form

Why is the last iteration given, instead of the current one?

I have some PHP & HTML code which fetches id's, names & statuses from a mysql database.
Using buttons and $_POST i'm attempting to update the MYSQL database when said the users button is clicked (it's a simple in/out board)
Here is my code
<?php
include 'confile.php';
if(isset($_POST['update'])) {
echo $_POST['update']. " "; //test to show correct name
echo $_POST['staffid']; //test to show the correct staffid << **THIS IS WHERE THE ISSUE IS**
//$incid = $_POST['staffid'];
//$sql = "SELECT status FROM staff WHERE id=$incid";
//$result = $conn->query($sql);
//echo $result; //show the status
} else {
//do nothing.
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<title>Staff Board</title>
<body>
<div align="center" class="header">
<div class="header text">
<h1>Staff Board</h1>
</div>
<div class="header logo">
<img src="/assets/img/logo.gif" width="64px" height="64px">
</div>
</div>
<div id="conbox" align="center" class="content">
<hr>
<?php
//get all staff and their statuses
$sql = "SELECT id, firstname, surname, status FROM $staff ORDER BY surname ASC";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
// assign results to values
$id = $row["id"];
$firstname = $row["firstname"];
$surname = $row["surname"];
$status = $row["status"];
$fullname = $firstname . " " . $surname . " " . $id; //The $id variable will be dropped from here... it's just for testing. note, it works here, the correct ID is added to the button value
if ($status == 1) { //pick the correct color for the status
$color = "butGreen";
} else {
$color = "butRed";
}
?>
<form class="staffGrid" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<input type="hidden" id="staffid" name="staffid" value="<?php echo htmlspecialchars($id); ?>"/> <!-- hidden input to pass the id to $_POST -->
<input type="submit" id="update" name="update" value="<?php echo htmlspecialchars($fullname); ?>"/> <!-- submit button to trigger POST -->
</form> <!-- added as per devpro & billyonecan -->
<?php
};
?>
</div>
</div>
</body>
</html>
When I first load the page, the buttons show correctly, and there is no test output at the top of the page, which I expect.
however, when I click a button, the page refreshes correctly, and shows the correct name for the button being pushed (from the echo on line 5), but the wrong staffid is given. It gives the LAST id for the while loop, instead of correct value for that button.
I had assumed that for each iteration, the values would be set for that specific element (the button)... obviously i'm incorrect here.
Why is this happening and how do I fix it?
Additional info
Confile.php has the following variables used in the code:-
$conn = new mysqli($server, $username, $password);
$staff = [Location of db table]
some output :-
echo $sql;
SELECT id, firstname, surname, status FROM inout.staff ORDER BY surname ASC
echo print_r($_POST);
Array ( [staffid] => 17 [update] => First Second 8 )
The solution was to ensure that the closing tag was present in the code, and in the correct location to prevent erroneous iteration!

How to insert and update value into database table php

I am beginner in PHP and i want to insert value into my database table for my drop-down value using PHP insert query, I am having an error to insert data and also want to update the existence value of database table when insert new value into database table, here is my code help me to solve it, My Code is below :
<?php
include 'dbconfig.php';
?>
<html>
<head>
<title>Sales Panel App</title>
</head>
<body>
<form method="POST" name="myForm" action="<?php $_PHP_SELF ?>">
<table border="1">
<tr>
<td>Sales Person List</td>
<td>
<?php
$sql="select name,id from sales order by name";
echo "<select name = 'salelist' value=''>Sales Person Name</option>";
echo "<option value = 'Select Sales Person' selected>Select Sales Person</option>";
{
foreach ($conn->query($sql) as $row){
echo "<option value=$row[id]>$row[name]</option>";
}
echo "</select>";
}
echo "<br>";
?>
</td>
</tr>
<tr>
<td>No of Panels</td>
<td><input type="text" name="panelnumber" size="1"></td>
</tr>
</table>
<p><input type="submit" value="Submit" name="submit" id="submitdata"></p>
</form>
<?php
$salelist = $_POST['salelist'];
$panelnumber = $_POST['panelnumber'];
$sql2 = "select * from sales where name = $salelist";
$result = mysqli_query($sql2);
if ($row = mysqli_fetch_array($result)) {
$oldvalue = $panelnumber;
$newvalue = $oldvalue + $panelnumber;
$query = 'update sales where name = $panelnumber';
}
else {
$qry = "insert into sales (id, name, panelnumber) values ('', $salelist, $panelnumber)";
}
?>
</body>
</html>
Your problem is here
$query = 'update sales where name = $panelnumber';
You are not saying what to update. You have to use one of the methods available to update an SQL row.
For example, a correct one should be:
$query = "update sales set city='rio' where name = '$panelnumber'";
Here is the official MySQL Documentation.
And you have one more error, if you write this:
$number = 5;
$variable = '$number';
echo $variable;
The output of $variable will not be "5", will be "$number", literally. If you want to set a variable in a string, you must us double quote (") not single quote (') because single quote will literally save what is between them, and double will try to "translate" variables and other stuff.
The correct way would be:
$number = 5;
$variable = "$number";
echo $variable;
Here you have a detailed PHP official explanation about what I am describing.

Pass PHP array through Select Option Fields

I am writing a basic CMS system and have come across something which should be seemingly simple -but is beginning to frustrate me.!
I am trying to pass an array through a select option field to populate a list of categories in which I can save a post.
I have a 'posts' form which comprises of 3 fields. Title, content and Category ID (CatID).
When the user creates a post, they can select the category they wish to assign the post assigned to by using a drop down list - (this is populated by using a different form).
So the technical bit; -
MySQL DB:-
categories = catname (char60 PRIMARY), catid (INT10, AI)
posts = id (bigint20 PRIMARY), catid (int10 PRIMARY), title (text), content (varchar255)
Example of categories populates: catname = Home / catid = 1 ...etc
Output.php ;
<?php
function display_post_form($post = '') {
$edit = is_array($post);
?>
<form action="<?php echo $edit ? 'edit.php' : 'add.php' ; ?>" method="post">
<table border="0">
<tr>
<td> Title:</td>
<td> <input type="text" name="title" value="<?php echo $edit ? $post['title'] : '' ; ?>" size="60" /> </td>
</tr><tr>
<td> Content:</td>
<td> <textarea id="editor1" name="content" value="<?php echo $edit ? $post['content'] : '' ; ?>"> </textarea> </td>
</tr><tr>
<td> Category:</td>
<td><select name="catid">
<?php
$cat_array = get_categories($catid, $catname);
foreach($cat_array as $thiscat) {
echo "<option value=\"".$thiscat['catid']."\" ";
if (($edit) && ($thiscat['catid'] == $post['catid'])) {
echo " selected";
}
echo ">".$thiscat['catname']."</option>";
}
?>
</select>
</td>
</tr><tr>
<td> Button:</td>
<td <?php if (!$edit) { echo "colspan=2"; } ?> align="center">
<?php
if ($edit)
echo "<input type=\"hidden\" name=\"_id\" value=\"". $post['id'] ."\" />";
?>
<input type="submit" value="<?php echo $edit ? 'Update' : 'Add' ; ?> Post" />
</form></td>
</td>
</tr>
</table>
</form>
<?php
}
?>
Functions.php ;
function get_categories($catid, $catname) {
$conn = db_connect();
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL " .mysqli_connect_error();
}
$sql = "SELECT catname, catid FROM categories";
$result = mysqli_query($conn, $sql) or die(" Could not query database");
while($row = mysqli_fetch_assoc($result)) {
printf("\n %s %s |\n",$row["catname"],$row["catid"]);
}
mysqli_close($conn);
}
I am able to call in the 'get_cattegories()' function which generates a flat data of categories and their respective id's. I then combined this with the Select Option Field in the Output.php file and it doesn't generate anything.
Can anyone give some useful tips or advice? Many thanks :)
You are not returning the array but printing a string to the output. Change printf to return:
function get_categories($catid, $catname) {
$conn = db_connect();
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL " .mysqli_connect_error();
}
$sql = "SELECT catname, catid FROM categories";
$result = mysqli_query($conn, $sql) or die(" Could not query database");
$categories = array();
while($row = mysqli_fetch_assoc($result)) {
$categories[] = $row;
}
mysqli_close($conn);
return $categories;
}
Also I agree for the comments to your question. The arguments are useless.
You also may refactor the code, actually... alot. Move the mysql_connect() to the other place, probably at the beginning of your script.
I suggest to use some frameworks. I think KohanaPHP will be a good start. You will learn about architecture and some design patterns. Keep the good work and improve your skills ;-)

While loop for inserting values for each rows into the database using single submit button

Currently, I am working on the attendance form. In this interface, it consists rows of student(get from student table). The list of students are viewed in the table. the first column is NO, second column in Birth No, third STudent Name, forth Attendance. in column attendance, there are three radio button which is PT, AT, and MC which their value is present, absent, and mc respectively. The outside of the table, there is a submit button. Teacher needs to click which attendance of the student, either pt, at or mc. Teacher needs to click for all students. When submit button clicked by teacher, attendance of the students will be inserted into the database. When I execute code below, there nothing value is inserted in the database. Can some please help me to figure it out where i went wrong? I worked on this code for past 2 weeks yet still not getting an expected result. Thank you.
$getdata = mysql_query("select * from student where
class = '$class' order by name ") or die(mysql_query);
if (isset($_POST['submit'])){
$id = 1;
while($row = mysql_fetch_assoc($getdata)){
if(isset($_POST['a'.$id])) {
$status = $_POST['a'.$id];
if(!empty($status)){
if(($status == "present" || $status == "mc")){
$attend = 1;
}
else if($status == "absent"){
$attend = 0;
}
$query = "INSERT INTO attendance(birth_no, date, status, attend)
VALUES ('$birth_no','$date','$status','$attend')";
if($query_run = mysql_query($query)){
echo 'Insert attendance done';
}
else{
echo'Attendance not inserted.';
}
}
else{
echo 'Please enter all fields';
}
}
$id ++;
}
}
else {
?>
<form action="addattend.php" method = "POST">
<table>
<?php
$id = 1;
while($row = mysql_fetch_assoc($getdata)){
$birth_no= $row['birth_no'];
$name = $row['name'];
?>
<tr>
<td><center><?php echo $id ?></center></td>
<td><center><?php echo $date ?></center></td>
<td><center><?php echo $birth_no ?></center></td>
<td><center><?php echo $name ?></center></td>
<td>
<input type="radio" name="a<?php echo $id; ?>" value="present">PT
<input type="radio" name="a<?php echo $id; ?>" value="absent">AT
<input type="radio" name="a<?php echo $id; ?>" value="mc">MC
</td>
</tr>
<?php
$id ++;
} // end while
?>
</table>
<center><input type="submit" name="submit" value="Submit"></center>
</form> <!-- end the form here -->
<?php
} // end else
?>
this is what i meant about the interface(picture below)
for every row, there are 3 radio buttons. The list of student was retrieved from the database. Teachers need to select the attendance for all students. with a single submit button, All the attendance will be inserted in the database with birth_no, date(selected earlier by teacher) and also $attend which is assigned after attendance selected.
I don't get it when you said use primary key instead of $id
Let me explain: When you use the while loop with $id you increment the $id for each while loop. What if your table is missing the primary key '1' or any one for that matter? Answer: The first row may not be correlating to the primary key of '1'. Let me further explain with some data:
An example table:
student_id | name
-----------+--------
1 | John
3 | Jane
4 | Bob
now lets loop through with a while using sudo code
$id = 1;
while(row exists){
print row['name']." has primary key of $id";
$id++;
}
This would print something similar to:
John has primary key of 1
Jane has primary key of 2
Bob has primary key of 3
Which would be incorrect.
Here is how I would go about doing something like this, this code may need slight adaptation for your specific use:
<?php
$getdata = mysql_query("select * from student where
class = '$class' order by name ") or die(mysql_query);
if (isset($_POST['submit'])){
while($row = mysql_fetch_assoc($getdata)){
//set the id equal to the primary key
$id = $row["birth_no"];
$date = date("Y-m-d");
if(isset($_POST['a'.$id])) {
$status = $_POST['a'.$id];
if(!empty($status)){
if(($status == "present" || $status == "mc")){
$attend = 1;
}
else {
$attend = 0;
}
$query = "INSERT INTO attendance(birth_no, date, status, attend)
VALUES ('$id','$date','$status','$attend')";
if($query_run = mysql_query($query)){
echo 'Insert attendance done';
}
else{
echo'Attendance not inserted.';
}
}
else{
echo 'Please enter all fields';
}
}
}
}
else {
?>
<form action="addattend.php" method = "POST">
<table>
<?php
while($row = mysql_fetch_assoc($getdata)){
$birth_no = $row['birth_no'];
$name = $row['name'];
?>
<tr>
<td><center><?php echo date("F j, Y") ?></center></td>
<td><center><?php echo $birth_no ?></center></td>
<td><center><?php echo $name ?></center></td>
<td>
<input type="radio" name="a<?php echo $birth_no; ?>" value="present">PT
<input type="radio" name="a<?php echo $birth_no; ?>" value="absent">AT
<input type="radio" name="a<?php echo $birth_no; ?>" value="mc">MC
</td>
</tr>
<?php
} // end while
?>
</table>
<center><input type="submit" name="submit" value="Submit"></center>
</form> <!-- end the form here -->
<?php
} // end else
?>

Categories