calculations on specific rows in table of database using php - php

i'm working on a php project that manages teachers in school. but i'm stuck with a problem, i have two tables in my database, first one T1 has on row, second T2 has multiple rows, but they have the same columns number. in a third table T3 i need to fill a column with the total of
(cell1 of T1*cell1 of T2) + (cell2 of T1*cell2 of T2)+ (cell3 of T1*cell3 of T2)....to the last column
i just couldn't find the right way to do this
this is the part that shows the tables from my db
<?php
$host="localhost";
$user="root";
$pass="";
$bdd="test";
$cnx=mysql_connect($host,$user,$pass);
if(!$cnx)
echo"connexion echouee"."</br>";
else
echo"connexion reussie"."</br>";
if (mysql_select_db($bdd))
echo"base de donnees trouvee"."</br>";
else
echo"base de donnees introuvable"."</br>";
$req1="SELECT * FROM `table1`";
$res1=mysql_query("$req1");
// printing table rows
while($row1 = mysql_fetch_row($res1))
{
echo "<tr>";
foreach($row1 as $cell1)
echo "<td>|$cell1|</td>";
echo "</tr>"; echo"</br>";
}
echo "_____</br>";
$req2="SELECT * FROM `table2`";
$res2=mysql_query("$req2");
// printing table rows
while($row2 = mysql_fetch_row($res2))
{
echo "<tr>";
foreach($row2 as $cell2)
echo "<td>|$cell2|</td>";
echo "</tr>";echo"</br>";
}
?>

As long as it is guaranteed that table1 will return 1 row, here is a suggestion:
Instead of using a while loop to fetch the contents, just fetch the row, so the contents of table1 are in $row1
Change foreach($row2 as $cell2) to a foreach($row2 as $key=>$value) format. This way you will have the index of the corresponding element in $row1
Inside the foreach($row2 as $key=>$value) loop, use an accumulator to calculate "Column I". E.G. $tot += $value * $row1[$key]
"echo" the accumulater column before the </tr>
You also probably want to add an empty <td> in the $row1 loop to make sure that all the rows have the same number of columns.

You can traverse second table and calculate total with nested loop:
$res1 = mysql_query("SELECT * FROM `table1`");
$res2 = mysql_query("SELECT * FROM `table2`");
$row1 = mysql_fetch_row($res1);
$row = 0;
// for each row of second table
while ($row2 = mysql_fetch_row($res2)) {
$row++;
$total = 0;
// for each column of first table's row
foreach ($row1 as $index => $table1RowValue) {
// get value of same column in the second table's row
$table2RowValue = $row2[$index];
// calculate aggregated value
$total += $table1RowValue * $table2RowValue;
}
// print result
echo "Line $row: $total</br>";
}

Related

How to create an Edit button for each row from a 2d array in PHP

I have a 2d array in php that displays the table contents and I was able to create an edit icon for each row. However, I am having trouble retrieving the data from the selected row.
Here's how I populated my array:
<?php
//use query to retrieve columns
$sql = "SHOW COLUMNS FROM $table_name";
$result1 = mysqli_query($conn, $sql);// contains the query that creates 2d
while ($record = mysqli_fetch_array($result1)) { //returns current row 1d
$fields[] = $record['0'];//takes first element from record called fields (table names)
}
//retrieve the table content since data table has rows and columns
//lets use 2d array
$data2dArr = array();
//retrieve all columns without listing them explicitly, for the sort
if ($dir == 0) {
$query = "SELECT * FROM $table_name ORDER BY $fields[$cn]"; //ascending
} else {
$query = "SELECT * FROM $table_name ORDER BY $fields[$cn] DESC"; //descending
}
$result2 = mysqli_query($conn, $query);
while ($line = mysqli_fetch_array($result2, MYSQL_ASSOC)) {
$i = 0; // counter
//each element in array line
foreach ($line as $col_value) {
$data2dArr[$i][] = $col_value; // is stored in col value, dataarr used for display
$i++;
}
}
?>
First, I printed the values in my 2d array like this:
<?php
for ($j = 0; $j < count($data2dArr[0]); $j++) {
?>
<tr>
<?php
for ($k = 0; $k < count($fields); $k++) {
?>
<td><?php print $data2dArr[$k][$j]; print $j;? </td>
<?php
}
//added the Edit button here
?>
<th><input type="image" src="images/edit.png" onclick="openForm()"/</th>
<?php
}
?>
In my edit.php file, I have the same array above but inside the 2nd for loop, contains:
<td><input name="field<?php echo $k ?>" id="field<?php echo $k ?>" placeholder="<?php print $data2dArr[$k][$j] ?>" class="full-width" type="text"> </td
the purpose is print the selected row x that contains y columns but the solution above prints out all of the elements. I know that it's because all contents in my table are being put in my input<> for each iteration, what I cannot figure out is how to print just the fields of the column from selected row.
For example,
From the table called Student
student_number | name | class| major |
22 | Rick | 3 | CS | editButton
32 | Ross | 5 | Math | editButton
If I select the student number from the second row, I expect my input placeholder to have |32|Ross|5|Math
I would like to know how do I go about this? Any advice would be very helpful.
You question is kinda long and confusing so I assume you have problem to print specific
field in the array?
You can try:
foreach($data2dArr as $key => $value){
print $data2dArr[$key]["student_number"]."|".$data2dArr[$key]["name"]."|".$data2dArr[$key]["class"]."|".$data2dArr[$key]["major"];
}
It is better to show less of your code and explain briefly yet clearly what are you trying to achieve

how to make column2 second row becomes first row while all other columns stays the same

My table now
the above picture shows how my table looks like after select from sql. I wish to eliminate the first row of the time column move all rows up of the time column by one row. like the picture below.desired table Please advice. Any advice that would help is welcome.
code:
<?php
require_once 'db.php';
mysqli_set_charset($conn, "utf8");
$arr = array();
$sql = ("SELECT * FROM myTable WHERE idvisit=384 ORDER BY server_time ASC ");
$sql = mysqli_query($conn, $sql) or die ("ERROR :" .mysqli_error($conn));
while ($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)){
$arr[] = $row['time_spent'];
echo "<br>";
}
$fruit = array_shift($arr);
print_r($arr);
echo $arr;
?>
First store the result into an array then remove first item from the array.
Sample Code:
$data = array();
while($row = mysqli_fetch_assoc($query))
{
$data[] = $row;
}
array_shift($data); //array_shift() remove first element of an array
Now run another loop if you want to grab result of each row. If you want to show it in table, here is a sample loop with html table.
echo "<table><tbody>";
forach($data as $item){
echo "<tr><td>";
echo $item['column_name'];
echo "</td></tr>";
}
echo "</tbody></table>";
Now, in the table it will show the result without first row from database.

Numbering the array rows

I have selected the whole table with mysql, there are records of sold tickets.
When I am writing them out with foreach, they are showing correctly from the newest sold ticket at the top to the oldest purchase at the bottom.
The problem is that the IDs do not look good. I have done many test purchases before launching it and the id numbers are starting from 50 now.
I would like to keep it as it is now but only number the records with normal numbers from 1. The problem is that the highest number must be at the top since the latest record is there on top. Could somebody advice me on how to do this please?
When you use while loop you have to create one variable before start loop and increatement it by 1 in loop and use it as row number :)
$sql ="SELECT * FROM tbl_purchases ORDER BY id DESC";
if ($result = $link->query($sql)) {
echo "<table border='1'>";
$line_counter=mysqli_num_rows($result);
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>".
"<td>{$line_counter}</td/>".
"<td>{$row['id']}</td/>".
"<td>{$row['name']}</td>".
"</tr>";
$line_counter--;
}
echo "</table>";
}
Usually, when you're fetching from DB, the ID column which is usually on auto-increment is not reliable, so when fetching, you should run your own auto-increment. i.e.
<?php foreach($rows as $index => $row): ?>
<table>
<td><?php echo $index + 1 ?></td>
to display with custom index in descending order using php
$sql ="SELECT * FROM tbl_purchases ORDER BY id DESC";
if ($result = $link->query($sql)) {
$index = mysqli_num_rows($result);
echo "<table border='1'>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>".
"<td>{$index}</td/>".
"<td>{$row['id']}</td/>".
"<td>{$row['name']}</td>".
"</tr>";
$index--;
}
echo "</table>";
}
for ascending index
$sql ="SELECT * FROM tbl_purchases ORDER BY id DESC";
if ($result = $link->query($sql)) {
$index = 1;
echo "<table border='1'>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>".
"<td>{$index}</td/>".
"<td>{$row['id']}</td/>".
"<td>{$row['name']}</td>".
"</tr>";
$index++;
}
echo "</table>";
}
==================
To reset the auto incremental column in DB (start again from 1)
For MYISAM
ALTER TABLE tbl_purchases AUTO_INCREMENT = 1;
For INNO DB
SET #num := 0;
UPDATE tbl_purchases SET id = #num := (#num+1);
ALTER TABLE tbl_purchases AUTO_INCREMENT =1;

How to echo a dynamic html snippet based on a MySQL databse with PHP?

I'm trying to create an image gallery with a for loop iterated by a counter of database rows.
To make it more clear: for each row in the table, get only the id(primary index) number and the image link from the server (not all the info in the row). With that information, echo an HTML image tag with the link inside the 'src=' and the id inside the 'alt='.
Two problems here:
1- the id number of the first row isn't zero.
2- I don't have a clue on how to get the total number of rows and to fetch only those two informations (id and img source).
That way, I could subtract the total number of rows minus the id number of the first row and using it to put an end on the loop.
So how to echo this dynamic html snippet based on my databse with PHP?
My code:
<?php
$link = mysqli_connect('localhost','user','pass','db');
$result = mysqli_query($link, "SELECT * FROM `table`");
$rows = mysqli_num_rows($result);
/* free result set */
mysqli_free_result($result);
$caption = mysqli_query($link, "SELECT ");
for($i=0; $i < $rows; $i++) {
echo "<img src='$imageURL' alt='$idNumber'>";
}
?>
You need to use sql functions to iterate through the dataset results. Replace your for loop... replacing 'image_url_column' and 'id_number_column' with the name of your actual columns in your db:
while ($row = while ($row = mysqli_fetch_assoc($caption)){){
echo "<img src='".$row['image_url_column']."' alt='".$row['id_number_column']."'>";
}
This is a really easy task.
First we fetch the data from the database using mysqli_query to do the query.
Then we use mysqli_fetch_array to get an array so then we can loop through it and echo each item.
After that, we mysqli_num_rows to get the total number of rows returned and increment it by 1 so it is not zero.
NOTE: Since you are going to increment the id to avoid getting a '0', don't to forget to minus '1' if you intend to use that id for some server-side purpose.
$result = mysqli_query($link, "SELECT * FROM `table`"); //query sql
$result_array=mysqli_fetch_array($result, MYSQLI_ASSOC);//return array from the query
$count = mysqli_num_rows($result); //get numbers of rows received
foreach($result as $row){ //do a foreach loop which is really simple
echo "<img src='". $row['img_column_name_from_db'] . "' alt='" .$row['id_column_name_from_db'] + 1 . "'>"; //echo data from the array, + 1 to "$row['id_column_name_from_db']" so that 'alt=' doesn't start from '0'.
}
echo $count;
You can use the count function of MySql to achieve the total number of rows.
also you can do this via mysqli_num_rows() function of mysql.
Code:
<?php
$link = mysqli_connect('localhost','user','pass','db');
$caption = mysqli_query($link, "SELECT id, img, count(id) as total from table");
echo
//$rows = mysqli_num_rows($result);
while($rows = mysqli_fetch_assoc($caption)){
echo "<img src='$rows[img]' alt='$rows[id]'>";
echo "Total Rows: ".$rows[total];
}
?>

Repeat region table with minimum number of rows

I have created a table that is dynamically populated from a MySQL database using PHP. The first row is a repeated region for all records. However is it possible to have a minimum number of rows created whether there was a record or not. For example if I have 8 records for a given date could the table be drawn with 12 rows regardless, 4 of them will just be empty?
Firstly, good design separates retrieval and data model from display (MVC)
$data = array();
$result = $db->query("SELECT * FROM table");
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
Now you just do
$MIN_VALUE = 12; // Some value
$i = 0;
foreach($data as $row) {
//Data row
$i++;
}
while(!$i < $MIN_VALUE) {
//Blank row
$i++;
}

Categories