Count from table with session id - php

I try to build a Notification Popup I have for this a script what seems to work
but when I add a code I am = getting the numbers 1 2 3 4 from the 4 records from this user-id
I would like to see only the total number (4)
<?php
$q=mysqli_query($conn,"select * from notice where user='".$_SESSION['user']."'");
$rr=mysqli_num_rows($q);
if(!$rr)
{
echo "<h2 style='color:red'>No any notice for You !!!</h2>";
}
else
{
?>
<?php
$i=1;
while($row=mysqli_fetch_assoc($q))
{
echo "<Tr>";
echo "<td>".$i."</td>";
echo "</Tr>";
$i++;
}
?>
</table>
<?php }?>

simply add the echo out of your loop
$i=1;
while($row=mysqli_fetch_assoc($q))
{
$i++;
}
echo "<Tr>";
echo "<td>".$i."</td>";
echo "</Tr>";

Just output the $rr variable, it contains the number of rows.
mysqli_num_rows
UPDATE, example added based on your code:
<?php
$q=mysqli_query($conn,"select * from notice where user='".$_SESSION['user']."'");
$rr=mysqli_num_rows($q);
if(!$rr)
{
echo "<h2 style='color:red'>No any notice for You !!!</h2>";
}
else
{
echo "<h2 style='color:green'>Total Notice for you: $rr</h2>";
}
?>

Use MySQL's COUNT function..
assuming your user table has a column named id.. try
$q=mysqli_query($conn,"select COUNT(`id`) as USERS from notice where....
Doing this will result in 1 result, so remove your while and just do..
$row=mysqli_fetch_assoc($q);
echo $row['USERS'];

Related

PHP While Loop to separate data in to columns

Hello Programing Newbie here.. Forgive me if I'm my question doesn't make sense. But, I'm attempting to Loop through a Table and display the Data in 3 Columns based on data..
There is a field "column_number" in the Table to identify the column it needs to be rendered to..
I have things working except getting the "Div's" assigned to "their" column.
right now the loop is creating a column for each. This is undesired..
See image..
Rendered Code :
I'll attach my Loop Code.
<?php
// display data retrieved if it's greater than zero
echo "<div id='colums'>";
if($num>0){
//echo "<div id='colums'>";
// loop through the records
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo "<div id='column{$column_number}'>";
//echo "<div id='column'>";
// display details
echo "<div class='Div'>";
echo "<div class='DivHeader' style='background-color:#{$title_bg_color}'>";
echo "<p style='color:#{$title_txt_color}' class='alignleft'>{$title}</p>";
echo "<p class='alignright'><a href='edit.php'>edit</a><a href='delete.asp'></a>";
echo "</p>";
echo "</div>";
echo "<div class='DivBody'>";
echo "Div Contents";
echo "</div>";
echo "</div>";
echo "</div>";
}
// the number of rows retrievede
$total_rows=0;
}
// Display message if no data found
else{
echo "<div class='alert'>";
echo "<strong>**** No User Data Found ****</strong>";
echo "</div>";
}
echo "</div>";
?>
I will try to add more information..
You can see in the first below screenshot I would like 3 Columns with the "widgets/DIV's" listed in each that have an associated column_number.
I named each "widgets/DIV's" accordingly the UserName, Column_Number and WidgetID so i can see if the DIV's are showing in the correct DIV/Column based on the logged in user.
I have also attached a pic of the Query and Data in the table for "usrid=3"
I have a Limit in the query because I was playing with possibly paging..
I must confess, The end result is to have the widgets draggable so the users can move them around and it will save/remember their place, column and order in the column.. The "Draggable" is currently working. I just want to get the widgets to land in their assigned column and then tackle the Draggable/Save..
Desired Result Screenshot :
Query and Data Screenshot :
Sample Desired Rendered Result :
Place the fetched results into an array then construct a foreach() loop and structure your column construct within the foreach() loop.
while($row = $result->fetch_assoc()){
$data[] = $row;
}
//Added a static array within $data for example purposes
$data = ['some info', 'somemore info', 'More info here'];//this is an array returned from your DB
if(is_array($data)){
$stmt = '';//declare an empty variable
foreach($data as $key => $value){
$stmt .= "
<div style='float:left; width: max-content; padding:20px;' id='columnTitle'>Column ".$key."
<div class=\"column".$key."\">".$value."</div>
</div>
";
}
$stmt .= "<div style='clear:both;'></div>";
}
Then use in html like:
<div>
<?=$stmt?>
</div>
or
<div>
<?php echo $stmt; ?>
</div>
output
Like an concept, i can propose you to modify the code according to this model:
<?php
$array = array(1,2,3,4,5,6,7,8,9,10); // Assuming we have 10 records
$max_col = 3; //Maximum columns we need
$init_col = 1; //Initial col number
echo "<div class='columns'>\n";
foreach($array as $value){
if($init_col <= $max_col){
//display first and second column
echo 'col' . $init_col;
//set init value increment
$init_col++;
} else {
echo "\n"; //Echo new line since we have new column
$init_col = 1;
//display first and second column
echo 'col' . $init_col;
//set init value increment
$init_col++;
}
}
echo "\n</div>";
Output:
<div class='columns'>
col1 col2 col3
col1 col2 col3
col1 col2 col3
col1
</div>
For your code example i propose this:
$max_col = 3; //Maximum columns we need
$init_col = 1; //Initial col number
if($num>0){
echo "<div id='colums'>";
// loop through the records
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
if($init_col <= $max_col){
//display first and second column
echo "<div id='column{$init_col}'>";
// display details
echo "<div class='Div'>";
echo "<div class='DivHeader' style='background-color:#{$title_bg_color}'>";
echo "<p style='color:#{$title_txt_color}' class='alignleft'>{$title}</p>";
echo "<p class='alignright'><a href='edit.php'>edit</a><a href='delete.asp'></a>";
echo "</p>";
echo "</div>";
echo "</div>";
echo "<div class='DivBody'>";
echo "Div Contents";
echo "</div>";
echo "</div>";
//set init value increment
$init_col++;
} else {
//Echo new line since we have new column
$init_col = 1;
//display first and second column
//display first and second column
echo "<div id='column{$init_col}'>";
// display details
echo "<div class='Div'>";
echo "<div class='DivHeader' style='background-color:#{$title_bg_color}'>";
echo "<p style='color:#{$title_txt_color}' class='alignleft'>{$title}</p>";
echo "<p class='alignright'><a href='edit.php'>edit</a><a href='delete.asp'></a>";
echo "</p>";
echo "</div>";
echo "</div>";
echo "<div class='DivBody'>";
echo "Div Contents";
echo "</div>";
echo "</div>";
//set init value increment
$init_col++;
}
}
echo "</div>";
}
// Display message if no data found
else{
echo "<div class='alert'>";
echo "<strong>**** No User Data Found ****</strong>";
echo "</div>";
}
Hope it will helps

Displaying 2 records in a column using php

So I have a code
<?php
$showorder = "SELECT order_number FROM orders WHERE customer_number=522";
$orderesult = mysqli_query($con, $showorder);
$ord = mysqli_fetch_array($orderesult);
?>
in my database customer number 522 has 2 order numbers, when i tried to show the result, it only shows 1.
Here's my other code
echo "<table>";
echo "<th>Order Number</th><th>Order date</th>";
echo "<tr><td>";
echo $ord["order_number"];
echo "</td><td>";
echo $ord["order_date"];
echo "</td></tr>";
You just need to use while() here for getting all records, something like:
while($ord = mysqli_fetch_array($orderesult)){
//echo all value here
}
Also note that, if you want to print $ord["order_date"] than you must need to select column also in your query.
Otherwise, $ord will only contain order_number value.
Your SQL is missing the extra column.
Current SQL:
SELECT order_number FROM orders WHERE customer_number=522
Change to:
SELECT order_number, order_date FROM orders WHERE customer_number=522
Put mysqli_fetch_array($orderesult); in a while loop.
while($ord = mysqli_fetch_array($orderesult)) {
echo $ord["order_number"];
# code
}
Replace your code with the below code and then try again
<?php
$showorder = "SELECT order_number, order_date FROM orders WHERE customer_number=522";
$orderesult = mysqli_query($con, $showorder);
echo "<table>";
echo "<tr>";
echo "<th>Order Number</th><th>Order date</th>";
echo "</tr>";
while($ord = mysqli_fetch_array($orderesult)) {
echo "<tr>";
echo "<td>$ord['order_number']</td>";
echo "<td>$ord['order_date']</td>";
echo "</tr>";
}
echo "</table>";
?>
echo "<table>";
echo "<th>Order Number</th>";
while($ord = mysqli_fetch_array($orderesult)) {
echo "<tr><td>";
echo $ord["order_number"];
echo "</td></tr>";
}
you must use loop to show all result , and you can use echo one time .
while($ord = mysqli_fetch_array($orderesult)) {
echo "<table>
<th>Order Number</th><th>Order date</th>
<tr><td>".
$ord["order_number"]."
</td></tr>";
}

Splitting Long php generated HTML table?

I use a MySql query to select data from my DB and then print it in the form of a HTML Table. It works perfectly, fine but sometimes the table consists of hundreds of rows and the webpage looks incredibly akward. Is there a way to split the table side by side into 2 or 3 halves.
Present Output
Desired output
PHP
<?php
....
echo "<h3>Classes attended :</h3>";
echo "<table class='dates' border='1'>";
foreach ($results as $dates) {
echo "<tr><td width='50%'>";
echo $dates->db_date;
echo "</td>";
echo "<td width='50%'>";
echo $dates->day_name;
echo "</td>";
echo "</tr>";
}
echo "</table>";
?>
What would be the best way to achieve it?
Help would be appreciated.
You can use PHP to determine in your loop if the loop index is divisible by a certain number using something like this:
echo "<h3>Classes attended :</h3>";
echo "<table class='dates' border='1'>";
$rowCount = 1;
$numRows = count($results);
$maxRows = 12;
foreach ($results as $dates) {
echo "<tr><td width='50%'>";
echo $dates->db_date;
echo "</td>";
echo "<td width='50%'>";
echo $dates->day_name;
echo "</td>";
echo "</tr>";
if($rowCount % $maxRows == 0 && $rowCount != $numRows) {
echo "</table><table class='dates' border='1'>";
}
$rowCount ++;
}
echo "</table>";
That's the basics of doing this. Basically in your loop you're testing each index to see if it's divisible by $maxRows, and if so then you're going to close your table and open a new one. You'll have to add the styling to place the tables side by side.
If you wanted to expand upon this concept you can set $maxRows to be an evaluation of $numRows. For instance if you wanted to split the items as close as possible to half in order to show just two tables, you could do... $numRows = count($results); $maxRows = round($numRows / 2);
Inspired by Robert Wade's answer:
<?php
....
echo "<h3>Classes attended :</h3>";
$i=0;
$maxRows=10;
foreach ($results as $dates) {
$a=$i/$maxRows == 0 ? "<table class='dates' border='1'>":"";
$b=$i/$maxRows == 0 ? "</table>":"";
echo $a;
echo "<tr><td width='50%'>";
echo $dates->db_date;
echo "</td>";
echo "<td width='50%'>";
echo $dates->day_name;
echo "</td>";
echo "</tr>";
echo $b;
$i++;
}
?>
At last, add some css style to the tables.
You can also use array_chunk() for splitting your results. Or instead of displaing a lot of tables next to each other you can make pagination and get only some range in your query. For example:
SELECT * FROM `clients` LIMIT 5, 10
Selects 10 rows beggining from row 5. Now, when you change your page, just change limit values.

How do i add another Table ROW at the end of my loop.

I would like to add a row, after the loop, the number of rows before the LAST row is random based on the user's orders. so for example the user ordered 10, i would like to add another row, to the list. even if the order is 3 there would still be another row at the end.
while ($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['prod_name']."</td>";
echo "<td>".$row['quantity']."</td>";
echo "<td>₱".number_format(($row['price']*$row['quantity']),2)."</td>";
echo "</tr>";
if($row['carrier']=="LBC"){
echo "<tr>";
echo "<td>Shippment Option Chosen: ".$row['carrier']."</td>";
echo "<td></td>";
echo "<td>₱250.00</td>";
echo "</tr>";
}
}
echo "</table>";
?>
Here, i made it create another row, but it creates a row after each row, i just need to add 1 row at the end of the table. Thank you :)
Hmm Why not just add a new query? I fixed your codes. and added these.
$qryx = "SELECT DISTINCT customers.serial,customers.name,customers.payment,customers.carrier,customers.tracking_no, orders.date, order_detail.productid, order_detail.quantity, order_detail.price, order_detail.orderid, inventory.prod_name
FROM customers
RIGHT JOIN orders on customers.serial=orders.serial
RIGHT JOIN order_detail on orders.serial=order_detail.orderid
LEFT JOIN inventory on order_detail.productid=inventory.prod_id
where customers.email='{$_SESSION['email']}'
AND order_detail.orderid='{$_REQUEST['orderid']}'
GROUP BY customers.carrier";
$resulty = #mysql_query($qryx);
while ($rowz=mysql_fetch_array($resulty)){
if($rowz['carrier']=="LBC"){
echo "<tr>";
echo "<td>Shippment Option Chosen: ".$rowz['carrier']."</td>";
echo "<td></td>";
echo "<td>₱250.00</td>";
echo "</tr>";
}
}
I changed the name of the qry, result, and row. and added DISTINCT and GROUP BY to remove redundancy.
You should add a line right before your
echo "</table>";
line, but after the closing bracket before it. That last closing bracket is where your loop ends. It should look like this:
while ($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['prod_name']."</td>";
echo "<td>".$row['quantity']."</td>";
echo "<td>₱".number_format(($row['price']*$row['quantity']),2)."</td>";
echo "</tr>";
if($row['carrier']=="LBC"){
echo "<tr>";
echo "<td>Shippment Option Chosen: ".$row['carrier']."</td>";
echo "<td></td>";
echo "<td>₱250.00</td>";
echo "</tr>";
}
}
echo "<tr>";
echo "<td>LAST LINE...</td>";
echo "<td></td>";
echo "<td></td>";
echo "</tr>";
echo "</table>";
?>
You can use mysqli_num_rows to get the no. of rows. Then you can add a counter in the while loop. When the counter = mysqli_num_rows, you can echo the row you wanted to echo at last
Example:
$totalrows=mysqli_num_rows($result);
$counter=1;
while ($row=mysql_fetch_array($result)){
//echo the row data
if($counter==$totalrows)
{
//echo the extra row which you wanted.
}
}
echo "</table>";

How to do an HTML 'upward' rowspan

Here is the problem:
I need to know if there is a way to do an upward rowspan on a <th> element on a form.
I am reading some rows inside a DB that I need to put inside an html table.
I am doing something like:
echo "<table>";
while($result = $resultSet->fetch())
{
echo "<tr>";
echo "<td>$result['Name']</td>";
echo "<td>$result['Job']</td>";
echo "</tr>";
}
ehco "</table>";
First steps are easy until I needed to 'span' together two adjacent cells that contains the same value.
For exemple if someone have the same name but had two jobs I would like them to have something like :
echo "<tr>";
echo "<td rowspan='2'>$result['Name']</td>";
echo "<td>$result['Job']</td>";
echo "</tr>";
But I can't predict how many jobs someone have (except they all have at least one and that they are all in order).
exemple of record in MySQL table
Name/**/Jobs
Paul/**/Jobs1
Simon/**/Jobs23
Simon/**/Jobs45
Roger/**/Jobs67
(All simon's jobs are 'behind one another', they are grouped. If Paul had a second job it would be the second record in the table 'pushing' simons jobs down).
So I need to change the rowspan value of the first element to fit how many jobs that person have.
This is why I would need to know if it is possible to do a upward span because i could just display every on of them and count how many jobs each person have and do a rowspan that would merge the table cell upward.
It would certainly be easier then fetching every row in the DB then looping throught them all and checking how many jobs a person have to 'span' the cells now and then display them all and then skipping them. and so on.
Thanks
A situation like this calls for pre-processing. Like so:
$people = array();
while($result = $resultSet->fetch())
{
if( !isset($people[$result['Name']])) $people[$result['Name']] = array();
$people[$result['Name']][] = $result['Job'];
}
echo "<table>";
foreach($people as $name=>$jobs)
{
echo "<tr>";
echo "<td rowspan=\"".count($jobs)."\">".$name."</td>";
echo "<td>".array_shift($jobs)."</td>";
echo "</tr>";
foreach( $jobs as $otherjob)
{
echo "<tr><td>".$otherjob."</td></tr>";
}
}
echo "</table>";
Done!
What you're looking for doesn't exist in HTML. But you can do it like this:
$currName = $result['Name'];
echo "<tr>";
if($currName==$prevName)
{
echo "<td> </td>";
}
else
{
echo "<td>$result['Name']</td>";
}
echo "<td>$result['Job']</td>";
echo "</tr>";
$prevName = $currName;
Rather than using rowspan, just nest a table in the second column with all of the jobs for that person.
echo "<tr>";
echo "<td>$result['Name']</td>";
echo "<td>";
echo "<table>"
foreach($jobs as $job): //$jobs holds the job values for the current name
echo "<tr><td>";
echo $job;
echo "</td></tr>";
endforeach;
echo "</table>";
echo "</td>";
echo "</tr>";
Note: you will need to preprocess the result set to get a 2D array for this method (see answer from Niet the Dark Absol).

Categories