sammyltk sammyltk - 1 year ago 73
MySQL Question

Issue to output mysql result

I create a form to register company and insert into DB. also created a form to insert each company cost and sell price. after all this has been inserted in DB, i try to output it on table but it was showing the company id instead of name... please bellow illustrate better

company DB

|id | company_name |
|1 | Oliva Ltd |
|2 | Bone Mill |

comp_product DB

|id | company_id | cp | sp |
|3 | 2 | 20000 | 18000 |
|4 | 1 | 3000 | 100 |

The help I need is to output all data from comp_product DB by representing the
with their
from company DB.

Ouput Table

| company_id | cp | sp |
| Bone Mill | 20000 | 18000 |
| Oliva Ltd | 3000 | 100 |

i tried bellow code, but i was showing only one row.


$result = mysql_query("SELECT * FROM comp_product ORDER BY id DESC");
while($row = mysql_fetch_array($result))
$result = mysql_query("SELECT * FROM company WHERE id ='".$row['company_id']."'");
while($rowz = mysql_fetch_array($result))
{ $name = $rowz['company_name']; }
<td><?php echo $name ?></td>
<td><?php echo $row['cp'] ?></td>
<td><?php echo $row['cp'] ?></td>

Show can I do this. Thanks for understanding

Answer Source

You need a JOIN query

SELECT `company`.`company_name`, `comp_product`.`cp`, `comp_product`.`sp`
FROM `company`
LEFT JOIN `comp_cp`
ON `company`.`id` = `comp_product`.`company_id`

You do not need two queries, you can just loop through the results of one. If you need to limit this to one company you can add a WHERE clause.

In addition you need to stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download