Grouped/Stratified Reports using PHP and MySQL - php

I am trying to generate a grouped/stratified report using PHP and MySQL.
tbl_items has the following fields: (1) UserName and (2) ItemName
A single user can have multiple items listed.
I want to generate an output where the data is stratified by each user. For example:
*UserName #1
-ItemName 1
-ItemName 2
*UserName #2
-ItemName 3
*UserName #3
-ItemName 4
-ItemName 5
I keep playing with the code, trying to put a loop inside a loop...but can't figure out how to do it! This is what I have so far:
<?
$sql="SELECT * FROM $tbl_items";
$result=mysql_query($sql);
?>
<html>
<body>
<? php while($rows=mysql_fetch_array($result)){ ?>
Item: <? echo $rows['ItemName']; ?> (<? echo $rows['UserName']; ?>)
<?php } mysql_close(); ?>
</body>
</html>
Please help!

while($row=mysql_fetch_array($result))
{
$itemsByUser[$row['UserName']][] = $row;
}
foreach($itemsByUser as $user => $items)
{
echo $user . "<br>";
foreach($items as $array)
{
echo "-" . $array['ItemName'];
}
}
This first creates an array that is order by Username. This means each user has an element in the array that contains an array of the items that have been assigned to the user.
Then, we go over each user and print out all of the items.

Related

I want to display products from my database to HTML. I only get the last row from my database to show up

I am working on a school project, a simple webshop.
I decided to ask it here.
What i want to do is display products from my database to my "product page" using PHP.
For some reason i only get the last product to show, also having trouble with the images.. I know the query is correct.
"SELECT * FROM products";
Here is my code.
This is my PHP, I have put this on top of the product.php page.
product.php
<?php
session_start();
include "includes/connectie.php";
include "includes/navbar.php";
$vraag = "SELECT * FROM products";
//var_dump($vraag); Var dump test
$resultaat = $conn->query($vraag);
if ($resultaat->num_rows > 0)
{ // Min. 1 row returned
while ($rij = $resultaat->fetch_assoc())
{
$id = $rij['id'];
$titel = $rij['product_name'];
$prijs = $rij['product_price'];
$omschrijving = $rij['description'];
$foto = $rij['image'];
}
}
else
{
// Do nothing
}
?>
This is my HTML code below, where i want to "display" i also have this in the same file as code above. So first php, then html
product.php
<body>
<div class="products">
<div class="productContainer">
<h1 id="banner">ALL ITEMS</h1>
<div class="productRow">
<?php
echo '<img src="img/product_'.$id.'.jpg">';
?>
</div>
<?php
echo '<h1>'.$titel.'</h1>';
echo '<p class="prijs">'.$prijs.'</p>';
echo '<p class="omschrijving">'.$omschrijving.'</p>';
?>
<div class="productRow">
<?php
echo '<img src="product_'.$id.'.jpg">';
echo '<h1>'.$titel.'</h1>';
echo '<p class="prijs">'.$prijs.'</p>';
echo '<p class="omschrijving">'.$omschrijving.'</p>';
?>
So i only put the HTML/PHP where i would want the first two products as example.
In total i have 6 products. I also included a picture of the database
database
What am i doing wrong?
This is how it looks right now:
example of product display
in your php file you have added all the values from database to an array. but you have not used any loop when you are trying to display array values in html. loop is a must to display all the values of array. Add a loop in your HTML file.

PHP dropdown menu that concatenates 2 rows from MySQL data table

Not experienced with creating forms in PHP.
I can get my form to produce a dropdown list that has one of my rows listed as an option, but as soon as I try to concatenate 2 rows together (from the same table) for option output...
a) It just doesn't work and I get errors
b) I get the first row as a single option, then my next row as a separate option.
I know there is a simple solution to this, but I am an online student just learning, and I can't seem to find a good example of the code to write it. I'm pretty sure it's an issue of quotes not being placed correctly.
MySQLTable Data:
Table Name: courses
Table Rows: course_id, course_name, max_enrolment
Sample Data: LO-COMP-8001, Intro to HTML, 20
function select_course(){
global $open;
$select = "SELECT * FROM courses";
$result = mysqli_query($open, $select);
return $result;
}
<form action="insert.php" method="post">
<dl>
<dt>Select Course</dt>
<dd><select name="course_id">
<?php // CREATE dropdown menu
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {
foreach ($row as $selection) {
echo "<option value=\"$selection\">$selection</option>";
}}
?>
</select>
</dd>
</dl>
Then there are a few more form fields such as student name and student id afterwards...
Goal Output:
course_id course-name
"LO-COMP-8001 Intro to HTML" ... as a single connected dropdown option and other remaining courses in a dropdown menu
Current Output:
LO-COMP-8001 (as an option)
Intro to HTML (as another option! ... No good)
20 (must be hidden, I need to check if course is full in another function and either allow or deny a student to enrolled etc.)
I have tried:
// output is the one mentioned above..
echo "<option value=\"$selection\">$selection</option>";
// or alternatively...
echo '<option value="'.$row['course_id'].'">'.$row['course_id'].'</option>';
But the second option creates all kinds of weird results.
This is what I am experimenting with right now...
echo '<option value="'.$row['course_id'] $row['course_name']'">'.$row['course_id'] $row['course_name'].'</option>';
But there is a bunch of issues with quotes and square brackets, and I just don't know how to format it correctly for the output.
Any assistance is appreciated.
$row holds the entire row as an associative array therefore no need for the 'foreach' loop.
function select_course(){
global $open;
$select = "SELECT * FROM courses";
$result = mysqli_query($open, $select);
return $result;
}
<form action="insert.php" method="post">
<dl>
<dt>Select Course</dt>
<dd><select name="course_id">
<?php // CREATE dropdown menu
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {?>
<option value="<?php echo $row["course_id"]; ?>"><?php echo $row["course_name"]; ?></option>
<?php }
?>
</select>
</dd>
</dl>
</form>
I was able to come up with another solution as well:
Once the foreach loop was removed, I tried cleaning up the code some... I'm not sure if this is uncommon or 'bad' style, but it does work.
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {
$course_id = $row['course_id'];
$course_name = $row['course_name'];
echo "<option value=\"$course_id\">$course_id $course_name</option>";
Results in: LO-COMP-8001 Intro to HTML as a single option, plus all my other courses in the database.

Fetch comma seperated link list from MySQL - PHP

id name
1 Abc
2 Bcd
3 Def
4 Efg
5 Xyz
Now i am using mysqli prepared statements to fetch my data
<?php
if ($stmt1 = $mysqli->prepare("SELECT name FROM TABLE")) {
$stmt1->execute();
$res1 = $stmt1->get_result();
while($rwv=mysqli_fetch_array($res1)) {
?>
<?php echo $rwv['name']; ?>
<?php } } $stmt1->close(); ?>
Output i get on using above query:
AbcBcddefEfgXyz
Desired Ouput:
Abc, Bcd, Def, Efg, Xyz
I searched on Google and found solutions to use GROUP_CONCAT func. I used GROUP_CONCAT function but then it shows an error on a href that variable "name" is undefined. How i can get the desired output ?? Thanks in advance...
Please check below example, You can use GROUP_CONCAT in mysql.
"SELECT GROUP_CONCAT(CONCAT('<','a href=\"pagename.php?name=', title, '\"\>', title, '<', '/a>')) as name FROM YOUR_TABLE"
The above example fetch the records with comma separated value from mysql with column name name, So you will not get the error as you mentioned above. May be it will help you.
The other answer is just terrible.
We are trying desperately to make PHP users to refrain from intermixing PHP with HTML, but that answer is lowering a problem a level deeper, intermixing HTML with SQL.
While using separation from HTML you can make your code real neat
<?php
$data = $mysqli->query("SELECT name FROM users")->fetch_all(MYSQLI_ASSOC);
$last = count($data) - 1;
?>
<? foreach ($data as $i => $row) { ?>
<?= $row['name'] ?><!--
--><?php if ($i != $last) { ?>,<?php } ?>
<?php } ?>
Another way to go that you can use with your existing code is: (added 3 lines to the code, all with comment //Added this
<?php
if ($stmt1 = $mysqli->prepare("SELECT name FROM TABLE")) {
$stmt1->execute();
$res1 = $stmt1->get_result();
$hasGonePastFirst = false; //Added this
while($rwv=mysqli_fetch_array($res1)) {
if($hasGonePastFirst) echo ' , '; //Added this
else $hasGonePastFirst = true; //Added this
?>
<?php echo $rwv['name']; ?>
<?php
} } $stmt1->close(); ?>

Php while codes show just 1 row

I'm using these codes.
$blog = mysql_query("SELECT * FROM blog ORDER BY id");
while($sutun = mysql_fetch_array($blog)) {
$fake = $sutun["date"];
echo "$fake";
}
When i use echo"$fake"; I can see all of my rows. But when I use <?php echo "$fake" ?> , It shows just 1 row for me.
I want to all of my rows while I'm using <?php echo "$fake" ?>.
Beacuse The echo"$fake"; in with in a loop it will echo at every iteration thats why you can see all your rows but <?php echo"$fake"; ?> executed when the loop is done so only the last row will be echoed;
You should seperate your logic like
<?php
$blog = mysql_query("SELECT * FROM blog ORDER BY id");
while($sutun = mysql_fetch_array($blog)) {
$fake = $sutun["date"];
?>
<?php
echo $fake;
}

How to auto increment serial number of result on page like 1,2,3

I want to auto increment serial number of result fetched from query on page like 1,2,3......
Below is my piece of code:
<td><font size="-1"><?php echo $++i ?> </font></td><td><font size="-1">
Now <?php echo $++i ?> fetches actual row id which is 17,18 of a table.
i want just simple value 1,2,3...so on
Inside your table row you can echo incremented variable (simple counter):
<?php $i = 0; ?>
...
<tr><td><?php echo ++$i;?></td><td><font size="-1"><?php echo $row['id']; ?> </font></td></tr>
...
You could start your own variable and increment it, but it might be easier for you to instead subtract to get the value you want. change you code from:
<?php echo $row['id']-16; ?>
to
<?php echo $row['id']-16; ?>
an example you can run to show this works:
<?php $row = array('id' => '17'); ?>
<?php for($row['id']; $row['id']<40; $row['id']++){ ?>
<?php echo $row['id']-16; ?>
<?php } ?>

Categories