I recently started learning PHP on my own and started to use MySQL and Apache as well. I made a basic table in MySQL, and using some PHP code, I displayed the table in a HTML table in a browser. Now I'd like to add a delete button beside each row, and when clicked, it would delete that row. I am very new to this, and I'm just practicing. Could anyone please help me? This is the code I have so far:
From: phpcode on Pastebin
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
mysql_connect('localhost', 'root', '');
mysql_select_db('testdb');
$result = mysql_query('select * from products');
$numrows = mysql_numrows($result);
//****************************************************************
print "<table border = 3 style = width:400px>";
for($i = 0; $i < $numrows; $i++)
{
$row = mysql_fetch_row($result);
print "<tr>";
foreach($row as $cell)
{
print "<td>";
print $cell;
print "</td>";
}
print "</tr>";
}
print "</table>";
mysql_close();
?>
I also have a delete.php page, but I really don't know where to start. I've looked for online tutorials, and many say different ways.
Just add another "" inside the loop with delete text and pass the id for that
for($i = 0; $i < $numrows; $i++)
{
$row = mysql_fetch_row($result);
print "<tr>";
foreach($row as $cell)
{
print "<td>";
print $cell;
print "</td>";
print "<td>";
print "DELETE";
print "</td>";
}
print "</tr>";
}
Let say your table like below;
$result = mysql_query('select * from products');
print "<table>";
while ($row = mysql_fetch_assoc($result)) {
print "<tr><td>" . $row["name"] . "</td><td>" . $row["surname"] . "</td><td>Delete</td></tr>";
}
print "</table>";
Here, while iterating your row, you need to put $row["id"] in delete link id.
And in your delete.php
$id = $_GET["id"];
// Delete sql here. Do not forget to validate id here.
header("Location: index.php"); // I assume, table page is this
In your table products you need a field with different value for each register, name it id or whatever you want.
If you have table but doesn't have that field, good option would be and auto_increment field.
Code for add an auto_increment field:
ALTER TABLE `products` ADD COLUMN `id` INT AUTO_INCREMENT UNIQUE FIRST;
Then id would be unique for each register and you don't need to worried about it because you don't need to insert it, it is generated automatically.
print "<table border = 3 style = width:400px>";
for($i = 0; $i < $numrows; $i++)
{
$row = mysql_fetch_row($result);
print "<tr>";
foreach($row as $cell)
{
print "<td>";
print $cell;
print "</td>";
}
print "<td><a href='delete.php?id=".$row["id"] ."' > delete </a> " ;
print "</tr>";
}
$row["id"] is the id of register you want to delete.
in delete.php
$id = $_GET["id"];
$delete = " DELETE from yourTable where id = ". $id ;
mysq_query ( $delete ) ;
PD: Use mysqli_
Related
I want to display 9 different tables from my sql database in 9 different html created tables on the website.
In detail: I have 9 tables ("dt_bookmarks_01", "dt_bookmarks_02" etc.) with 4 columns "id" (which is primary and auto increment), icon (for favicon), link (url) and text (for the display text).
I've created 9 different html tables with bootstrap and want to output the content of each table in a different bootstrap table of my site.
My problem is that i have no idea how to get different "foreaches" or counter for each different table.
To automaticaly add new rows to the bootstrap table I use the count and foreach function. problem here is: I dont know how to seperate them from each other. If i have 4 entries in sql table 1 it multiplies the one and only entrie of sql table 2 to match the current count of 4.
I am very new to sql and php so I guess I just miss some fundamental functions or something.
document header:
php
$sql = "
SELECT *
FROM dt_bookmarks_01, dt_bookmarks_02";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
$conn->close();
and for the html table I use:
php
<tbody>
<!--begin: SQL Selection -->
<?PHP
$count = 0;
foreach($rows as $item){
if (!empty($item['icon'])) {
$icon = '<img src="assets/media/bm-icons/'. $item['icon'] . '">';
}else{
$icon = '<img src="assets/media/bm-icons/default.png">';
}
$count++;
echo "<tr>";
/*echo "<td>" . $count . "</td>";*/
echo "<td> " . $icon . "</td>";
echo "<td> <a href=\"" . $item['link'] . "\"'>" . $item['text'] . "</a> </td>";
echo "<td></i> ";
echo "</i></td>";
echo "</tr>";
}
?>
<!--end: SQL Selection -->
</tbody>
I do not have a database on hand to give you an answer with complete code, but here is the idea:
<?php
for ($i = 1; $i <= 9; $i++)
{
$query = "SELECT index1,index2 FROM dt_bookmarks_0$i";
echo "<h1>This is the content of table $i</h1>";
# RUN THE QUERY HERE !!!
echo "<table>";
# EXTRACT THE RESULTS
foreach $rows as $item
{
echo "<tr><td>$item[index1]</td><td>$item[index2]</td></tr>"
}
echo "</table>";
echo "<br><br>";
}
?>
Loop on your tables.
In each table loop, you output the HTML code to display it's content.
Avoid SELECT *, specify your indexes (research "sql why avoid SELECT *")
So you loop twice. One time to go through the tables, the other to loop on the results.
so here is the new working code.
header:
<?PHP
require_once('/htdocs/_nt/mysql/data.php');
$sql = "
SELECT *
FROM dt_bookmarks";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
$conn->close();
?>
and for the table output:
<?PHP
$count = 0;
foreach($rows as $item){
if ($item['category'] == talk) {
$count++;
echo "<tr>";
echo "<td> " . $icontalk . "</td>";
echo "<td> <a href=\"" . $item['url'] . "\"'>" . $item['text'] . "</a> </td>";
echo "</tr>";
}else{
echo "";
}
}
?>
Ok, so I think I should be storing my mysql query as an array since I want to call upon the data multiple times. So instead of querying the database over and over, I can just do it once and then use the array over and over.
However, I am a bit lost in how to regenerate the table I was able to with mysql+php with the new array...
Here is my array call:
$userid = 3;
$results = mysqli_query($con,"SELECT user,product,etd FROM wp_summary WHERE user=$userid");
$history = array();
while( $row = mysqli_fetch_array($results) ){
$history[]= [
$row['product'],
$row['etd']
];
}
echo print_r($history); //debugging so I can see I actually called it right
But what I would like to do is now dynamically generate a table with a while loop on the rows. with a MySQL query, it was like this:
while($row = mysqli_fetch_array($result))
{
echo "<tr style='font-size: 0.8em'>";
echo "<td>" . $row['product'] . "</td>";
echo "<td>" . $row['etd'] . "</td>";
echo "</tr>";
}
But I can I convert this for the array now instead of the mysql query?
Solved my own riddle after the hint from #DimitrisFilippou ;
for ($i = 0; $i < count($history); $i++) {
echo '<br>';
echo $history[$i]['product'];
echo $history[$i]['etd'];
}
I tried to print the Mysql fetched rows into html table using php. However, when using the following code, the first fetched row is repeatedly printing. It looks like the $row hold the first fetched value. I found a similar problem here. But I would like to know about working with the for loop. Thanks
for ($j=0;$j<=$len2;$j++)
{
$sql = "SELECT * FROM database_search WHERE gene_id LIKE'%$key%'";
$qry = $dbo->prepare($sql);
$qry->execute();
$row = $qry->fetch(PDO::FETCH_ASSOC);
$val = array_values($row);
echo "<tr>";
for ($k=0;$k<=4;$k++)
{
$x=$val[$k];
echo "<td style=font-size:7.9px>$x</td>";
}
echo "</tr>";
}
<table>
<?php
while($row = $qry->fetch(PDO::FETCH_ASSOC)){
echo '<tr>';
foreach($row as $cell){ echo '<td>'.$cell.'</td>'; }
echo '</tr>';
}
?>
</table>
After fetching the query as $row variable, you need to use the following code instead
foreach($row as $tr) {
echo "<tr>";
echo "<td style=font-size:7.9px>".$tr['col1']."</td>";
echo "<td style=font-size:7.9px>".$tr['col2']."</td>";
echo "</tr>";
}
This is possible that $row only have one record fetching from database and than your for ($k=0;$k<=4;$k++) loop print that only one record 5 time
because you are using print under this loop, this loop will run 5 time.
Try the following code.
foreach($row as $val) {
echo "<tr>";
echo "<td style=font-size:7.9px>".$val['column Name']."</td>";
echo "</tr>";
}
When I add my first record into the database table, it doesn't show on the page where the records are displayed. But when I add the second record and on, they are displayed on the page except the first record that I entered.
Here is my code:
$result = mysql_query("SELECT * FROM members ORDER BY player_role DESC", $db);
while ($row = mysql_fetch_array($result))
{
echo "<table>";
echo"<tr><th><B>Player Name</B><Th><B>Role</B></TR>";
while ($myrow = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>". $myrow['player_name']. "</td>";
echo "</td>";
echo "<td>" .$myrow['player_role']. "</td>";
echo "</tr>";
}
echo "</table>";
}
Can someone please tell me what is wrong?
It may be caused by nested while() loop. No need to use nested while(). Use one while() instead. Example:
$result = mysql_query("SELECT * FROM members ORDER BY player_role DESC", $db);
echo "<table>";
echo"<tr><th><B>Player Name</B></th><th><B>Role</B></th></tr>";
while ($row = mysql_fetch_array($result))
{
echo '<tr><td>'.$row['player_name'].'</td><td>'.$row['player_role'].'</td></tr>';
}
echo "</table>";
Player Name and Role should not be inside while() loop.
MOST IMPORTANT Do not use mysql, it is deprecated. Instead use mysqli
Your code (changed)
$result = mysqli_query($db,"SELECT * FROM members ORDER BY player_role DESC");
echo "<table>";
echo"<tr><th><B>Player Name</B></th><th><B>Role</B></th></tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<tr><td>'.$row['player_name'].'</td><td>'.$row['player_role'].'</td></tr>';
}
echo "</table>";
I have a database of images which I want to output as a gallery ...
I want to display each image in its own cell <td>image1</td> and limit the number of cells to 7 per row.
<tr>
<td>image1</td><td>image2</td><td>image3</td><td>image4</td><td>image5</td><td>image6</td><td>image7</td>
</tr>
Then a new row would be created and continue to output all the images.
<tr>
<td>image8</td>
and so on ..
I know how to do a query, but I am lost as to how to assemble the rows into the format I am looking for.
Can anyone please help me it would be greatly appreciated. Thanks.
First run your query, then get the mysql_fetch_assoc in a variable. Then echo your beginning tags for the table and tr. Then create a foreach loop of the query assoc, as another variable such as row, and echo $row['image'] in a td. This will add a new td with the image for every entry in the database. Then echo your closing tags for the tr and table.
$query = mysql_query("SELECT image FROM table_name");
$query_a = mysql_fetch_assoc($query);
echo "<table><tr>"
foreach ($query_a as $row)) {
echo "
<td>" . $row['image'] . "</td>
";
}
echo "</tr></table>";
Not tested, but try something like this
<table>
<?php
// make sure there is at least 1 row first
$cnt = 0;
$while($row = mysql_fetch_assoc($query))
{
if(++$cnt == 1) {
echo '<tr>';
} elseif($cnt % 7 == 0) {
echo '</tr><tr>';
}
// show images in <td>'s
echo "<td>" . $row['image']. "</td>";
}
echo '</tr>';
?>
</table>
Keep it simple:
Query the database to get the desired information, loop through the results, construct a new row come each new loop.
$sql = "Select * from table";
mysql_query($sql) or die(mysql_error());
if(mysql_num_rows !=0)
{
// Found at least one record, create table
echo "<table>";
echo "<tr>";
while($row = mysql_fetch_assoc($sql)
{
$cell_count = 0;
// Create a new row for each record found
echo "<td>" . $row['image_column']. "</td>";
$cell_count++;
if($cell_count == 7)
{
echo "</tr>";
echo "<tr>";
$cell_count = 0;
}
}
// Close the table
echo "</tr>";
echo "</table>";
}