I have a table like this full of orders, each customer will have multiple orders:
Customer ponumber quantity ..
customer1 234345 56
customer2 343454 34
customer1 w34234 54
customer5 332423 54
I'm trying to loop through each DISTINCT customer and print the corresponding orders with the following code.
<?php
include("php/database_connect.php");
$query = mysql_query("SELECT DISTINCT customer FROM orders");
$customer = mysql_fetch_array($query);
foreach($customer as $customers)
{
echo ' <li><h1>'. $customers . '</h1></li>';
$result = mysql_query("SELECT * FROM orders WHERE misc='new' AND customer='$customers' ORDER BY columnpos ASC ");
while($row = mysql_fetch_array($result))
{
echo'
<li id="id_' . $row['id'] . '">
<div class="card">
<table>
<tr>
<td>' . $row['customer'] . '</td>
<tr>
<td>P/O: ' . $row['ponumber'] . '</td>
</tr>
<tr>
<td>' . $row['partnumber'] . '</td>
</tr>
<tr>
<td><b>' . $row['quantity'] . '</b> x ' . $row['foil'] . '</td>
</tr>
<tr>
<td>' . $row['daterequired'] . '</td>
</tr>
<tr>
<td>' . $row['prep'] . '</td>
</tr>
</table>
<input class="hiddenid" type="hidden" value="' . $row['id'] . '" />
<input class="hiddenquantity" type="hidden" value="' . $row['quantity'] . '" />
<input class="hiddenpartnumber" type="hidden" value="' . $row['partnumber'] . '" />
<input class="hiddenfoil" type="hidden" value="' . $row['foil'] . '" />
</div>
</li>
';
}
}
?>
However the above code currently prints:
customer1 234345
customer1 w34234
customer1 234345
customer1 w34234
which seems odd... its not going through each customer.
any help is greatly appreciated!
Make only one DB query (better performance) but process the results before looping over them:
$result = mysql_query("SELECT * FROM orders WHERE misc='new' ORDER BY customer ASC ");
$ordersByCustomer = array(); // nested array. 1. level: customers, 2. level: orders
while(($row = mysql_fetch_assoc($result))) {
if(!array_key_exists($row['customer'], $ordersByCustomer)) {
$ordersByCustomer[$row['customer']] = array();
}
$ordersByCustomer[$row['customer']][] = $row;
}
foreach($ordersByCustomer as $customer=>$orders) {
echo ' <li><h1>'. $customer . '</h1></li>';
foreach($orders as $order) {
// rest of HTML code
}
}
I also encourage you to use a better separation of HTML and PHP, like so, using the alternative syntax for control structures:
<?php foreach($ordersByCustomer as $customer=>$orders): ?>
<li><h1><?php echo $customer; ?></h1></li>
<?php foreach($orders as $order): ?>
<li id="id_<?php echo $row['id'];?>">
<div class="card">
<table>
<tr><td><?php echo $order['customer']; ?></td></tr>
<!-- and so forth -->
<?php endforeach; ?>
<?php endforeach; ?>
Btw, you are not generating valid HTML. li element must be contained in ul or ol elements.
use
while($customer = mysql_fetch_array($query){
instead of
$customer = mysql_fetch_array($query);
foreach($customer as $customers)
{
Related
I am making a leaderboard with persons out of my database. My website is build in PHP (PDO) the problem is that I cant get the users out of the database to show the correct way under each other.
The function I use to get info out of the database is:
public function get_klanten(){
$getKlant = $this->database->query("SELECT * FROM klanten ORDER BY id ASC LIMIT 1");
$klanten = $this->database->resultset();
return $klanten;
}
How it is now
The problem I get is that it puts every records after each other and not on a new line that why I added LIMIT 1 but I want that the second user in this case Amet also be out of the database.
The HTML with this is a different file and is the code down below.
<thead>
<tr>
<th>#</th>
<th>Lid</th>
<th><span class="glyphicon glyphicon-sort-by-attributes" aria-hidden="true"></span></th>
<th><span class="glyphicon glyphicon-ok" aria-hidden="true"></span></th>
</tr>
</thead>
<tbody>
<tr>
<?php
$klantten = $app->get_klanten();
foreach ($klantten as $klant) {
echo '<td>' . $klant['id'] . ' </td>';
echo '<td>' . $klant['voornaam'] . ' ' . $klant['achternaam'] . ' </td>';
echo '<td>' . $klant['punten'] . ' </td>';
echo '<td>' . $klant['punten'] . ' </td>';
}
?>
</tr>
<tr>
<td>2</td>
<td>amet</td>
<td>456</td>
<td>52</td>
</tr>
BONUS
<div class="col-md-6">
<div class="well dash-box">
<h2><span class="glyphicon glyphicon-list-alt" aria-hidden="true"></span> Stel jezelf voor</h2>
<h5> Laat wetn wie jij en je business zijn</h5>
</div>
</div>
<div class="col-md-6">
<div class="well dash-box">
<h2><span class="glyphicon glyphicon-list-alt" aria-hidden="true"></span> 12</h2>
<?php
$toppics = $app->get_topics();
$i = 0;
foreach ($toppics as $topic) {
echo '' . $topic['onderwerp'] . '';
}
?>
</div>
</div>
Function:
public function get_topics(){
$getTopic = $this->database->query("SELECT * FROM topics ORDER BY id DESC");
$topics = $this->database->resultset();
return $topics;
}
I want this also to be each record in a new block. So each topic is a new block. You can see now 2 blocks I want each block to get a different record out of the database
1: https://i.stack.imgur.com/lH8oz.png
Remove limit 1 from query, then move your TR tag so it's inside your foreach loop.
<?php
$klantten = $app->get_klanten();
foreach ($klantten as $klant) {
echo '<tr>';
echo '<td>' . $klant['id'] . ' </td>';
echo '<td>' . $klant['voornaam'] . ' ' . $klant['achternaam'] . ' </td>';
echo '<td>' . $klant['punten'] . ' </td>';
echo '<td>' . $klant['punten'] . ' </td>';
echo '</tr>';
}
?>
page1, the code, below, works fine and lists recipe names i.e. BBQ Pork etc
<form action="recipe_show.php" method="post">
<?php
$result = mysql_query("SELECT recipe_name FROM recipes ORDER BY recipe_name ASC"); // Run the query
if ($result) { // If it ran OK, display the records
// Table header
echo '<table>
<td align="left"><b>Recipe Name</b></td>
</tr>';
// Fetch and print all the records
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<tr>
<td>'. $row['recipe_name'] .'</td>
</tr>';
}
echo '</table>'; // Close the table
mysql_free_result ($result); // Free up the resources
} else { // If it did not run OK
// Message
echo '<p class="error">The current recipe_name could not be retrieved. We apologize for any inconvenience.</p>';
// Debugging message
echo '<p>' . mysql_error($dbcon) . '<br><br />Query: ' . $q . '</p>';
} // End of if ($result)
mysql_close($dbcon); // Close the database connection.
?></p>
</form>
</div>
When I click the link, from page1, it opens page2. I get the headings but not the data for the BBQ Pork link. Below is the code on page2.
<form action="" method="post">
<?php
$recipe = mysql_real_escape_string($_GET['recipe_name']); //if using mysql
$myresult = "SELECT * FROM recipes WHERE recipe_name = '".$recipe. "'";
$num = mysql_num_rows($myresult);
for ($i = 0; $i < $num; $i++){
$row = mysql_fetch_array($myresult, MYSQL_ASSOC);
$row = (($i % 2) == 0) ? "table_odd_row" : "table_even_row";
echo "<tr row=".$row.">";
}
if ($myresult) { // If it ran OK, display the records
echo '<table>
<td width="250" align="center"><b>Recipe Name</b></td>
<td width="250" align="left"><b>Instructions</b></td>
<td width="250" align="left"><b>Directions</b></td>
<td width="250" align="left"><b>Notes</b></td>
</tr>';
while ($row = mysql_fetch_array($myresult, MYSQL_ASSOC)) {
echo '<tr>
<td align="left">' . $row['recipe_name'] . '</td>
<td align="left">' . $row['ingredients'] . '</td>
<td align="left">' . $row['directions'] . '</td>
<td align="left">' . $row['notes'] . '</td>
</tr>';
}
echo '</table>'; // Close the table
mysql_free_result ($myresult); // Free up the resources
} else {
echo '<p row="error">The current Recipe could not be retrieved. We apologize for any inconvenience.</p>';
echo '<p>' . mysql_error($dbcon) . '<br><br />Query: ' . $q . '</p>';
} ($myresult)
mysql_close($dbcon); // Close the database connection.
?>
Hope I have correctly set this out? Many thanks, in advance, for help and guidence
so I'm using this API (http://phptopdf.com/) to convert some php text to PDF.
But I'm getting this error :-
Everything works fine until the first name, email.
But, when I try to link in the orders, everything goes haywire.
Parse error: syntax error, unexpected T_WHILE in /home/a/public_html/pdf/packing_slip.php on line 124
Code
<?php
session_start();
include_once('phpToPDF.php') ;
include '../dbconnector.php';
include_once '../inc/inc.functions.php';
include '../dbpdo.php';
//require 'fbconfig.php';
if(!isset($_SESSION['email']))
{
//not logged in.
header('Location:http://macbuyback.co.uk/register');
exit();
}
if((isset($_SESSION['logged']) && $_SESSION['logged']=1) || $user)
{
//load the record for last orders
$user_email = $_SESSION['email'];
$date=date('Y-m-d');
try
{
$statement = $conn->prepare("SELECT * From sales where email =? and orderDate = ?");
$statement->execute(array(
$user_email,
$date));
$statement->setFetchMode(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
//now get the customer details
try
{
$statement2 = $conn->prepare("SELECT * From users where email = ?");
$statement2->execute(array(
$user_email));
$statement2->setFetchMode(PDO::FETCH_ASSOC);
$user_info = $statement2->fetch();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
// Assign html code into php variable:-
$html = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Company</title>
<style type="text/css">
<!--
body {
font-family:Tahoma;
}
img {
border:0;
}
#page {
width:800px;
margin:0 auto;
padding:15px;
}
#logo {
float:left;
margin:0;
}
#address {
height:181px;
margin-left:250px;
}
table {
width:100%;
}
td {
padding:5px;
}
tr.odd {
background:#e1ffe1;
}
-->
</style>
</head>
<body>
<div id="page">
<div id="logo">
<img src="http://www.domain.co.uk/pdf/logo.png">
</div><!--end logo-->
<div id="address">
<p>Company<br />
info#company
<br /><br />
Created on ' . date("Y-m-d") . '
echo ' . $a . '
</p>
</div><!--end address-->
<div id="content">
<p>
<strong>Customer Details</strong><br />
Name: ' . $user_info['firstname'] . '<br />
Email: ' . $_SESSION['email'] . '<br />
<hr> ' . $a=1 .'
<table>
<tr>
<td><strong>Serial</strong></td>
<td><strong>Product Name</strong></td>
<td><strong>Amount</strong></td>
<td><strong>Pickup Date</strong></td>
</tr>
' . while($row = $statement->fetch()){ . '
' if(($a%2) == 0){ . '
<tr class="odd">
<td> ' . $a . '</td>
<td> ' . getProductNameFromId($row['pid']) . '</td>
<td>' . $row['amount'] . '</td>
<td>' . $row['shipmentdate'] . '</td>
</tr>
' . $a++ }else{. '
<tr class="even">
<td> ' . $a . '</td>
<td> ' . getProductNameFromId($row['pid']) . '</td>
<td>' . $row['amount'] . '</td>
<td>' . $row['shipmentdate'] . '</td>
</tr>
' . $a++ }. '
' . } . '
</table>
<hr>
<p>
Thank you for your order! This transaction will appear on your billing statement as "Your Company".<br />
If you have any questions, please feel free to contact us at youremail#somewhere.com.
</p>
<hr>
<p>
<center><small>This communication is for the exclusive use of the addressee and may contain proprietary, confidential or privileged information. If you are not the intended recipient any use, copying, disclosure, dissemination or distribution is strictly prohibited.
<br /><br />
© Your Company All Rights Reserved
</small></center>
</p>
</div><!--end content-->
</div><!--end page-->
</body>
</html>';
phptopdf_html($html,'pdf', 'sample.pdf');
echo "<a href='pdf/sample.pdf'>Download PDF</a>";
}//login check
else
{
header('Location:http://domain.co.uk/register');
exit();
}
?>
What might be wrong ?
Any suggestions are welcome.
Your while loop cannot be used inside a string concatenation.
$html ='.....
</tr>';
while($row = $statement->fetch()){
if(($a%2) == 0){
$html .= '<tr class="odd">
<td> ' . $a . '</td>
<td> ' . getProductNameFromId($row['pid']) . '</td>
<td>' . $row['amount'] . '</td>
<td>' . $row['shipmentdate'] . '</td>
</tr>';
$a++; }else{
$html .= '<tr class="even">
<td> ' . $a . '</td>
<td> ' . getProductNameFromId($row['pid']) . '</td>
<td>' . $row['amount'] . '</td>
<td>' . $row['shipmentdate'] . '</td>
</tr>';
$a++; }
}
$html .= ' </table>
.....';
Here is the table below that I'm trying to delete rows out of:
<form method="POST" >
<table class="sortable">
<thead>
<tr>
<th id="makehead">Make </th>
<th id="modelhead">Model </th>
<th id="idhead">Delete </th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
foreach ($carArray as $k => $carInfo) {
$i++;
echo '<tr>';
if ($i % 2) {
echo '<td class="make">' . $carInfo['make'] . '</td>
<td class="model">' . $carInfo['model'] . '</td>
<td class="id"><input type="checkbox" name="id" value="' . $carInfo['id'] . '">' . $carInfo['id'] . '</td>';
} else {
echo '<td class="makelight">' . $carInfo['make'] . '</td>
<td class="modellight">' . $carInfo['model'] . '</td>
<td class="idlight"><input type="checkbox" name="id" value="' . $carInfo['id'] . '">' . $carInfo['id'] . '</td>';
}
}
?>
</tr>
</table>
</tbody>
<td>
<input Onclick="return ConfirmDelete();" name="delete" type="submit" id="delete" value="Delete"></input>
</td>
</table></form>
As you can see i'm using checkboxes to tick each row then the delete button will have a confirm message then should delete but it doesn't here is my if statement:
if ($_REQUEST['delete']) {
$dbid = $_REQUEST['id'];
$db->setdbid($dbid);
So when this wasn't working I had a look on here and on other questions people said I need a setter function so i did this: EDIT: this is my class file.
public function setdbid($dbid){
$this->dbid=$dbid;
}
for this main function to delete things:
public function delete($dbid) {
try {
$sql = "DELETE FROM cars WHERE id = '$dbid'";
$this->db->exec($sql);
echo "Car has been deleted.";
} catch (PDOException $e) {
echo $e->getMessage();
}
}
So that's all the relevant code I think, please help me if you can.
You just have to replace some piece of code in PHP :
if ($_REQUEST['delete']) {
$dbid = $_REQUEST['id'];
$db->delete($dbid); //Assuming delete is well a $db method, else replace it by the correct delete call
}
As you are using checkboxes with the same name, you have to change it so it's an array (and this way you'll be able to delete multiple rows at once) :
<td class="id"><input type="checkbox" name="ids[]" value="' . $carInfo['id'] . '">' . $carInfo['id'] . '</td>';
Then in your php code, treat this data as such :
if ($_REQUEST['delete']) {
foreach($_REQUEST['ids'] as $id){
$xxx->delete(intval($id)); //convert to integer to avoid sql injection.
}
}
Note that you don't need to set $db->setdbid since you pass that id as a parameter of your delete method.
I have put together a basic order list for admin users in php for checking order contents placed by logged in users.
The aim of this script is to retrieve the order details (item, quantity, price) as well as the user’s first name and surname (where ‘Order for:’ is).
The script below does everything ok in that it retrieves the order (and orders if there are more than one) and it’s/their item, quantity and price.
However, it doesn’t display the user’s name and surname.
I know the problem is that where I am trying to display the name is outside the while loop but Im a little stuck in where it should sit. Any suggestions? Code is below:
<?php
$page_title = 'View Individual Order';
include ('includes/header.html');
// Check for a valid user ID, through GET or POST.
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) )
{ // Accessed through view_users.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) )
{ // Form has been submitted.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<h1 id="mainhead">Page Error</h1>
<p class="error">This page has been accessed in error.</p><p><br /><br /></p>';
include ('./includes/header.html');
exit();
}
?>
<h1>Order Details</h1>
<?php
require_once ('database.php'); // Connect to the db.
// Retrieve the user's, order and product information.
$query = "SELECT us.users_id, us.users_sales_id, us.users_first_name, us.users_surname, us.users_dealer_name,
ord.order_id, ord.users_id, ord.total, ord.order_date,
oc.oc_id, oc.order_id, oc.products_id, oc.quantity, oc.price,
prd.products_id, prd.products_name, prd.price
FROM users AS us, orders AS ord, order_contents AS oc, products AS prd
WHERE ord.order_id=$id
AND us.users_id = ord.users_id
AND ord.order_id = oc.order_id
AND oc.products_id = prd.products_id
";
$result = mysql_query ($query) or die(mysql_error());
if (mysql_num_rows($result)) { // Valid user ID, show the form.
echo '<p>Order for:<strong>' . $row[2] . ' ' . $row[3] . ' </strong> </p>
<table border="0" style="font-size:11px;" cellspacing="1" cellpadding="5">
<tr class="top">
<td align="left"><b>Product</b></td>
<td align="center"><b>Price</b></td>
<td align="center"><b>Qty</b></td>
</tr>';
$bg = '#dddddd'; // Set the background color.
while($row = mysql_fetch_array($result, MYSQL_NUM)) { // WHILE loop start
$bg = ($bg=='#eaeced' ? '#dddddd' : '#eaeced');
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="left">' . $row[15] . '</td>
<td align="center">' . $row[13] . ' pts</td>
<td align="center">' . $row[12] . '</td>
</tr>';
echo '';
}// end of WHILE loop
echo '</table>
<p> Here:</p>
<br><br>
<p> << Back to Orders</p>
<p> </p>
<p> </p>
<p> </p>
';
} else { // Not a valid user ID.
echo '<h1 id="mainhead">Page Error</h1>
<p class="error">This page has been accessed in error.</p><p><br /><br /></p>';
}
mysql_close(); // Close the database connection.
?>
<p>Footer here</p>
<?php
include ('./includes/footer_admin_user.html'); // Include the HTML footer.
?>
One way you could do it is grab the row first, and then use a do/while loop instead of just a basic while loop. Like this:
if (mysql_num_rows($result)) { // Valid user ID, show the form.
/*********** I added this line ***********/
$row = mysql_fetch_array($result, MYSQL_NUM);
echo '<p>Order for:<strong>' . $row[2] . ' ' . $row[3] . ' </strong> </p>
<table border="0" style="font-size:11px;" cellspacing="1" cellpadding="5">
<tr class="top">
<td align="left"><b>Product</b></td>
<td align="center"><b>Price</b></td>
<td align="center"><b>Qty</b></td>
</tr>';
$bg = '#dddddd'; // Set the background color.
/*********** I changed this from a while loop to a do-while loop ***********/
do { // WHILE loop start
$bg = ($bg=='#eaeced' ? '#dddddd' : '#eaeced');
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="left">' . $row[15] . '</td>
<td align="center">' . $row[13] . ' pts</td>
<td align="center">' . $row[12] . '</td>
</tr>';
echo '';
} while($row = mysql_fetch_array($result, MYSQL_NUM)); // end of WHILE loop
It looks like the problem is when you're trying to display the user's name:
echo '<p>Order for:<strong>'.$row[2].' '.$row[3]
The $row variable doesn't exist yet. Not seeing your database or the result from your database query, my guess is that the user's name is repeated next to every single item in their order, so it might be as simple as just starting the WHILE loop, and checking to see if you've printed their name yet:
$lastUser = NULL;
while($row = mysql_fetch_array($result, MYSQL_NUM)) {
if ($row[0] !== $lastUser) {
if (isset($lastUser)) {
// finish up the report for the previous user
}
// echo the stuff for the current user's name
$lastUser = $row[0];
}
// go on echo-ing their order information
}
// after the while loop is over,
// close up the last user's report
But like I said, this is just a guess, and might be totally off.
The problem is that you tried to access $row[2] and $row[3] before mysql_fetch_array(). Since you are already echo'ing HTML tags, why don't you "buffer" your output first like this?:
while($row = mysql_fetch_array($result, MYSQL_NUM)) {
$bg = ($bg=='#eaeced' ? '#dddddd' : '#eaeced');
$order = '<tr bgcolor="' . $bg . '">
<td align="left">' . $row[15] . '</td>
<td align="center">' . $row[13] . ' pts</td>
<td align="center">' . $row[12] . '</td>
</tr>';
$orders[$row[2] . " " . $row[3]][] .= $order;
}
Then do a second foreach loop for the $orders
foreach($orders as $name => $orderList)
{
echo "Order for: $name";
echo "<table ...>";
foreach($orderList as $order)
{
echo $order;
}
echo "</table>";
}