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
Related
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>
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.
I have the following code:
$sql = "SELECT * FROM Tickets WHERE stat='Open'";
$result = mysql_query($sql);
mysql_close($con);
?>
<!DOCTYPE>
<html>
<body>
<table class="striped">
<tr class="header">
<td>Username</td>
<td>Title</td>
<td>Description</td>
<td>Admin Name</td>
<td>Category</td>
<td>Status</td>
<td>Urgency</td>
<td>Time In</td>
<td> </td>
</tr>
<?php
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row[username]."</td>";
echo "<td>".$row[title]."</td>";
echo "<td>".$row[description]."</td>";?>
<td><select>
<?php
echo "<option value'".$row[admin_name]."'>".$row[admin_name]."</option>";
$sql = mysql_query("SELECT username FROM Users WHERE user_type='admin'");
while ($u = mysql_fetch_array($sql)){
echo "<option value='".$u['username']."'>".$u['username']."</option>";
}
?>
</select></td>
<?php
echo "<td>".$row[category]."</td>";
echo "<td>".$row[stat]."</td>";
echo "<td>".$row[urgency]."</td>";
echo "<td>".$row[time_in]."</td>";
echo "<td><a href='close.php'>Close Ticket</a></td>";
echo "</tr>";
}
?>
</table>
<a href='update.php'>Update</a>
</body>
</html>
I have two links on this page. Both of them need to update a SQL database. The Close ticket link needs to just update the single row, while the update link should update all of them. I am not sure how to get the info from one php to the next. It seems like you can put the individual row information into a Post array for the close ticket link, but I am not sure how. For the update link it needs to take the value of the dropdown in the table and change the admin_name field to that value.
I have a mySQL table which can be simplified down to something like this:
animal breed
Cat Persian
Cat Siamese
Dog Alsatian
Dog Poodle
I want to display the information in this form:
<table>
<tr>
<td class="heading">Cat</td>
</tr>
<tr>
<td class="body">Persian</td>
<td class="body">Siamese</td>
</tr>
<tr>
<td class="heading">Dog</td>
</tr>
<tr>
<td class="body">Alsatian</td>
<td class="body">Poodle</td>
</tr>
</table>
So far, I have a query like this:
$query = "SELECT * FROM aa_animal";
$result = mysql_query($query, $MySQL_extranet) or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
$resultarray[] = $row;
}
Then I think I am going to need a pair of nested foreach() loops, but it is the handling of the multi-dimensional array that gets me hopelessly lost.
foreach("unique_animal") {
<tr>
<td class-"heading">$animal</td>
</tr>
if ($animal=="unique_animal") {
foreach("row") {
<tr>
<td class-"body">$breed</td>
</tr>
}
}
How do I manipulate $resultarray to get the right values for $animal, $breed, etc?
PROGRESS SO FAR
Justin's reply provided the solution to the problem as described above. However the real-life page has a lot more columns in the database table. Here is the code for a halfway file between the simple example I gave originally and the page I am trying to create.
<?php
$countryid='spain';
// MySQL query to select hotels and display all the hotel info
$query = "SELECT hid, hotel, pricefrom, place, region, country, picture, property, prop2, rooms, summary, lat, lng, zoomloc, breakfast, searchparam, specialoffer, biz_model, ta_rating, bc_rating FROM ex_hotel WHERE country LIKE '%$countryid%' AND showhide = 'show' ORDER BY orderr DESC";
$result = mysql_query($query, $MySQL_extranet) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
if (isset($resultarray[$row['region']])) {
$resultarray[$row['region']][] = $row['hotel'];
}else{
$resultarray[$row['region']] = array($row['hotel']);
}
}
ksort($resultarray);
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<table width="500" border="1" cellspacing=" 4" cellpadding="4">
<?php foreach($resultarray as $region => $hotel)
{
echo '<tr><td colspan="2" style="background-color:#ddd">'.$region.'</td></tr>';
foreach($hotel as $value) {
echo '<tr><td width="250px">'.$value.'</td>';
}
foreach($hid as $value2) {
echo '<td>'.$value2.'</td></tr>';
}
}?>
</table>
</body>
</html>
All those values in the mySQL query need to be used in the table, but how do I get them?
You should group data when fetching
while($row = mysql_fetch_assoc($result))
{
if (isset($resultarray[$row['animal']]))
$resultarray[$row['animal']][] = $row['breed'];
else
$resultarray[$row['animal']] = array($row['breed']);
}
And then, display it
foreach($resultarray as $animal => $breed)
{
echo '<tr><td class="heading">'.$animal.'</td></tr>';
foreach($breed as $value)
echo '<tr><td class="body">'.$value.'</td></tr>';
}
EDIT:
If you need more columns, what you have to do is storing full row instead of one item:
while($row = mysql_fetch_assoc($result))
{
if (isset($resultarray[$row['region']]))
$resultarray[$row['region']][] = $row;
else
$resultarray[$row['region']] = array($row);
}
And then, you can also fetch those rows
foreach($resultarray as $region => $rows)
{
echo '<tr><td class="heading">'.$region.'</td></tr>';
// this way (display everything)
foreach($rows as $row)
foreach($row as $key => $value)
echo '<tr><td class="body">'.$key.': '.$value.'</td></tr>';
// or this way (if you want to display only specific item)
foreach($rows as $row)
echo '<tr><td class="body">Hotel: '.$row["hotel"].' / price: '.$row["pricefrom"].'</td></tr>';
}
I want to display the results of my select query on my webpage in a table, however the code im using at the moment uses a pre-defined set of columns. My code is this:
$result= mysqli_query($con,"SELECT * FROM Customers where First_name = '$specFirstName'");
echo "<table border=\"1px solid black\" width=\"80%\"><tr><th>Customer ID</th><th >First Name</th><th>Last Name</th></tr>" ;
while($row = mysqli_fetch_array($result)){
echo "<tr><td style=\"text-align:center;\">". $row[('CustomerID')] . "</td><td style=\"text-align:center;\">".$row[('First_name')]."</td><td style=\"text-align:center;\">".$row[('Last_name')];
echo "</td></tr>";
}
echo "</table>"
Now, How can I do the same, but use the database headers in an automatically generated table? Can I also use this method to allow the user to specify the required columns in the query?
Many thanks,
Tommy
You can fetch the fields before the while loop like
$fields = ($result->fetch_fields());
?> <table border="1px solid black" width="80%"><tr> <?php
foreach($fields as $field) {
?> <th><?php echo $field->name; ?></th> <?php
}
?> </tr> <?php
while($row = mysqli_fetch_array($result)){
?><tr><?php
foreach($row as $val) {
?> <td style="text-align: center;"> <?php echo $val; ?> </td> <?php
}
?> </tr> <?php
}
?> </table> <?php
Something like this should work. You only have to define the $columns you want to display in the array map. This also works once you write the code to allow the user to select the columns she/he wants, you will only have to set this map with the selected options.
// Define the columns title and name in this array map.
$columns = array(
'Customer ID' => 'CustomerID',
'First Name' => 'First_name',
'Last Name' => 'Last_name'
);
// Run the query
$result= mysqli_query($con,"SELECT * FROM Customers WHERE First_name = '$specFirstName'");
// Output table header
echo "<table border=\"1px solid black\" width=\"80%\"><tr>";
foreach ($column as $name => $col_name) {
echo "<th>$name</th>";
}
echo "</tr>";
// Output rows
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($column as $name => $col_name) {
echo "<td style=\"text-align:center;\">". $row[$col_name] . "</td>";
}
echo "</tr>";
}
// Close table
echo "</table>"