Display value of row with same id in PHP

mysql, php, string

Solution

You could use

SELECT order_id, GROUP_CONCAT(product_name SEPARATOR ', ') AS product_names FROM orders GROUP BY order_id;

Example in PHP:

<?php
    $db_server = 'localhost';
    $db_user = 'user';
    $db_pass = 'pass';
    $db_name = 'database';

    $con = mysql_connect($db_server, $db_user, $db_pass)
        or die('Could not connect to the server!');

    mysql_select_db($db_name)
        or die('Could not select a database.');


    $sql = "SELECT order_id, GROUP_CONCAT(product_name SEPARATOR ', ')";
    $sql .= " AS product_names FROM orders GROUP BY order_id";

    $result = mysql_query($sql)
        or die('A error occured: ' . mysql_error());
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
    <title>test</title>
</head>

<body>
<h1>orders</h1>
<table>
   <tr><th>orders_id</th><th>product_names</th></tr>
<?php
while ($row = mysql_fetch_assoc($result)) {
    printf("<tr><td>%d</td><td>%s</td></tr>\n", $row['order_id'],
                                                $row['product_names']);
}
?>
</table>
</body>
</html>

Problem

I am trying to make a system which automatically prints out orders, and I am facing a problem right now. I am trying to make a string in a format which the printer is understanding, and right now, i need to gather the data from database before sending. Now my problem is that in some cases the order_id is the same. Here is an example: ``` +----------+----------------------+ | order_id | product_name | +----------+----------------------+ | 1 | Pizza with cheese | +----------+----------------------+ | 1 | Coca-Cola Zero | +----------+----------------------+ | 2 | Spaghetti | +----------+----------------------+ | 3 | Lasagna | +----------+----------------------+ ``` So what i am trying to is gather all the "product_name"'s in one string which have the same "order_id", so it display it as: "Pizza with cheese, Coca-Cola Zero" Is there any way to do that? Thanks in advance. EDIT: I don't know if I mentioned it above clearly, but I want to make a PHP script that are displaying it. Sorry if I am confusing.

Original source