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
Related
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>
I am trying to sum up the column of the row selected from the database and displays the result under the table display in my website. I am using new to PHP coding. Please help me. Below is my code:
Below the submit button, is a table where it will display the result of the search.
<form action="ViewAcc.php" method="get" >
Invoice/Check No.:<input type="text" name="rcchk">
<br>
OR
<br>
Retailer Name :<input type="text" name="rtsr">
<br>
<button class="button-special" value="Submit">SUBMIT</button>
</form>
<br>
<div class="9u 12u(mobile) important(mobile)">
<section align="left">
<table cellpadding="2px" cellspacing="2px" width="50%">
<tr><th>Invoice/Check No.</th><th>Retailer</th><th>Credit/Debit</th>
<th>Purpose</th></tr>
<?php
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['rcchk'] . "</td><td>" . $row['rtsr'] . "</td><td>"
. $row['crdbt'] . "</td><td>" . $row['purpose'] . "</td></tr>";
//$row['index'] the index here is a field name
}
?>
</table>
<table>
<tr><th></th><th>Total</th><th><?php echo $sum?></th><th></th></tr>
</table>
Below here is my PHP code:
<?php
include ('dbase.php');
$rcchk = $_GET['rcchk'];
$rtsr= $_GET['rtsr'];
$query = "SELECT * , sum(crdbt) as total FROM account WHERE rcchk='$rcchk' OR rtsr='$rtsr'";
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
include('ViewAccount.php');
include('ViewAccount_2.php');
mysql_close();
?>
How can I calculate the sum of the Credit/Debit column especially when I have selected only specific rows(based on the Invoice No. or Retailer Info) and where can I place the codes? Please help me.
<?php
$conn = mysqli_connect("localhost","root","","dbname");
$query = "SELECT * FROM `tablename` WHERE WHERE rcchk='$rcchk' OR rtsr='$rtsr'";
$sql = mysqli_query($conn,$query);
$sum = 0;
//echo $sum before the loop and give it value 0.
while($row = mysqli_fetch_array($sql)){
$sum += $row['crdbt'];
}
echo $sum;
?>
So I have a selector which gets its information from a database.
When I select something from the selector and press: Add to list, it generates a table with the selected information.
Now this what it should do. But now, when I select another result and press Add to list. It removes the old one and replaces it with the new one.
But I actually don't want it to remove the old one, but make a new row under it. So that table gets bigger. How do I do this?
Code for selector:
<!--Selector-->
<?php
//Get name and id data from the db. In an assoc array
$results = $database->Selector();
echo "<form name='form' method='POST' id='selector'>";
echo "<select name='train_name' id='train_name' multiple='multiple'>";
// Loop trough the results and make an option of every train_name
foreach($results as $res){
echo "<option value=" . $res['train_name'] . ">" . $res['train_name'] . "</option>";
}
echo "</select>";
echo "<br />" . "<td>" . "<input type='submit' name='Add' value='Add to list'/>" . "</td>";
echo "</form>";
if(isset($_POST["train_name"])){
//Get all data from database, in an assoc array
$results = $database->getAllAssoc();
//Make table headers
?>
<div id="train_select_table">
<form name="selector" method="post" action="customer_list.php?user_id=<?php echo $_SESSION['user_id']?>">
<table>
<tr>
<th>Train name</th>
<th>Number of bogies</th>
<th>Number of axles</th>
<th>Delete</th>
<th>More info</th>
<th>Check</th>
<!--Only for admins (later!)-->
<!--<th>XML</th>
<th>SQL</th> -->
</tr>
<div id="looprow">
<?php
foreach($results as $res){
//Loop trough results, generate a tablerow every time
?>
<tr>
<td name="train_name"><?php echo $res['train_name']?></td>
<td><?php echo $res['number_of_bogies']?></td>
<td><?php echo $res['number_of_axles']?></td>
<td>Delete</td>
<td>More Information</td>
<td><input type="checkbox" name="checkbox[]" value="<?php echo $res['train_id']?>"></td>
<!--Only for admins (later!)-->
<!--<td>XML</td>
<td>SQL</td>-->
</tr>
<?php
}
?>
</div>
</table><br />
<input name="Add to list" type="submit" id="add_to_list" value="add_to_list">
</form>
</div>
<?php
}
?>
Function:
function getAllAssoc() {
$sql = "SELECT * FROM train_information WHERE train_name = :train_name";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(":train_name", $_POST["train_name"]);
$sth->execute();
return $sth->fetchAll();
}
function selector() {
$sql = "SELECT train_name, train_id FROM train_information";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $sth->fetchAll();
}
I understand why it keeps replacing the old row. this is because I send a new query. but I don't know how to keep the old one.
as each time user will chose a single value while not mutiple value, so if you want to use the new value and the old value too, you should store the old value using cookie or session or hidden input in that form. It depends on you.
E.g. at the beginning, do this:
<?php
session_start();//make it be before your output if you want to use session or cookie
if(!$_SESSION['train_name']) $_SESSION['train_name'] = array();
if(isset($_POST["train_name"])) $_SESSION['train_name'] = array_merge ($_SESSION['train_name'], $_POST["train_name"]);
.......
//next step, inquiry with $_SESSION['train_name']
Simply change the name of your multiple select list from train_name to train_name[] as follows:
...
echo "<select name='train_name[]' id='train_name' multiple='multiple'>";
...
By this way your $_POST['train_name'] will be an array passed to bindParam
need some help here. It's a very simple web app i'm developing but just needed some help with something.
Here's what's setup. I have a html form with one combo box. All I need is to update this combo box with the entries from a mysql table named 'supplier'. The input to this table 'supplier' is via another form on my website which i've already setup. I need help in auto updating this combo box from the table 'supplier'. Please let me know the php code for it. I've included my code as well. Thanks in advance! I have included the html form as well.
replace your code
$result = mysql_query("SELECT supplier FROM supplier");
while($row = mysql_fetch_array($result))
{
/*echo '<form action="">';*/
echo "<select name='supplier'>";
echo "<option value = '$row[supplier]'>""</option>";
echo "</select>";
with
$result = mysql_query("SELECT supplier FROM supplier");
echo "<select name='supplier'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = '".$row[supplier]."'>".$row[supplier]."</option>";
}
echo "</select>";
So,
what is the problem? Is your script not working or do you want a active Combobox on one screen to be updated, when on another screen a new entry for supplier is entered?
Ok, some hints:
The "select"-Tag should be placed outside the loop.
Put the column name in "
Add a display-Value for the options
So, without checking it:
/*echo '<form action="">';*/
echo "<select name='supplier'>";
while($row = mysql_fetch_array($result))
{
echo "<option value = '".$row["supplier"]."'>".$row["supplier"]."</option>";
}
echo "</select>";
Your problem is here:
$result = mysql_query("SELECT supplier FROM supplier");
while($row = mysql_fetch_array($result))
{
/*echo '<form action="">';*/
echo "<select name='supplier'>";
echo "<option value = '$row[supplier]'>""</option>";
echo "</select>";
You're creating the drop down box (the Select) inside of the mysql data loop. As #Hitesh has explained. You need to create this outside of the loop and only echo out the data results within. For example:
$result = mysql_query("SELECT supplier FROM supplier");
echo "<select name='supplier'>";
while($row = mysql_fetch_array($result))
{
echo "<option value=".$row['supplier'].">".$row['supplier']."</option>";
}
echo "</select>";
This will output your drop down box, with all your supplier names as the value and the displayed text options.
If you attempted to do the following:
$result = mysql_query("SELECT supplier FROM supplier");
while($row = mysql_fetch_array($result))
{
/*echo '<form action="">';*/
echo "<select name='supplier'>";
echo "<option value = '$row[supplier]'>""</option>";
echo "</select>";
}
You would just end up with as many drop down boxes as you had suppliers in your database. This is because you're creating a new Select box for each record found.
Also, without specifying the second $row['supplier'] between the option tags, you'd just end up with a blank (empty) drop down box.
Hope this helps.
Here is complete code:
PHP Code:
<?php
// select box open tag
$selectBoxOpen = "<select name='supplier'>";
// select box close tag
$selectBoxClose = "</select>";
// select box option tag
$selectBoxOption = '';
// connect mysql server
$con = mysql_connect("localhost","user","pass");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
// select database
mysql_select_db("rtgs", $con);
// fire mysql query
$result = mysql_query("SELECT supplier FROM supplier");
// play with return result array
while($row = mysql_fetch_array($result)){
$selectBoxOption .="<option value = '".$row['supplier']."'>".$row['supplier']."</option>";
}
// create select box tag with mysql result
$selectBox = $selectBoxOpen.$selectBoxOption.$selectBoxClose;
?>
HTML Code:
<form action="ntxn.php" method="post">
<table>
<tr>
<td>Supplier Name:</td>
<td>
<?php echo $selectBox;?>
</td>
</tr>
<tr>
<td>Bill No. :</td>
<td><input type ="text" name="billno"/></td>
</tr>
<tr>
<td>Bill Date : </td>
<td><input type="date" name="billdate"/></td>
</tr>
<tr>
<td>Bill Amount : </td>
<td><input type="text" name="billamt"/></td>
</tr>
<tr>
<td>NEFT / RTGS No. :</td>
<td><input type="text" name="rtgs"/></td>
</tr>
<tr>
<td><input type="submit" name="Save"/></td>
</tr>
</table>
</form>
I have created a while loop
while($row = mysql_fetch_Array($result)) {
echo '<tr class="record"> <td></td><td>'
. $row['company'] .'</td><td>'
. $row['project'].'</td><td>'
. $row['assignee']. '</td><td>'
. $row['current_milestone'] . '</td><td>'
. $date=date("d-m-Y", strtotime($row['start_date'])).'</td><td>' ..'</td><td>'
. $row['next_milestone'] . '</td><td>'
. $date=date("d-m-Y", strtotime($row['next_date']))
.'</td></tr>' ;
}
This displays correctly but my question is:
How can the user select an individual row so he/she can edit it. I was hoping that the user can select which row they wanted and they would be taken to another screen where they can make the changes. I can figure out how to do the part where I can update the data. But it is the selecting the row and collecting correct data I dont understand how to do.
Embed an <a href='update.php?id=> somewhere in there which carries the record id to the update script as a parameter in the query string:
while($row = mysql_fetch_Array($result)) {
echo '<tr class="record"> <td></td><td>'
// Insert a link with an id parameter.
// Use whatever column value uniquely identifies your row
. ' Edit this! '
// etc...
// etc...
// etc...
.'</td></tr>' ;
}
And retrieve it on the update script via:
// Assuming an integer id was passed...
// if it is some other string value, escape and quote it accordingly.
$id = intval($_GET['id']);
And you will want to check that the user making the edit has permission to edit that record. In other words, verify that the record is owned by the user is logged in, since anyone could technically visit the URL with any id, whether or not it belongs to them. As in:
UPDATE yourtable SET col1 = 'whatever', col2 = 'whatever' WHERE id = $id AND user_id = 'logged_in_user'
Create some sort of primary key (a new field that will be different for each row/entry) in your database. Example: an ID field
Create a separate page for updating that accepts a GET parameter id. Ex: update.php
Validate and sanitize the id parameter (ensure it is a valid id, not an SQL injection attempt, and the user has the privileges to edit this id)
Load info from database for that id. Ex: SELECT fields FROM table WHERE id = $id
Display a form so user can edit the information.
Validate form input and update the table. Ex: UPDATE table SET field1=newVal WHERE id = $ID
First of all, you need to create a primary key in the table, suppose primary_key in this case, so as to access the particular row having a definite and unique ID.
Secondly, add one more column to your table:
while($row = mysql_fetch_Array($result)){
echo '<tr class="record"> <td></td><td>'
. $row['company'] .'</td><td>'
. $row['project'].'</td><td>'
. $row['assignee']. '</td><td>'
. $row['current_milestone'] . '</td><td>'
. $date=date("d-m-Y", strtotime($row['start_date'])).'</td><td>' ..'</td><td>'
. $row['next_milestone'] . '</td><td>'
. $date=date("d-m-Y", strtotime($row['next_date']))
.'</td>' ;
?>
<td>
<form action='update.php' method='post'>
<input type="hidden" name="id" value="<?php echo $row['primary_key']; ?>">
<input type="submit" value="Edit">
</form>
</td>
<?php
echo "</tr>";
}
?>
And now you know which row's details you need to display in the form at update.php
The code on update.php goes like:
<?php
$id = $_POST['id'];
$result = mysql_query("SELECT * FROM table WHERE primary_key = '$id'");
$info = mysql_fetch_array($result);
?>
<form action='target.php' method='post'>
Company: <input type="text" name="company" value="<?php echo $info['company']; ?>">
Project: <input type="text" name="project" value="<?php echo $info['project']; ?>">
.
.
<input type="hidden" name="id" value="<?php echo $info['primary_key']; ?>">
<input type="submit" value="Save Changes">
</form>
And then on target.php all you have to do is use the command:
mysql_query("UPDATE table SET company='".$_POST['company']."' AND project='".$_POST['project']."' WHERE primary_key='".$_POST['id']."');