Repeat region table with minimum number of rows - php

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

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

calculations on specific rows in table of database using 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>";
}

Get sum of each row added together in while loop

So I have a mysql table that contains an integer in each row. What I am trying to do is get the sum of the integers. Here is what I currently have that is working.
$cn = 0;
$sql = mysqli_query($con,"SELECT * FROM members WHERE member='$userid'");
while($row = mysqli_fetch_array($sql)) {
$i = $row['number'];
$cn = $cn + $i;
}
echo $cn;
So I make $cn equal zero then each time it goes through the loop it will add the number from the matching row.
Does anyone have a better idea on how to accomplish this? Thanks!
You don't need to use PHP or here a loop for that, because your database can do the job for you.
$sql = mysqli_query($con,"SELECT sum(number) FROM members WHERE member='$userid'");
If you want the sum of the column number for each member with a particular user id
$sum = 0;
$sql = mysqli_query($con,"SELECT SUM(number) as number_total FROM members WHERE member='$userid'");
while($row = mysqli_fetch_array($sql)) {
$sum = $row['number_total'];
}
$sum will have the total

Not able to extract all values of a column in mysql

I am having problem extracting values from a mysql table:
I need to get all values of picname column from a table where uid condition is satisfied.
Now i have two rows where this condition is satisfied but i am getting output only for 1st case. I am not able to get the second row's value. 1st rows value repeats again for second time.
$i = 0;
for($i;$i<2;$i++)
{
$s = "SELECT picname FROM uploaded_data WHERE uid='$uid'";
$que = mysql_query($s,$db);
while($num = mysql_fetch_array($que))
{
echo $name ['picname'];
}
}
Thank You
it should not give you any result you do not have
$name
should be:
$i = 0;
for($i;$i<2;$i++)
{
$s = "SELECT picname FROM uploaded_data WHERE uid='$uid'";
$que = mysql_query($s,$db);
while($num = mysql_fetch_array($que))
{
echo $num['picname'];
}
mysql_free_result($que);
}

Checking to see if a MySQL row is populated

I have a page that writes to a MySQL table. The table has a set amount of rows (24).
I have an $id variable that's set by a rand() function. I basically want to pull the row at that $id, so if $id was 3, I want to pull the third row. Then, I want to check if there is a price set at that row (indicating that the row is being used). If there is no price, I want to keep $id at the value it has been set at and proceed with the query. If there is a price, I want to re-randomize the $id variable, and check again if that row is used up. When it finds an empty row, proceed with the query.
My solution semi-works, but it seems to have a <10% chance of overwriting a used row, for some reason. I want it to never overwrite a used row.
Here's my code:
mysql_select_db("delives0_booklet", $con);
$query = "SELECT * FROM booklet WHERE id = '$id'";
$res = mysql_query($query,$con);
$newId = $id;
while($row = mysql_fetch_array($res))
{
if($row['price'] != 0)
{
do{
$newId = rand(1, 24);
}while($newId == $id);
}
}
$id = $newId;
mysql_query("UPDATE booklet SET price = '$price', advertiser = '$advertiser', image = '$image', monthsRemaining = '$monthsRemaining', availability = 1 WHERE id = '$id'");
Edit
I had the idea to do this. I loop through the table and I put the 'id' of each unfilled spot into an array. Then I pick randomly from that array. However, there seems to be a bug that I can't find, since the array keeps showing as having nothing in it, even after the loop is run, and $i is the correct figure.
mysql_select_db("delives0_booklet", $con);
$query = "SELECT * FROM booklet";
$res = mysql_query($query,$con);
$i = 0;
$isEmpty = array();
while($row = mysql_fetch_array($res))
{
if($row['price'] == 0)
{
$isEmpty[i] = $row['id'];
$i = $i + 1;
}
}
echo $i . " unfilled spots.";
$n = 0;
while($n<$i)
{
echo $isEmpty[$n];
$n = $n + 1;
}
if($i > 0)
{
$id = $isEmpty[rand(0, $i)];
}
if($i == 0)
{
echo 'All spots have been filled.';
}
I think it is a top level logic problem. Because you populate with random ids, you can get duplicate ids, and so when you update "WHERE id = '$id'" you may be picking up rows already populated.
I don't know your goal, but perhaps using an auto-increment id, and dropping rows that you want to get rid of, is the way to go. A rolling set of rows (24 at a time) but with ever increasing ids, would prevent mistaking one for the other.
If I understand the problem correct, this should work:
SELECT *
FROM booklet
WHERE price = 0 OR price IS NULL
ORDER BY RAND()

Categories