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.
Related
i need some little help ,,,
I have a data like this.., (I use php mysql)
Initially there was no problem with this, but as time goes by, my data is getting bigger and bigger.
finally its made my program slow ..
I think maybe because I used "while" inside of "while". make SQL is called multiple times.
is there a solution to make it faster ??
I have hundreds of data in tb1 and thousands in tb2 T.T
You should not be using loops to iterate over tables. SQL is an inherently set based declarative language. So, you should just join the tables, order the result set, and then use a single loop with presentation logic. Use this query:
SELECT tb1.id_a, tb2.id_b, tb2.data
FROM tb1
INNER JOIN tb2 ON tb2.id_a = tb1.id_a
Then, use this PHP script:
echo "<table>";
echo "<tr><th>No.</th><th>id_b</th><th>data</th></tr>";
$a = null;
while ($row = mysql_fetch_array($result)) {
if ($a == null || $row['id_a'] != $a) {
echo "<tr>";
echo "<td>" . $row['id_a'] . "</td>";
echo "<td colspan=2>data" . $row['id_a'];
echo "</tr>";
$a = $row['id_a'];
}
echo "<tr>";
echo "<td></td>";
echo "<td>" . $row['id_b'] . "</td>";
echo "<td>" . $row['data'] . "</td>";
echo "</tr>";
}
echo "</table>";
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 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.
I have working code but I seem to have introduced a bad bottleneck to my code. Before I go into detail, let me give you some background on what this code does. I have a table generated in PHP/HTML that shows a list of parts that are in a database (149 parts). The user can select a quantity for that item and click "Add To Cart" which all works fine.
However, I tried to spruce things up a bit by adding in a feature that only allows the user to select the quantity we actually have on hand for this product (before add this feature I previously had the max value hard coded at 100).
Now this does work, but it is TERRIBLY slow (50 seconds to load the page). However, before implementing this the page loaded immediately without a problem, therefore this is definitely a problem with the getPartQuantityOnHand() function.
I think the problem is that for every part (149) I am calling this function that then has to reconnect to the database to find the correct quantity. Does anyone see a way I can improve this? FYI, the parts are hosted on a completely separate database from where the quantity on hand for these parts are hosted.
I have left some parts out of the php code since it was unnecessary bulk for this post, I know that I am missing parts here.
getParts.php
<?php
$partList = $_SESSION['controller']->getParts();
foreach ($partList as $part) {
//Call to get the current quantity on hand for this specific part
//THIS IS WHEN THE PROBLEM WAS INTRODUCED
$quantityOnHand = $_SESSION['controller']->getPartQuantityOnHand($part->number);
//Only display this part if we have at least one on hand
if ($quantityOnHand > 0)
{
echo "<tr>";
echo "<td>" . $part->number . "</td>";
echo "<td>" . $part->description . "</td>";
echo "<td>$" . $part->price . "</td>";
echo "<td>";
echo '<input name="qty'. $part->number .'" type="number" value="1" min="1" max="' . $quantityOnHand .'"/>';
echo "</td>";
echo "</form>";
echo "</td>";
echo "</tr>";
}
}
echo "</table>";
echo "</div>";
?>
getPartQuantityOnHand()
public function getPartQuantityOnHand($partNum) {
$conn = $this->connect();
$sql = "select Quantity from ReceivingInfo where PartNumber = '$partNum'";
$stmt = $conn->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$quantityOnHand = $row['Quantity'];
return $quantityOnHand;
}
Thanks for any help you can provide!
As the two databases are separate you have two options:
Determine the part numbers before you loop and generate your HTML, then query all at the same time with an IN clause:
SELECT ... WHERE PartNumber IN (1, 2, 3, 4);
Select all stock levels for your parts when you first call getPartQuantityOnHand and store that:
public function getPartQuantityOnHand($partNum) {
if(!$this->partQuantitiesOnHand) {
$conn = $this->connect();
$sql = "select Quantity, PartNumber from ReceivingInfo";
$stmt = $conn->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$this->partQuantitiesOnHand = array_column($rows, 'Quantity', 'PartNumber');
}
return $this->partQuantitiesOnHand[$partNum] ?? null;
}
The disadvantage of option 2 is that if you have many more parts than are listed on a single page, it will never perform as well as option 1.
So, instead of doing a 149 different SQL queries, just do one query that brings back all the Quantity values you need.
ex.
SELECT Quantity FROM ReceivingInfo WHERE PartNumber IN ($listOfPartNums)
of course you will have to build the string $listOfPartNums
Or, if you really are always bringing back the full list of them, you can exclude the IN clause and don't need to worry about generating the string.
You'll have to change your function a bit to store the partnum/quantity pairs in an associative array.
Then in your getParts.php get the Quantity like this:
<?php
$partList = $_SESSION['controller']->getParts();
$quantityList = getQtyList(); // return assoc array of partnum/qty pairs
foreach ($partList as $part) {
//Call to get the current quantity on hand for this specific part
//THIS IS WHEN THE PROBLEM WAS INTRODUCED
$quantityOnHand = $quantityList[$part->number];
//Only display this part if we have at least one on hand
if ($quantityOnHand > 0)
{
echo "<tr>";
echo "<td>" . $part->number . "</td>";
echo "<td>" . $part->description . "</td>";
echo "<td>$" . $part->price . "</td>";
echo "<td>";
echo '<input name="qty'. $part->number .'" type="number" value="1" min="1" max="' . $quantityOnHand .'"/>';
echo "</td>";
echo "</form>";
echo "</td>";
echo "</tr>";
}
}
echo "</table>";
echo "</div>";
?>
I'm struggling to reference the MySQL data simultaneously by both column name and individual row number.
The code sample below does the following;
Successfully
prints the correct data to a table when looping through the whole table, referencing columns by name OR number.
when referencing individual rows in the database the correct columns by the column number
But I can't get it to successfully reference individual rows (by number) and columns (by name) at the same time.
Apologies if this is a ridiculous question, I'm new to PHP and MySQL.
I think my description is abysmal, so maybe this will help. Of the four options available (column either by name or number, and rows either individually or looping through a group) it works like this;
Column by number, each row in a loop. Yes.
Column by name, each row in a loop. Yes.
Column by number, individual row. Yes.
Column by name, individual row. NO! (as shown in the last line of code, a is a column in my database)
Does anyone please have any advice on what I'm doing wrong?
Code:
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<t
h>Lastname</th>
<th>test</th>
<th>order</th>
</tr>";
$ind = 0;
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . ($row['age'] * 1) . "</td>";
echo "<td>" . ($row['a']) . "</td>";
echo "<td>" . $ind. "</td>";
echo "</tr>";
$ind += 1;
}
echo "</table>";
$sql="SELECT * FROM Persons ORDER BY PID";
if ($result=mysqli_query($con,$sql))
{
// Prints single entry AP
print "<br>";
$rowNumber = $id;
mysqli_data_seek($result, $rowNumber);//start row is whatever you need to be the first row
$row = mysqli_fetch_row($result);
print "<br>";
//-----------------------------------------------------
$mathString = $row[1];
$description = $row[4];
echo "math string:" . $mathString . "<br>";
echo "a is said to equal:" . $description . " - " . $row['a'];