I'm making a web application for a restaurant kind of type. The idea is to administrate the orders and customers.
For selecting one of the orders and showing more specific data about it, i've got this PHP script. As you can see i'm using prepared statements to prevent SQL injection.
try {
$connection = new PDO('mysql:host=localhost;dbname=broodjes-service;charset=utf8mb4', 'root', 'password');
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!empty($_GET['order_id'])) {
$order_id = $_GET['order_id'];
$order_data = $connection->prepare("SELECT c.first_name, c.last_name, c.email_adress, c.customer_info, o.order_info, o.total_price, o.location, o.created FROM customers AS c LEFT JOIN orders AS o ON c.id = o.customer_id WHERE o.id = :order_id LIMIT 1");
$order_data->bindParam(":order_id", $order_id, PDO::PARAM_INT);
$order_data->execute();
$query = "SELECT `products`.`name`, `orders-items`.`quantity` FROM `orders-items`" . "INNER JOIN `products` ON `orders-items`.`products_id` = `products`.`id`" . "WHERE order_id = :ordero_id LIMIT 1";
$order_items = $connection->prepare($query);
$order_items->bindParam(":ordero_id", $order_id, PDO::PARAM_INT);
$order_items->execute();
$orderObject = array();
$orderObject['header'] = $order_data->fetch();
$orderObject['items'] = array();
while ($orderedItem = $order_items->fetch()) {
$orderObject['items'][] = $orderedItem;
}
header('Content-type: application/json');
echo json_encode($orderObject);
$connection = null;
}
} catch (PDOException $e) {
echo $e->getMessage();
die();
}
The parameters for the 2 queries are both the same. But I don't know how to use only one line for them.
- The first query is for selecting the specific data about the order.
- The second query is for selecting the items inside the order.
Both queries should be run, to get all results.
Problems
- It's messy that I actually have 2 queries.
- It's messy that I'm using 2 lines for the same parameter
Explanation; why there are 2 queries
Whenever I use one query like this:
SELECT c.first_name,
c.last_name,
c.email_adress,
c.customer_info,
o.order_info,
o.total_price,
o.location,
o.created,
p.name,
ot.quantity
FROM customers AS c
LEFT JOIN orders AS o ON c.id = o.customer_id
LEFT JOIN `orders-items` AS ot ON o.id = ot.order_id
LEFT JOIN `products` AS p ON ot.products_id = p.id
WHERE order_id = :order_id;
I get 3 times the results of the specific data from the customer. Then I don't know how to get back the orders-items
separately. Also, whenever there are no results, I have no idea how to 'not select them' within MySQL.
Also, when using that query, when a customer doesn't have any orders_items
no result is given.