how to populate html dropdown with sql data - php

I am new to PHP, hoping for some help please.
I am trying to populate an HTML dropdown list with data from my SQL database.
I would like to be able to select an item from a dropdown list that would then fill an HTML table with the associated record from the database.
So far I have managed to connect to my database and retrieve all of the data from the relevant table.
Can someone please help me set this up to work through the dropdown list?
Thanks
<?php
$username = 'root';
$password = '';
$conn = new PDO( 'mysql:host=localhost; dbname=Oaktown', $username, $password );
$sql ="SELECT RoundNumber, RoundDate, HomeTeam, HomeTeamScore, AwayTeam, AwayTeamScore FROM Fixture";
$statement = $conn->prepare( $sql );
$statement->execute();
$results = $statement->fetchAll( PDO::FETCH_ASSOC );
?>
<h2>Competitions</h2>
<article>
<p id="TableHeader1">Fixture Information</p>
<P>Select Round and Game number from the dropdown list under Round Number.</P>
<br>
<br><form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<p id="TableHeader2">Round Number
<select style="width:250px"></select>  <input class="button"
type="submit" name="Get" value="Get Fixture Results"></p>
<p id="TableHeader2">Results</p>
<table class="table">
<tr><td><b>Round Number:</b></td>
<?php foreach( $results as $row ){
echo "<td>";
echo $row['RoundNumber'];
}
?>
</tr>
<tr>
<td><b>Round Date:</b></td>.
<?php foreach( $results as $row ){
echo "<td>";
echo $row['RoundDate'];
}
?>
</tr>
<tr>
<td><b>Home Team:</b></td>
<?php foreach( $results as $row ){
echo "<td>";
echo $row['HomeTeam'];
}
?>
</tr>
<tr>
<td><b>Home Team Score:</b></td>
<?php foreach( $results as $row ){
echo "<td>";
echo $row['HomeTeamScore'];
}
?>
</tr>
<tr>
<td><b>Away Team:</b></td>
<?php foreach( $results as $row ){
echo "<td>";
echo $row['AwayTeam'];
}
?>
</tr>
<tr>
<td><b>Away Team Score:</b></td>
<?php foreach( $results as $row ){
echo "<td>";
echo $row['AwayTeamScore'];
}
?>
<td colspan="2><?php echo $message; ?>"></td>
</tr>
</table>
</form>

Using a similar block of code like the one you use for the tables you can do something like this:
<select>
<?php foreach( $results as $row ){
echo "<option value='" . $row['value column'] . "'>" . $row['text column'] . "</option>";
}
?>
</select>
if you don't have or need a pair of values then you can simply do this:
<select>
<?php foreach( $results as $row ){
echo "<option>" . $row['text column'] . "</option>";
}
?>
</select>

Related

Getting the value from checkbox

I am trying to update my table with a checkbox. The process is like this, In every row there is a checkbox and if I check one of it and click the submit button the checked row will update a column with a specific value.
This is what I did.
<tbody>
<?php
while ($fetch = mysqli_fetch_array($query,MYSQLI_BOTH)) {
?>
<tr>
<td><input type="checkbox" name="approveArr[]" value=" <?php $prsid = $fetch['prsid']; ?>"></td>
<?php echo "<td>". $prsno = $fetch['prsno'] ."</td>" ;?>
<?php echo "<td>". $qty = $fetch['qty'] ."</td>" ;?>
<?php echo "<td>". $productcode = $fetch['productcode'] ."</td>" ;?>
<?php echo "<td>". $productdescription = $fetch['productdescription'] ."</td>" ;?>
<?php echo "<td>". $vendors = $fetch['vendors'] ."</td>" ;?>
<?php echo "<td>". $prsdate = $fetch['prsdate'] ."</td>" ;?>
<?php echo "<td>". $status = $fetch['status'] ."</td>"; ?>
</tr>
<?php } ?>
<?php
if(isset($_POST['submits'])){
print_r($_POST);
$update = "UPDATE prs set status='Approved' where id='$prsid'";
$query = mysqli_query($conn,$update);
}
?>
</tbody>
I made an assumption with the following code in that I added the form and table elements to complete the picture - but in your original code you had left the database vulnerable to sql injection which I try to correct here.
<form method='post'>
<table>
<tbody>
<?php
while ( $fetch = mysqli_fetch_array( $query,MYSQLI_BOTH ) ) {
/* assign row values to variables... */
$prsid = $fetch['prsid'];
$prsno = $fetch['prsno'];
$qty = $fetch['qty'];
$productcode = $fetch['productcode'];
$productdescription = $fetch['productdescription'];
$vendors = $fetch['vendors'];
$prsdate = $fetch['prsdate'];
$status = $fetch['status'];
/* use placeholders to represetn each variable in the output html and assign relevant value for printing */
printf('
<tr>
<td><input type="checkbox" name="approveArr[]" value="%s>"></td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
</tr>',
/* the variables */
$prsid,
$prsno,
$qty,
$productcode,
$productdescription,
$vendors,
$prsdate,
$status
);
}
?>
</tbody>
</table>
<input name='submits' type='submit' />
</form>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submits'] ) ){
$approveArr=$_POST['approveArr'];
$sql='update prs set status='approved' where id=?';
$stmt=$conn->prepare($sql);
$stmt->bind_param( 'i', $status );
foreach( $approveArr as $status ) $stmt->execute();
}
?>

<td> not filling all the dynamic table HTML PHP MySQL

My table is not filling all the data i need. Is missing some columns be filled with form multiple. The column where the th is Renault need to be the same for all the rest are empty.
In next picture, you can see when i select options in dynamic selectbox multiple and submit, is only filling in the first column when the expectable is fill all the columns selected.
Next is the code where is giving the value of the select box multiple.
if ($consulta !=0) {
}//
else{
echo "";
}
#$s1= $_POST['s1'];
if( is_array($s1)){
while (list ($key, $val) = each ($s1)) {
}
}//
else{
echo "";
}
/////////////////
#$s2= $_POST['s2'];
if( is_array($s2)){
?>
Next is the code where data is filled in the html table. That line of code<td align=\"center\" bgcolor='FFFFFF'> need to be associate the result of: <?php echo "$key => $val1\n";?> to which form:
The result of <?php echo "$key => $val1\n";?>
0 => Renault 1 => Opel 2 => Mercedes 3 => Audi
The expected output is missing.
Renault
<form onsubmit=\"return validate();\" id=\"teste\" method=\"post\" action=\"teste.php\">
Opel
<form onsubmit=\"return validate();\" id=\"teste\" method=\"post\" action=\"teste.php\">
Mercedes
<form onsubmit=\"return validate();\" id=\"teste\" method=\"post\" action=\"teste.php\">
Audi
<form onsubmit=\"return validate();\" id=\"teste\" method=\"post\" action=\"teste.php\">
That is dynamic, will get the values from mysql database and i can select which i want.
There is all the table where is filled the data. Static and dynamic.
<table>
<tbody>
<tr>
<th>Parametro:</th>
<?php
while (list($key, $val1) = each ($s2)) {
?>
<th><?= htmlspecialchars($val1, ENT_HTML5 | ENT_COMPAT, 'UTF-8') ?></th>
<?php
echo "$key => $val1\n";
?>
<?php
}
?>
The values down of the Parametro:
{
echo("<tr>
<td align=\"center\" bgcolor='FFFFFF'>$utilizador</td>
<td align=\"center\" bgcolor='FFFFFF'>
<form onsubmit=\"return validate();\" id=\"teste\" method=\"post\" action=\"teste.php\">
");
Code from the form:
$con = mysqli_connect( "localhost","root","","teste" ); // ◄■ CONNECT TO DATABASE.
$dat_menuid = mysqli_query( $con,"SELECT * FROM menu WHERE menuId = '".$menuId."'" ) // ◄■ MENUIDs.
or die( mysqli_error($con) );
$con1 = mysqli_connect( "localhost","root","","teste" ); // ◄■ CONNECT TO DATABASE.
$idtem = mysqli_query($con1, "SELECT MAX(id_tem) as id_tem FROM tem")
or die( mysqli_error($con) );
// Print out result
while($row = $idtem->fetch_assoc())
$toEcho = $row["id_tem"];
//echo $toEcho;
$toEchosave = $toEcho + 1;
$_SESSION['myvar'] = $toEchosave;
$options = array( "0.00","0.05","0.10","0.15","0.20","0.25","0.30","0.35","0.40","0.45","0.50","0.55","0.60","0.65","0.70","0.75","0.80","0.85","0.90","0.95","1" ); // ◄■■ OPTIONS ARE STATIC (ALWAYS THE SAME).
while ( $row_menuid = mysqli_fetch_array( $dat_menuid ) ) // ◄■ DISPLAY <SELECT>s.
{ echo "<select class='sumselect' name='corp_resp&{$row_menuid['menuId']}&{$_SESSION['UtilizadorID']}&{$dateTime}&{$toEchosave}' multiple>"; // ◄■■ CORP_RESP&1,CORP_RESP&2.
foreach ($options as $opt)
echo "<option value='$opt'>$opt</option>\n";
echo "</select>\n";
} ?>
</form>
</td>
</tr>
<?php } ?>
<?php }
}
}
?>
<div id='sum'></div>
<br><br><br>
</tbody>
</table>
follow this code
<?php
$sql = "SELECT * FROM menu WHERE $id = menuIdPai ORDER BY menuId ";
$consulta = mysql_query($sql);
while ($mostrar = mysql_fetch_array($consulta)) {
$id = $mostrar['menuId'];
$utilizador = $mostrar['menuNome'];
?>
<tr>
<td align=\"center\" bgcolor='FFFFFF'>Test1</td>
<td align=\"center\" bgcolor='FFFFFF'>Test2</td>
<td align=\"center\" bgcolor='FFFFFF'>Test3</td>
<td align=\"center\" bgcolor='FFFFFF'>Test4</td>
</tr>
<?php
}
?>
this is main format if work then update your code . you add 2 td but your main th 4 so need 4 td
your this tag not close
<td align="center" bgcolor='FFFFFF'>
<form onsubmit="return validate();" id="teste" method="post" action="teste.php">
so close this in your script
<div id='sum'></div>
<br><br><br>
</form>
</td>
</tr>
move this code before end loop
foreach ($options as $opt)
echo "<option value='$opt'>$opt</option>\n";
echo "</select>\n";
} ?>
</form>
</td>
</tr>
<?php } ?>
<?php }
}
}
?>
<div id='sum'></div>
<br><br><br>
</tbody>
</table>

taking the right value out of the loop

Below you can see my code. No need to show the other parts or the database table.
Code
<form method="POST" action="custInfo.php">
<center><input type="submit" id="btn" name="room"></center>
$query = mysqli_query($conn, "SELECT room_name, room_type, room_rate, inclusive, description, room_status, max_cap
FROM room
WHERE room_status = 'available'");
if(mysqli_num_rows($query)){
while($row = mysqli_fetch_assoc($query)){
echo "<div class='chooseRoom'>";
echo "<div class='indent'>";
echo "<h4>".$row['room_type']."</h4>
<h5>".$row['room_rate']."php</h5>";
echo "<img src='../images/".$row['room_type'].".jpg' width=250 height=160>";
echo "<h5>Number of Adult ";
echo "<select name='adult'>";
$x = 0;
while($x <= $row['max_cap']){
echo "<option>";
echo $x;
echo "</option>";
$x++;
}
echo "</select>";
echo " Number of Children ";
echo "<select name='children'>";
echo "<option>0</option>";
echo "<option>1</option>";
echo "<option>2</option>";
echo "<option>3</option>";
echo "<option>4</option>";
echo "<option>5</option>";
echo "</select></h5>";
echo "<table class='table'>";
echo "<thead>";
echo "<th>Inclusive</th><th>Description</th>";
echo "</thead>";
echo "<tbody>";
echo "<td>".$row['inclusive']."</td><td>".$row['description']."</td>";
echo "</tbody>";
echo "<tfoot>";
echo "<td colspan='2'>";
echo $row['room_status'];
echo "</td>";
echo "</tfoot>";
echo "</table>";
echo "</div>";
echo "</div>";
}
}
else{
echo "No rooms available in the date you desire!";
}
</form>
I need to take the value from the correct input. This code always takes the last input from the loop. And I have been trying to research about this for a day now. How do I fix this?
Please follow the below code:
$result = mysqli_query($connection, $query);
?>
<form method="POST" action="custInfo.php">
<center><input type="submit" id="submit_button" name="room_submit" value="Submit"></center>
<?php
while ($row = mysqli_fetch_assoc($result)) {
?>
<div class='chooseRoom'>
<div class='indent'>
<h4><?php echo $row['room_type']; ?></h4>
<h5><?php echo $row['room_rate']; ?></h5>
<img src='../images/<?php echo $row['room_type']; ?>.jpg' width="250" height="160">
<h5>Number of Adult
<select name='adult[]'> <!-- NOTICE HERE... -->
<?php
$x = 0;
while($x <= $row['max_cap']){
?>
<option><?php echo $x; ?></option>
<?php
$x++;
}
?>
</select>
Number of Children
<select name='children[]'> <!-- NOTICE HERE... -->
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</h5>
<table class='table'>
<thead>
<th>Inclusive</th>
<th>Description</th>
</thead>
<tbody>
<td><?php echo $row['inclusive']; ?></td>
<td><?php echo $row['description']; ?></td>
</tbody>
<tfoot>
<td colspan='2'><?php echo $row['room_status']; ?></td>
</tfoot>
</table>
</div>
</div>
<?php
}
?>
</form>
In the above code you will see that we are looping through some DB Rows. So there will be multiple Adult and Children selects. So for that case we are making them arrays with [] at the end. Which will preserve all inputs with same name inside an array.
/**
* After form submittion look at $_POST variable... eg.
*
* echo "<pre>";
* print_r($_POST);
* echo "</pre>";
*/
/**
*
* The $_POST['adult'] and $_POST['children'] will be an array.
* And then you can have whichever value you want by calling the right Index.
*
* Otherwise you can loop through them:
* foreach ($_POST['adult'] as $key => $value) {
* echo $value;
* }
* And ---- for children.
* foreach ($_POST['children'] as $key => $value) {
* echo $value;
* }
*
*/
Because of the names of inputs is duplicate. Try to change name of the input to Array.
For example:
<select name='children[]'></select>

Show only MySQL columns that exist in queried table

I have several MySQL tables that are dynamically generated into a html table one table at a time through the code below. However, the tables don't have the same columns. i.e. One table has a description column, whereas the other does not.
Is the following code the best way to have all the possible MySQL columns among the various tables in the script but only show the MySQL columns that exist for the selected table? I feel like I'm redundant by writing "isset" for every column. Thanks!
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
while($row = mysqli_fetch_array($query_select)) {
?>
<table>
<tr>
<?php if(isset($row['name'])){ ?>
<td><?php echo $row['name'];?></td>
<?php } ?>
<?php if(isset($row['description'])){ ?>
<td><?php echo $row['description']?></td>
<?php } ?>
</tr>
</table>
You might want to make your code adapt to the fields in the result set:
<?php
$result = mysqli_query($con,$query);
$fields = mysqli_fetch_fields($result);
$myaliases = array(
'column_id' => 'id'
);
?>
<table>
<tr>
<?php foreach ($fields as $field): ?>
<th><?php echo $myaliases[$field->name] ?: $field->name; ?></th>
<?php endforeach; ?>
</tr>
<?php while($row = mysqli_fetch_array($result)): ?>
<tr>
<?php foreach ($fields as $field): ?>
<td><?php echo $row[$field->name]; ?></td>
<?php endforeach; ?>
</tr>
<?php endwhile; ?>
</table>
Re comments:
I've added code above to print a table row for column headings.
I've also included an example of mapping a field name column_id to a table heading id in the output. If I define no alias for a given column, it defaults to the original field name by using the PHP 5.3 operator ?:
You could alternatively define column aliases in your SQL query like SELECT column_id AS id ...
See http://www.php.net/manual/en/mysqli-result.fetch-fields.php
You can foreach the array instead.
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
?>
<table>
<?php while($row = mysqli_fetch_array($query_select, MYSQLI_ASSOC)) { ?>
<tr>
<?php foreach($row as $key => $value) { ?>
<td><?=$value?></td>
<?php } //Endforeach ?>
</tr>
<?php } //Endwhile ?>
</table>
If you need to print labels you can also use an associative array and an additional iteration to do that as well.
<?php
$query = " SELECT * FROM $tablename ";
$keys = array('name' => 'Name Label', 'description' => 'Description Label');
$query_select = mysqli_query($con,$query);
$i = 0;
?>
<table>
<?php while($row = mysqli_fetch_array($query_select, MYSQLI_ASSOC)) { ?>
<?php if($i == 0) { ?>
<tr>
<?php foreach($row as $key => $value) { ?>
<td><b><?=$keys[$key]?></b></td>
<?php } //Endforeach ?>
</tr>
<?php } $i++; //Endif ?>
<tr>
<?php foreach($row as $key => $value) { ?>
<td><?=$value?></td>
<?php } //Endforeach ?>
</tr>
<?php } //Endwhile ?>
</table>
You could just loop through the results. However, that would not perform any checks. Most likely, you'll have to do something like this, depending on what you're actually getting from the database.
<?php foreach ($row as $field): ?>
<?php if ($field): ?>
<td><?php echo $field; ?></td>
<?php endif; ?>
<?php endforeach; ?>
Edit: In keeping in line with the comment you added above, you could simply remove the if clause.
not sure if this is what you need,
but you can use indexes instead for the column instead of names:
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
while($row = mysqli_fetch_array($query_select)) {
echo $row[0] ." ".$row[1]." ".$row[2]
}
?>
mysql_fetch_array
possible formating:
<table>
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
while($row = mysqli_fetch_array($query_select)) { ?>
<tr>
<?php for(var $i=0; $i < count($row); $i++){
echo "<td>". $row[i] ."</td>";
} ?>
</tr>
<?php } ?>
</table>

Show all rows in mysql table then give option to delete specific ones

I want to have the ability to show all the entries in a database table and by each one give the user the ability to delete specific ones.
I am currently using a for each loop that loops through the database showcasing each entry.
$result = mysql_query("SELECT * FROM KeepScores");
$fields_num = mysql_num_fields($result);
echo "<table><tr>";
// printing table headers
echo "<td>Recent Posts</td>";
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
How would to add a delete button that appears by each one and removes the entry from the database table?
You can do it with forms:
//main.php
<?php $result = mysql_query("SELECT * FROM KeepScores"); ?>
<table>
<tr>
<td>Recent Posts</td>
</tr>
<?php while($row = mysql_fetch_array($result)) : ?>
<tr>
<td><?php echo $row['field1']; ?></td>
<td><?php echo $row['field2']; ?></td>
<!-- and so on -->
<td>
<form action="delete.php" method="post">
<input type="hidden" name="delete_id" value="<?php echo $row['id']; ?>" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
<?php endwhile; ?>
</table>
//delete.php:
<?php
if(isset($_POST['delete_id'] && !empty($_POST['delete_id']))) {
$delete_id = mysql_real_escape_string($_POST['delete_id']);
mysql_query("DELETE FROM KeepScores WHERE `id`=".$delete_id);
header('Location: main.php');
}
Or you can do it with jQuery and AJAX:
//main.php
<?php $result = mysql_query("SELECT * FROM KeepScores"); ?>
<table>
<tr>
<td>Recent Posts</td>
</tr>
<?php while($row = mysql_fetch_array($result)) : ?>
<tr id="<?php echo $row['id']; ?>">
<td><?php echo $row['field1']; ?></td>
<td><?php echo $row['field2']; ?></td>
<!-- and so on -->
<td>
<button class="del_btn" rel="<?php echo $row['id']; ?>">Delete</button>
</td>
</tr>
<?php endwhile; ?>
</table>
<script>
$(document).ready(function(){
$('.del_btn').click(function(){
var del_id = $(this).attr('rel');
$.post('delete.php', {delete_id:del_id}, function(data) {
if(data == 'true') {
$('#'+del_id).remove();
} else {
alert('Could not delete!');
}
});
});
});
</script>
//delete.php
<?php
if(isset($_POST['delete_id'] && !empty($_POST['delete_id']))) {
$delete_id = mysql_real_escape_string($_POST['delete_id']);
$result = mysql_query("DELETE FROM KeepScores WHERE `id`=".$delete_id);
if($result !== false) {
echo 'true';
}
}
It's all untested and sure needs some adjustment for your specific project, but I think you get the idea and I hope it helps.
Next time, please post your schema if you ask stuff about database.
I thought I would improve on this a little bit by wrapping the delete post in a class and function. I was having the same problem. and this worked great for me. Thanks again # Quasdunk
<?php
// Class to hold the remove post function
class someClass{
//Function for removing the post
function removePost(){
if(isset($_POST['delete_id']) && (!empty($_POST['delete_id']))) {
$delete_id = mysql_real_escape_string($_POST['delete_id']);
$result = mysql_query("DELETE FROM post WHERE post_id='".$delete_id."' AND post_member='" . $_SESSION['SESS_USER'] . "'");
if($result !== false) {
echo 'true';
}
}
}
}
if(isset($_SESSION['SESS_MEMBER_ID'])){
$member = $_SESSION['SESS_USER'];
$res = mysql_query("SELECT * FROM post WHERE post_member='$member' ORDER BY timestamp DESC") or die(mysql_error());
$i = new someClass;
while($row = mysql_fetch_array($res)){
echo '<div style="width:100%;margin:0 auto;border-top:thin solid #000;">';
echo '<div style="width:600px;margin:0 auto;padding:20px;">';
echo $row['post_text'] . '<br>';
$postID = $row['post_id'];
echo '<div style="border-top:thin solid #000;padding:10px;margin-top:5px;background-color:#CCC;">';
echo 'You posted this on: ' . $row['post_date'] . '#' . $row['post_time'];
echo '<div style="float:right;">
<form method="post" action="'. $i->removePost() .'">
<input type="hidden" name="delete_id" value="'.$row['post_id'].'" >
<input type="submit" value="Delete Post">
</form>
</div>';
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?>
Produce a key to each table, using jquery,then link it to a php file which an accept the key and delete from the specific table (which also can be passed through jquery)

Categories