index array results from mysql call so I can call multiple times - php

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'];
}

Related

Multiple Tables of same Database on the same site

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

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.

Inner nested while loop is false on second iteration

The code below creates html table data.
Row 1 is correct and returns column1 with $row['LNAME'] and then column2 with ALL of the $row1['NAME'] results (there are four).
Row 2 and onwards echo only column1 and an empty cell in column2.
while ($row = $sql->fetch_assoc()){
echo "<tr>";
echo "<td>";
echo $row['LNAME'];
echo "</td>";
echo "<td>";
while($row1 = $sql1->fetch_assoc()){
echo $row1['NAME'] . "<br>";
}
echo "</td>";
echo "</tr>";
}
It would seem that after the inner loop has completed it evaluates as false in future iterations of the outer loop where I would like it to evaluate as true.
What should I change so that the inner loop does not evaluate as false until the outer loop does?
This is because you're at the end of $sql1. You can seek to the beginning of it again, but my preference is to separate pulling the data from the DB and the iterations, so I'd write it like this (using your code as the starting point):
$lname = array();
while($row = $sql->fetch_assoc()){
$lname[] = $row;
}
$name = array();
while($row1 = $sql1->fetch_assoc()){
$name[] = $row1;
}
foreach($lname as $lvalue) {
echo "<tr>";
echo "<td>";
echo $lvalue;
echo "</td>";
echo "<td>";
foreach($name as $value) {
echo $value . "<br>";
}
echo "</td>";
echo "</tr>";
}
you will need to use mysql_data_seek($rs, 0) to reset your result pointer at the first row. this is under the assumption that mysql is hidden behind your object. for mysqli use mysqli_data_seek respectively

PHP: using SQL result in a loop without re-executing query

I am trying to add 3 combo boxes which all display the exact same information that comes from my MySQL db. It seems like the code I wrote makes the entire page wait until all 3 combo boxes are populated, before continuing.
<?
$query = "Select * from tblWriters order by surname";
for ($i = 1; $i <= 3; $i++) {
$result = mysql_query($query);
echo "<tr><td>Writer".$i." *</td><td>";
echo "<select name='txtWriter".$i."' style='width: 200px;'>";
echo "<option value ='' selected='selected'></option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value ='" . $row['id'] . "'> " . $row['surname'] . ", " . $row['name'] . "</option>";
}
echo "</select><td></tr>";
}
?>
I would like to optimize this piece of code, so the query will not be executed 3 times, as I believe this is where the page slows down.
If I put
$result = mysql_query($query);
outside of the for loop, the 2nd and 3rd combo box do not populate. I tried looking into resetting the pointer of the result, but I can't seem to figure out how that works.
Also, is there a way I can reuse the while loop, so I don't have to execute it 3 times?
Can someone point me in the right direction?
I'm pretty new to PHP and trying to learn on my own. Any help would be much appreciated. Thanks!
If you move your mysql_query() out of the loop again, you can reset your mysql-result-pointer by using mysql_data_seek() at the beginning or end of your loop.
This will result in:
mysql_query($query);
for($i=1;$i<=3;$i++);
{
mysql_data_seek(0); // reset datapointer
// output querydata
}
I'm obliged however to point out that the mysql-extension is deprecated by now and you should use mysqli or pdo for new projects and code.
Cache the query result in an array, then generate your markup:
$query = "Select * from tblWriters order by surname";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_array($result))
{
$data[] = $row;
}
for ($i = 1; $i <= 3; $i++) {
echo "<tr><td>Writer".$i." *</td><td>";
echo "<select name='txtWriter".$i."' style='width: 200px;'>";
echo "<option value ='' selected='selected'></option>";
foreach ($data as $row) {
echo "<option value ='" . $row['id'] . "'> " . $row['surname'] .
", " . $row['name'] . "</option>";
}
echo "</select><td></tr>";
}

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.

Categories