How to make so a checkbox is added beside each row in a dynamic table? So if i get 5 result from databse i want to display 5 checkbox next to these results.
<table border="2">
<tr>
<th>title</th>
</tr>
<?php
include 'database.php';
$valid_query = "SELECT * FROM agencies ";
$valid_result = mysqli_query($link, $valid_query);
while ($row = mysqli_fetch_array($valid_result)) {
echo '<tr>';
echo '<td>'.$row['title'].'</td>';
<input type = 'checkbox' name = '$row[title]'>
echo '<tr>';
}
?>
</table>
Related
I am a student with a couple of weeks into PHP. What I am trying to do is Generate A table containing all users messages. Then I need a check box in each row. When the user hits the delete button rows with checkboxes marked will be deleted from table. The issue is that I can not figure out how to assign an individual value to each row of the HTML table to target with PHP. So I will only delete the rows that have been selected. I've only been able to delete all rows.
Here is what I got so far
<?php
//connect to database
include("../partials/.connect.php");
// select rows from contacts
$query = "SELECT * FROM contacts";
// display table headers
echo '<form>
<table width="100%" border="0" cellspacing="4" cellpadding="6">
<tr>
<th class="center">ID</th>
<th class="center">Name</th>
<th class="center">Phone</th>
<th class="center">Email</tdclass=center>
<th class="center">Message</th>
<th class="center"> <button type="submit" name="button1">Delete Selected</button</th>
</tr>';
// create loop to fetch all rows from DataBase
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["id"];
$field2name = $row["name"];
$field3name = $row["phone"];
$field4name = $row["email"];
$field5name = $row["message"];
// If delete button is clicked delete user
if(isset($_POST['button1'])) {
$sql = "DELETE FROM contacts WHERE id=$field1name";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
// display table data
echo '<tr>
<td class="center">'.$field1name.'</td>
<td class="center">'.$field2name.'</td>
<td class="center">'.$field3name.'</td>
<td class="center">'.$field4name.'</td>
<td class="center">'.$field5name.'</td>
<td class="center"> <input type="checkbox" id="if_checked" name="if_checked"></td>
</tr>
</form>';
}
$result->free();
}
?>
</body>
</html>
Your code is wrong, you just delete all your data along with your foreach run, so I just want to say keep learn more about programming logic since you're student
ok, for your question you have to put delete query before
$query = "SELECT * FROM contacts";
and your delete query should be based from foreach of checkbox value, and the most important thing is your checkbox name should be an array name since you will post multiple checkbox with the same name
<input type="checkbox" class="if_checked" name="if_checked[]">
and then you can use code like this
..................
include("../partials/.connect.php");
if(isset($_POST['button1'])) {
foreach($_POST['if_checked'] as $id) {
......your delete query
}
}
// select rows from contacts
$query = "SELECT * FROM contacts";
...................
You can use the checkbox as an array where you will store the ids when you select checkboxes for delete, you will loop through checkboxes and will be able to delete all selected rows.
I Was Able to solve this by storing the $row['id'] variable in the checkbox value instead of $Field1name. allowing me to specify which row to delete.
<?php
//connect to database
include("../partials/.connect.php");
// select rows from contacts
$query = "SELECT * FROM contacts";
//if delete button is set
if(isset($_POST['delete'])) {
$selected = $_POST['if_checked'];
//confirm record target
$confirm = mysqli_query($conn, "SELECT * FROM contacts WHERE id = '$selected'") or die("Not Found");
if(mysqli_num_rows($confirm)>0){
//record found delete
$delete_query = mysqli_query($conn, "DELETE from contacts where id = '$selected'")
or die("Not Deleted");
echo "<div><p>Record Deleted</p></div>";
} else {
//record not DataBase
die("Not deleted".mysqli_error());
}
}
// display table headers
echo '<form method="post" action="" role="form">
<table width="100%" border="0" cellspacing="4" cellpadding="6">
<tr>
<th class="center">ID</th>
<th class="center">Name</th>
<th class="center">Phone</th>
<th class="center">Email</th>
<th class="center">Message</th>
<th class="center"><input class="center" type="submit" name="delete" value="Delete"></th>
</tr>';
// create loop to fetch all rows from DataBase
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["id"];
$field2name = $row["name"];
$field3name = $row["phone"];
$field4name = $row["email"];
$field5name = $row["message"];
// If delete button is clicked delete user
// display table data
echo '<tr>
<td class="center">'.$field1name.'</td>
<td class="center">'.$field2name.'</td>
<td class="center">'.$field3name.'</td>
<td class="center">'.$field4name.'</td>
<td class="center">'.$field5name.'</td>
<td class="center">
<input type="checkbox" id="if_checked" name="if_checked" value="'.$row['id'].'"></td>
</tr>
</form>';
}
$result->free();
}
?>
</body>
</html>
As you can see I have developed a html/php page to create orders and I am having issues trying to load data from a table (MySQL) into that table I created in html. What I want is the user to digit an ID (identification) a secondary key like order number and then the whole row goes to my table. where he can edit, delete and save the row. So far i have the table and I was able to load the whole tabe in the html page.
HTML:
<p>What order number would you like to load?<input type="text" id="SKU" maxlength="10" size="10" placeholder="Search for SKU..." title="Type an SKU..."><button onclick="myCreateFunction()">LOAD</button></p>
<table id="itemsTable"> <tr> ID <th>Quantity</th>
<th>Item</th>
<th>SKU</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Subtotal</th>
<th>Cartons Scanned</th>
<th>Individually Scanned</th>
<th>Current Inventory</th>
<th>Location Selected</th>
<th>Image</th>
<th>Edit</th>
</tr>
<tr>
</tr>
</table>
now the php:
<?php
//Step2
$query = "SELECT * FROM item_new WHERE SKU=input ";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
$all_property = array(); //declare an array for saving property
//showing property
echo '<table id="itemsTable" class="data-table">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing data selected by the user (input)
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
database table
script
<script>
function myCreateFunction() {
var input
input = document.getElementById("SKU");
}
You can use following code block for you solution
there will be two ways to fetch data as you want one can be using AJAX which is bit of complex and another is using form.
<p>What order number would you like to load?</p>
<form type="post" action=''>
<input type="text" name='input_field' id="SKU" maxlength="10" size="10" placeholder="Search for SKU..." title="Type an SKU...">
<input type='submit' name='search'>
</form>
<table id="itemsTable">
<tr>
<th>ID</th>
<th>Quantity</th>
<th>Item</th>
<th>SKU</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Subtotal</th>
<th>Cartons Scanned</th>
<th>Individually Scanned</th>
<th>Current Inventory</th>
<th>Location Selected</th>
<th>Image</th>
<th>Edit</th>
</tr>
<?php
//Check if form is submitted
if(isset($_POST['search'])){
$query = "SELECT * FROM item_new WHERE SKU='".$_POST['input_field']."'";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
$all_property = array();
//showing property
while ($property = mysqli_fetch_field($result)) {
array_push($all_property, $property->name); //save those to array
}
//showing data selected by the user (input)
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo "<a href='myeditpage?id=".$_row['id']."' >Edit product</a>"
echo '</tr>';
}
}
?>
</table>
in upper example we first let the user to input the data using input and when user click on search it will submit the form to current URL.
after that we check if user submitted the form or not if submitted the we will fetch data and print on the table.
I have a database with 2 tables:
1st table "data" with columns(name , phone , personid)
2nd table "links" with columns (linkid , link , personid)
Personid is the foreign key that connects the two tables with a "one to many" relationship and it's "CASCADE" when DELETE or UPDATE ,
So one person could have more than 1 link.
The HTMl table looks like that:
name phone links
jim 432443 link1
link2
link3
.....
_______________________
john 54545 link1
_______________________
... ..... .....
The code that show database contains on an html table:
$state = $connect->prepare("SELECT data.personid, name, phone, link FROM data JOIN links ON data.personid = links.personid");
$state->execute();
$results = $state->fetchAll(PDO::FETCH_ASSOC);
$data = [];
foreach($results as $result) {
$data[$result['personid']] = [
'name' => $result['name'],
'phone' => $result['phone'],
'links' => [],
];
$data[$result['personid']]['links'][] = $result['link'];
}
<table>
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
<th>Links</th>
</tr>
</thead>
<tbody>
<?php
foreach ($data as $row) {
echo "<tr>";
echo "<th>".$row['name']."</th>";
echo "<td>".$row['phone']."</td>";
echo "<td>".implode('<br/>', $row['links'])."</td>";
echo "<td>";
echo "</td>";
echo "</tr>";
}
?>
</table>
I want to add a delete functionality to delete some of these data , Like a checkBox next to each query and a button called "Delete Selected" for example, I know how to add the checkBox and the button but I don't know the code to achieve this funcunality .
Hope it works for add please check the code shown here.
On html include this:
<form action="action.php" method="POST">
<button type="submit">delete</button>
<table>
<thead>
<tr>
<th><input type="checkbox" name="check_select" readonly="readonly" onclick="toggleselect(this,'delete_data');"></th>
<th>Name</th>
<th>Phone</th>
<th>Links</th>
</tr>
</thead>
<tbody>
<?php
foreach ($data as $row) {
echo "<tr>";
echo '<input type="checkbox" class="check_box" name="checkbox_delete_data[]" value="'.$row['primary_id_of_your_table'].'">';
echo "<td>".$row['name']."</td>";
echo "<td>".$row['phone']."</td>";
echo "<td>".implode('<br/>', $row['links'])."</td>";
echo "<td>";
echo "</td>";
echo "</tr>";
}
?>
</table>
</form>
In Javascript:
function toggleselect(source,chkbox_name)
{
checkboxes = document.getElementsByName('checkbox_'+chkbox_name+'[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
Now you can access the selected check box in your action.php file and use it to delete with query.
For example:
<?php
if (isset($_POST["submit"])) {
$selected_check_boxes = implode(',', $_POST["checkbox_delete_data"]);
$query= $connect->prepare("Delete from table where table.primary id IN ($selected_check_boxes)");
$query->execute();
}
?>
I would recomnend to make whole table in < form > and add some "data-" attribute with personId to each checkbox. Then handle (when form submitted) these attributes with javascript and merge the SQL query like
delete from data where personid (1,2,3, ...)
If you need more help i can write some code, but develop it by own is always better :)
Cheers
i have two tables one item table and customer table:
in the table you can see the second item item id 1002 have two entries.and i want to add colspan to that item for column 1 and 3.
<table>
<tr>
<th>Item ID</th>
<th>Item Color</th>
<th>Customer</th>
</tr>
<?php
$sql = mysqi_query($con,"select * from item_table");
while($row = mysqli_fetch_array($sql)){
?>
<tr>
<td><?=$row['item_id'];?></td>
<td><?=$row['item_color'];?></td>
<td>
<select>
<?php
$sql_cust = mysqli_query($con,"select * from customer_tbl");
while($row_cust = mysqli_fetch_array()){
if($row['customer_id'] == $row_cust['customer_id']){
echo "<option selected='selected' >".$row['customer_name']."</option>";
}else{
echo "<option>".$row['customer_name']."</option>";
}
<?php
}
?>
</select>
</td>
</tr>
<?php
}
?>
</table>
But it print in normal way, i have no idea how to add rowspan in loop..please suggest some logic to solve its appreciated.
You can try it this way:
First, add a counter to your query that will indicate how many entries has a given item.
$sql_cust = mysqli_query($con,
"SELECT *, (SELECT COUNT(*) FROM item_table as it
WHERE it.item_id = item_table.item_id) as c
FROM item_table");
Then, when looping through the items you will set the rowspan to the number of entries the item has. Below is the whole code adjusted.
<?php
$sql = mysqi_query($con,
"SELECT *, (SELECT COUNT(*) FROM item_table as it
WHERE it.item_id = item_table.item_id) as entry_count
FROM item_table");
$buffer = [];
while($row = mysqli_fetch_array($sql)){
if(!isset($buffer[$row[$item_id]])) {
$buffer[$row[$item_id]] = 1;
}
?>
<tr>
<?php if(!isset($buffer[$row[$item_id]])) {?>
<td rowspan="<?=$row['entry_count']?>"><?=$row['item_id'];?></td>
<?php }?>
<td><?=$row['item_color'];?></td>
<?php if(!isset($buffer[$row[$item_id]])) {?>
<td rowspan="<?=$row['entry_count']?>">
<select>
<?php
$sql_cust = mysqli_query($con,"select * from customer_tbl");
while($row_cust = mysqli_fetch_array()){
if($row['customer_id'] == $row_cust['customer_id']){
echo "<option selected='selected' >".$row['customer_name']."</option>";
}else{
echo "<option>".$row['customer_name']."</option>";
}
<?php
}
?>
</select>
</td>
<?php }?>
</tr>
<?php
}
?>
Note that I added a buffer where I set which item was already displayed. That array is used so you only open one td with the wanted rowspan, instead of doing it on every iteration.
i have a simple idea
give TD a ID like
<td id="dynamically-Generate"> (you need to verify that TD id need to be equal in .rowSpan ="here" inside script )
and set this TD if dynamically-Generate is greater than 1 then don't show
and again if dynamically-Generate is greater than 1 then then use this script
<script>
document.getElementById("dynamically-Generate").rowSpan = "dynamically-Generate";
</script>
use script inside loop and both dynamically-Generate need to be same inside everyloop and change after each loop
I have this table im trying to display users, being 2 users per 2 columns, then list down. Here is what i have so far:
<?php $result = mysql_query("SELECT * from users WHERE adminlevel='5'");
while($row = mysql_fetch_array($result)) { echo
" <table>
<tr>
<td width='85' align='left'><br><center>". $row['username'] . "</center>
</td>
<td align='right'><center></center>
</td>
</tr>
<td width='85' align='left'><center></center>
</td>
<td align='right'><center></center>
</td>
</table>";
} ?>
This just displays the members as rows going down, and missing out the other column completely. I was hoping that it would display the username in each of the table fields. I also did try putting ". $row['username'] ." in the other fields too, but that just duplicated it.
EDIT:
So iv'e changed it to this, I can't see going down as I only have 2 members, Would this work:
<?php $result = mysql_query("SELECT * from users WHERE adminlevel='5'"); ?>
<table>
<tr>
<?php while($row = mysql_fetch_array($result)) { echo
"<td width='85' align='left'><font size='1px'><center>". $row['username'] . "</font></center></td>
<td align='right'><center></center></td>";
} ?>
</tr>
</table>
example:
try something like this
<table>
<tr>
<th>name</th>
<th>name</th>
</tr>
<?php
$result = mysql_query("SELECT * from users WHERE adminlevel='5'");
$i = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($i == '0') echo "<tr>";
echo "<td>{$row['username']}</td>";
if ($i == '1') echo "</tr>";
$i++;
if($i =='2')$i='0';
}
?>
</table>
I think you're asking why the other fields in your "user" mysql table aren't showing up.
They aren't there because you only asked for the username:
$row['username']
If you have first/last name in your mysql table, you can retrieve it in the same way:
$row['firstname']
$row['lastname']
In your code you got the row as a key/value array like this:
$row = mysql_fetch_array($result)
The "key" is the name of the mysql column, like username, lastname, firstname. And the value is what is stored in the mysql table under that row/column, like joecool, smith, joe.