Multiple Tables of same Database on the same site - php

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 "";
}
}
?>

Related

one PHP function to handle different MySQLi select statements

I have two MySQL tables with number of columns. The table structure is given below,
1.pictures
postedON
caption
imageName
thumbName
imageLocation
thumbLocation
2.Videos
postedOn
category
Link
I am using the folowing PHP function to fetch data from DB using a select command.
function select($table){
if($this->db_connection){
$query = 'SELECT * FROM '. $table;
$result = mysqli_query($this->db_connection,$query) or die($this->db_connection->error);
//print_r($result);
//echo "Affected rows: " . mysqli_affected_rows($this->db_connection);
//var_dump($result);
echo "<table>";
echo "<tr>";
echo "<th>Date Posted</th>";
echo "<th>Category</th>";
echo "<th>Link</th>";
echo "</tr>";
while($row = $result->fetch_assoc()){
echo "<tr>";
echo "<td>" . $row['postedOn'] . "</td>";
echo "<td>".$row['category']. "</td>";
echo "<td>" . $row['link'] . "</td>";
echo "</tr>";
}
echo "</table>";
}else{
echo "db_connection is = " . $this->db_connection;
}
}
}
The problem with this function as you can see, it can only serve only one table and not dynamic. Can someone please explain the way to dynamically fetch data from different table with different number of columns using only one PHP function? Thanks
Try using mysqli_fetch_fields()
<?php
function select($table){
if($this->db_connection){
$query = 'SELECT * FROM '. $table;
$result = mysqli_query($this->db_connection,$query) or die($this->db_connection->error);
$fieldinfo = mysqli_fetch_fields($result);
echo "<table>";
echo "<tr>";
foreach ($fieldinfo as $val)
{
echo "<th>".$val->name."</th>";
}
echo "</tr>";
while($row = $result->fetch_assoc()){
echo "<tr>";
foreach ($fieldinfo as $val)
{
echo "<td>" . $row[$val->orgname] . "</td>";
}
echo "</tr>";
}
echo "</table>";
}else{
echo "db_connection is = " . $this->db_connection;
}
}
It could be hard to explain given all the wrong premises you approach is based on, but I'll try.
First of all, you have to understand that a query like SELECT * FROM table has a very little use, next to none. Most of time you are always have some WHERE or at least LIMIT clause. So, such a function will have no use at all.
Next, you have to learn by heart that database interaction should never be intermixed with any output stuff like HTML.
Given these two premises above, your function should accept a fill qualified query as a parameter and return an array with data as a result.
For which array, in turn you can write a helper function to display its contents in the form of HTML table.
But again, such a generalized output function will be of little use as well, because, as you can see from your own example, different fields will need different formatting. So it's better to write output each time by hand.

PHP Delete Button

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_

SQL Image Database assembling rows into HTML cells and rows

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>";
}

Store and display MySQL result to/from PHP array

Suppose I have the following MySQL table result:
ID price
-------------
1 10
2 20
3 30
Basically what I want to accomplish is to store these values to a PHP array, and have these values displayed/echoed as a HTML table on a per row basis.
I could do something like:
if($result) {
$i = 0;
while ($row = mysql_fetch_array($result)) {
$id[$i] = $row['id'];
$price[$i] = $row['price'];
}
}
And just have those elements echo together with the HTML table.
However, I also need to have a function that allows the user to delete a row. With that mind I believe I need to have some sort of a 'key' for every row as the identifier for deletion -- a feature which multidimensional array supports.
There's nothing preventing you from using a multi dimensional array and using one of the unique values as an index:
// Store result
$data = array();
if($result) {
while ($row = mysql_fetch_array($result)) {
$data[$row['raiser_id']] = $row;
}
}
// Building table
echo "<table>";
foreach ($data as $row)
{
echo "<tr>";
echo "<td>" . $row['raiser_id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['fcr'] . "</td>";
echo "<td>" . $row['date_of_application'] . "</td>";
echo "<td>" . $row['no_of_heads'] . "</td>";
echo "<td>" . $row['place_of_farm'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Removing an entry by raiser_id
$raiser_id = 10;
if (!empty($data[$raiser_id]))
{
unset($data[$raiser_id]);
echo "Removed entry";
}
else
{
echo "No entry to remove";
}
To delete a row from the database, you have to have another PHP script and have to call it using POST method and run an SQL query in it.
If you are talking of just displaying this table, PHP has nothing to do here then - go for JavaScript.
By the time a user sees his table, there is no mysql result, no PHP array and no whole PHP running either. It's all dead long time ago. Keep that in mind.

Create an HTML5 range "slider" that does the same as the following drop down menu

I have a drop down menu, which is filled from a database. When I select a value in the menu it displays a table of the data selected from the database. I'd like to change this to an HTML5 range slider. So far with no luck. I also want to show the values (dates) beside the range as I move along it.
This is the code to the drop down menu:
// Set SQL string
$query = "SELECT * FROM Test";
// Execute SQL
$result = mysql_query($query);
// Find number of rows in the resulting recordset array
$num = mysql_numrows($result);
// Initialise loop counter
$i = 0;
echo ("<form><select name='users' onchange='showUser(this.value)'>");
// Loop through recordset until end
while ($i < $num) {
// Associate variables for result at position i at table location specified
$Time = mysql_result($result, $i, "Time");
// Echo each entry as an OPTION for the Select List
echo ("<option value=\"$Time\">$Time</option>");
// Increment Loop Counter
$i++;
}
echo ("</select></form><br>");
gettime.php:
$sql = "SELECT * FROM Test WHERE Time = '" . $q . "'";
$resultb = mysql_query($sql);
if (!$resultb) {
echo "<p>The following SQL failed</p><p>" . $sql . "</p>";
}
echo "<table border='1'>
<tr>
<th>Time</th><th>First PC Room</th>
<th>First Group Study Room 1</th>
<th>First Group Study Room 2</th>
<th>First Main Room</th>
</tr>";
while ($rowb = mysql_fetch_array($resultb)) {
$bmsTime = $rowb['Time'];
//Convert Excel Timestamp of DB to Unix Timestamp
$unixtime=($bmsTime-25569)*86400;
$readable=date('l jS \of F Y h:i:s A',($unixtime));
echo "<tr>";
echo "<td>" . $readable . "</td>";
echo "<td>" . $rowb['firstPCroom'] . "</td>";
echo "<td>" . $rowb['firstGrpStdyRm1'] . "</td>";
echo "<td>" . $rowb['firstGrpStdyRm2'] . "</td>";
echo "<td>" . $rowb['firstmainroom'] . "</td>";
echo "</tr>";
}
echo "</table>";
Below is what I have so far on the "slider":
echo "<input id='slider' type='range' min='0' max=\"$num\" step='any' />
<span id='range'> </span>";
?>
<script>
var selectmenu=document.getElementById("slider");
var colorchange;
selectmenu.onchange=function changecolour(){
if (selectmenu.value<"0.5")
{colorchange=0}
else if (selectmenu.value>="0.5") {colorchange=Math.round(selectmenu.value)}
document.getElementById("range").innerHTML=colorchange;
}
</script>
Any help would be greatly appreciated! Thanks
Here is a jsFiddle that updates a table row using jQuery. Presumably you would replace the data with an AJAX call.
If you were a little more specific about where exactly you were having trouble, someone else may be able to tailor a solution that better fits your needs.

Categories