I'm displaying results from a MySQL table based on matching values in one column. I then need to separate these results based on the data in another column, when that data is different.
Here's a cut down example of the table I'm drawing data from:
customer_id customer_timestamp customer_order customer_email
27 2019-02-23 02:52:41 ABC123456789 admin#admin.com
28 2019-02-23 02:52:41 ABC123456789 admin#admin.com
32 2019-02-26 05:51:41 CBA987654321 admin#admin.com
From the above, I need to return all rows with the same customer_email then separate them by customer_order number.
Can this be achieved through a select statement alone and if so how?
Here's an example of a select statement I'm using which returns all rows with the same email;
$select = "select * from mytable where customer_email='admin#admin.com'";
The data I'm getting from the query is being fetched in an array so I need the array to generate a new loop based on the customer_order column.
I figured it out, might look a bit hacky but it works. I rolled back the idea of initially displaying any order data, now it requires user interaction to select a grouped order number to display details from that specific order.
Code below;
// Retrieve order number/s
$select_order = "select * from mytable where customer_email='admin#admin.com' group by customer_order";
$connect_order = mysqli_query($con, $select_order);
while ($row_order=mysqli_fetch_array($connect_order)) {
$customer_order = $row_order['customer_order'];
echo "
<form method='post'>
<input type='submit' value='$customer_order' name='order_current[]'>
</form>
";
}
// Make each grouped order number a separate query
if (isset($_POST['order_current'])) {
$order_all = $_POST['order_current'];
foreach ($order_all as $order_post) {
// Retrieve selected order details
$select_order = "select * from mytable where customer_email='admin#admin.coml' and customer_order='$order_post'";
$connect_order = mysqli_query($con, $select_order);
while ($row_order=mysqli_fetch_array($connect_order)) {
$name = $row_order['customer_name'];
$amount = $row_order['customer_amount'];
// Display selected order details
echo "
$name<br/>
$amount<br/>
";
}
}
}
Related
I have updated my original post based on what I learned from your comments below. It is a much simpler process than I originally thought.
require '../database.php';
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Orders WHERE id = 430";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
echo 'Order Num: ' . $data['id'] . '<br>';
$sql = "SELECT * FROM Order_items
JOIN Parts ON Parts.id = Order_Items.part_id
WHERE Order_Items.orders_id = 430";
$q = $pdo->prepare($sql);
$q->execute(array($line_item_id));
$data = $q->fetch(PDO::FETCH_ASSOC);
while ($data = $q->fetch(PDO::FETCH_ASSOC))
{
echo '- ' . $data['part_num'] . $data['qty'] . "<br>";
}
Database::disconnect();
Unfortunately, only my first query is producing results. The second query is producing the following ERROR LOG: "Base table or view not found: 1146 Table 'Order_items' doesn't exist" but I am expecting the following results.
Expected Results from Query 1:
Order Num: 430
Expected Results from Query 2:
- Screws 400
- Plates 35
- Clips 37
- Poles 7
- Zip ties 45
Now that I understand where you are coming from, let's explain a couple of things.
1.PDO and mysqli are two ways of accessing the database; they essentially do the same things, but the notation is different.
2.Arrays are variables with multiple "compartments". Most typical array has the compartments identified by a numerical index, like:
$array[0] = 'OR12345'; //order number
$array[1] = '2017-03-15'; //order date
$array[2] = 23; //id of a person/customer placing the order
etc. But this would require us to remember which number index means what. So in PHP there are associative arrays, which allow using text strings as indexes, and are used for fetching SQL query results.
3.The statement
$data = $q->fetch(PDO::FETCH_ASSOC)
or
$row = $result->fetch_assoc()
do exactly the same thing: put a record (row) from a query into an array, using field names as indexes. This way it's easy to use the data, because you can use field names (with a little bit around them) for displaying or manipulating the field values.
4.The
while ($row = $result->fetch_assoc())
does two things. It checks if there is a row still to fetch from the query results. and while there is one - it puts it into the array $row for you to use, and repeats (all the stuff between { and }).
So you fetch the row, display the results in whatever form you want, and then loop to fetch another row. If there are no more rows to fetch - the loop ends.
5.You should avoid using commas in the FROM clause in a query. This notation can be used only if the fields joining the tables are obvious (named the same), but it is bad practice anyway. The joins between tables should be specified explicitly. In the first query you want the header only, and there is no additional table needed in your example, so you should have just
SELECT *
FROM Orders
WHERE Orders.Order_ID = 12345
whereas in the second query I understand you have a table Parts, which contains descriptions of various parts that can be ordered? If so, then the second query should have:
SELECT *
FROM Order_items
JOIN Parts ON Parts.ID = Order_Items.Part_ID
WHEERE Order_Items.Order_ID = 12345
If in your Orders table you had a field for the ID of the supplier Supplier_ID, pointing to a Suppliers table, and an ID of the person placing the order Customer_ID, pointing to a Customers table, then the first query would look like this:
SELECT *
FROM Orders
JOIN Suppliers ON Suppliers.ID = Orders.Supplier_ID
JOIN Customers ON Customers.ID = Orders.Customer_ID
WHERE Orders.Order_ID = 12345
Hope this is enough for you to learn further on your own :).
I am trying to make a select to my table 'detail' where I have 4 registers with id 0,1,2,3 but this only returns the ids 1,2,3. What will be?
$sqls = "
SELECT *
FROM details
WHERE ped = 4500088849";
$results = mysqli_query($conn, $sqls);
while($row = mysqli_fetch_array($results)) {
print $row['ebelp'];
}
My table
Your query is filtering for rows where the column ped contains the value 11.
Using the mysql command line perform the query
SELECT ped, ebelp FROM details;
And review the value in the ped column for register 0, it sounds like it has a value other then 11.
Using the query SELECT * FROM details will get you all rows with all columns from the details table.
I have a query a Wordpress include which does the following:
$sql = "SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = 'merchant_id' LIMIT 6";
$results = $wpdb->get_results($sql);
foreach ($results as $row)
{
echo $row->meta_value . ",";
//sprintf("SELECT * FROM retailers WHERE advertiserId = '%s'", $row->meta_value);
}
//clean all results
$wpdb->flush();
It parses all pages custom fields (merchant ID numbers), and returns any unique distinct values, separated by a comma. This bit works great.
ie: The above may return: 1301,345,723,134,1435
What I also have is a separate MySQL table of about 20 fields, three of which are the MerchantID, programmeName, and commissionMax. Each value from the CSV correlates with the MerchantID in the database.
Regardless of the amount of merchant ID's that appear in the CSV - I need to parse them all, but show the three highest commission rates (commissionMax), as well as the programmeName.
I managed to get connected to my external database and retrieve the appropriate values (using the commented code above) however this showed all of the retailers information.
Any advice?
Use the following query with limit:
SELECT * // select all fields
FROM table_name // from your table
WHERE MerchantID IN (your_ids_here) // IDs received from previous query or wherever
ORDER BY commissionMax DESC // descending sort by commissionMax field
LIMIT 3 // take first 3 results
In my code I make use of this query. I want to include in the presentation the rows that have London in the pou field, and also the rows that the user have not selected any town and are empty.
$sql = "SELECT * FROM table WHERE eidos='online' AND pou='London' order by time asc";
I tried to add OR pou='' without luck. How can I do this?
Try
$sql = "SELECT * FROM table WHERE eidos='online' AND (pou='London' OR pou='') order by time asc";
What I'm basically trying to do is get the the staff table, fetch the id of the names per job title and then hit another table (based on the id fetched) and get the data I'm interested in off.
My approach so far is make a query, go with a while loop to get all the ids of the job title im interested and for every id go with another loop ( connection-query) to subtract more data.
I think my approach is wrong cause im suspicious i could merge those two queries into one not sure how though.
//new db connection here... (1)
$query="SELECT * FROM staff WHERE jobtitle='$forEachJob'";
$result=mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
$idFetched = $row['id'];
//new db connection here... (2)
$nextQuery = "SELECT * FROM schedule WHERE name='$idFetched' ORDER BY Day asc";
$nextResult = mysql_query($nextQuery)
}
You want to do a JOIN in mysql:
SELECT * FROM staff
JOIN schedule ON schedule.name = staff.id
WHERE jobtitle = '$forEachJob'
ORDER BY Day ASC
By the way, avoid using SELECT * and look into a DB wrapper such as PDO to sanitize/prepare your queries.