Select multiple options from option - php

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

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

Independent radiobuttons for each row read from server

I'm currently trying to generate independent radio buttons for each row read from my server. They are supposed to symbolize ON and OFF Switches. My current issue is that I manage to generate buttons for each row but these are not independent. I can only turn one off or on at a time.
I know that radio buttons become truly "independent" when the name of each is different. But I can't seem to figure out a way to create a new name for each row generated.
Currently my code looks like this
res = $db->query($query);
if ($res->num_rows > 0) {
while ($row = $res->fetch_object()) {
$query = "SELECT * FROM device_status
WHERE device = ($row->id)";
$status = $db->query($query);
$device_status = $status->fetch_object();
$content .= <<<END
<tr>
<td>{$row->devices}</td>
<td>{$row->description}</td>
<td>{$row->room}</td>
<td><input type='radio' name='radiobutton' id='myCheck'></td>
<td><input type='radio' name='radiobutton' id='myCheck' checked='checked'></td>
<!-- <td>{$device_status->status}</td> -->
<td>Delete
Edit</td>
</tr>
END;
}
}
echo $content;
I've been trying different methods such as using <td><input type='radio' name='$row->id' id='myCheck'></td>
But have not gotten it to work. Any help on how to solve this issue is greatly appreciated.
Thank you!
If you want the unique names for all the checkboxes generated you can have them by just incrementing $i for each row.
res = $db->query($query);
if ($res->num_rows > 0) {
$i = 0;
while ($row = $res->fetch_object()) {
$query = "SELECT * FROM device_status
WHERE device = ($row->id)";
$status = $db->query($query);
$device_status = $status->fetch_object();
$content .= <<<END
<tr>
<td>{$row->devices}</td>
<td>{$row->description}</td>
<td>{$row->room}</td>
<td><input type='radio' name='radiobutton<?php echo $i?>' id='myCheck'></td>
<td><input type='radio' name='radiobutton<?php echo $i?>' id='myCheck' checked='checked'></td>
<!-- <td>{$device_status->status}</td> -->
<td>Delete
Edit</td>
</tr>
END;
$i++;
}
}
echo $content;
If you do not care about the name of the radio button, you could use a "php random number generator", each row you asign a new random number to your radio button name:
<?php $x = rand(5, 100000); ?> <input type='radio' name='<?php echo $x; ?>' id='myCheck'>

Can't figure out how to process delete button when it is clicked

I am trying to add a 'delete' button on my item table and have a delete button to delete the item and the information about the both item and the seller. I have the delete button on the table but I cannot figure out how to process that button when it is clicked. Please help! Thank you in advance!!
<?php
require 'authentication.inc';
// connect to the server
$connection = sqlsrv_connect( $hostName, $connectionInfo )
or die("ERROR: selecting database server failed");
// prepare SQL query
$UserID = $_SESSION['userID'];
$query = "SELECT * FROM ITEM WHERE userID= '$UserID'";
// Execute SQL query
$query_result = sqlsrv_query($connection, $query)
or die( "ERROR: Query is wrong");
// Output query results: HTML table
echo "<table border=1>";
echo "<tr>";
// fetch attribute names
foreach( sqlsrv_field_metadata($query_result) as $fieldMetadata)
echo "<th>".$fieldMetadata['Name']."</th>";
echo "</tr>";
// fetch table records
while ($line = sqlsrv_fetch_array($query_result, SQLSRV_FETCH_ASSOC)) {
echo "<tr>\n";
foreach ($line as $cell) {
echo "<td> $cell </td>";
}
echo "<td></td>";
echo "</tr>\n";
}
echo "</table>";
// close the connection with database
sqlsrv_close($connection);
?>
To add a delete feature you need two things, a button and secondly the processing of said button. I am not sure what your unique value is in the table, so I am using this fictitious key: itemID. Update with whatever your unique column name is.
Replace your table loop with:
<table border=1>
<tr>
<?php
// fetch attribute names
foreach( sqlsrv_field_metadata($query_result) as $fieldMetadata)
echo "<th>".$fieldMetadata['Name']."</th>"; ?>
</tr>
<?php
// fetch table records
while ($line = sqlsrv_fetch_array($query_result, SQLSRV_FETCH_ASSOC)) { ?>
<tr>
<?php foreach ($line as $cell) {
echo "<td> $cell </td>";
} ?>
<td>
<form method="post">
<input type="hidden" name="itemID" value="<?php echo $line['itemID']; ?>" />
<input type="submit" name="action" value="DELETE" />
</form>
</td>
</tr>
<?php } ?>
</table>
In the processing portion at the top, add processing:
if(!empty($_POST['action']) && ($_POST['action'] == 'DELETE')) {
// Do some sort of validation here
if(is_numeric($_POST['itemID']))
sqlsrv_query($connection, "delete from ITEM where itemID = '".$_POST['itemID']."'");
}

Updating an HTML combo box from MySQL DB using PHP

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>

php checkbox from mysql

I've managed to pull records from a mysql database using php with a checkbox to select. I'm struggling to make the selected records (with the checkboxes) appear on a new page. Here is my code so far:
<?php
include('connect.php');
$query = 'SELECT * FROM grades';
if ($r = mysql_query($query)) {
print "<form>
<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['InstitutionName']}</td>
<td>{$row['InstitutionAddress']}</td>
<td>{$row['SubjectArea']}</td>
<td><input type='checkbox' name='check[$row{['GradeID']}] value='check' /></td>
</tr>";
}
print "</table>
</form>";
$checkbox[] = isset($_POST['checkbox']) ? true : false;
} else {
print '<p style="color: blue">Error!</p>';
}
?>
<html>
<form action="check2.php" method="POST">
<input type='submit' name='Submit' value='Submit'>
</html>
And on the page where I want the selected records to display, I have:
<?php
if(isset($checkbox))
{
foreach($checkbox as $value)
{
echo $value."<br>"; //it will print the value of your checkbox that you checked
}
}
?>
Any assistance would be appreciated!
Put checked="checked" just like you have put value="check":
<td><input type='checkbox' name='check[$row{['GradeID']}] value='check' checked="checked" /></td>
Edit:
Probably I misunderstood you. What do you expect to see?
First, you should make the form to perform POST request instead of GET (default):
print "<form method='POST' action='THE_FILE_YOU_PRINT_RESULTS.php'>"
Then in "THE_FILE_YOU_PRINT_RESULTS.php" do a print_r($_POST); to see what you get and how to display it.
A better way to do this would be to name your checkboxes check[]. Each checkbox value should then be the ID (rather than check).
Then on your results page, just loop through each instance of check[] and print the value out.
check[$row{['GradeID']}]
Seems incorrect to me, should it be:
check[{$row['GradeID']}]
Notice the moved opening curly bracket to before the $
Sorry if this is wrong haven't used PHP in long time but it stood out for me
The are a couple of error in the form print function.
You have to put the action on the first form, not on the second, you have to change the way how you print the checkbox as well.
Try to print the form in this way:
<?php
include('connect.php');
$query = 'SELECT * FROM grades';
if ($r = mysql_query($query)) {
print "
<form action=\"check2.php\" method=\"POST\">
<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['InstitutionName']}</td>
<td>{$row['InstitutionAddress']}</td>
<td>{$row['SubjectArea']}</td>
<td><input type='checkbox' name='check[".$row['GradeID']."] value='".$row['GradeID']."' /></td>
</tr>";
}
print "</table>
<input type='submit' name='Submit' value='Submit'>
</form>";
$checkbox[] = isset($_POST['checkbox']) ? true : false;
} else {
print '<p style="color: blue">Error!</p>';
}
?>
And print the checked box reading the _REQUEST array:
<?php
if(isset($_REQUEST["check"]))
{
foreach($_REQUEST["check"] as $key=>$value)
{
echo $key."<br>"; //it will print the value of your checkbox that you checked
}
}
?>
This should work.

Categories