php - How can I connect a value of one mySQL table to a value of another table? -
i have 2 tables in mysql database:
table "animals":
| animal | name | |:-----------|------------:| | cat | tom | | dog | |
table "orders":
| id | animal | |:-----------|------------:| | 1 | cat | | 2 | dog |
at first select table "orders" following data:
<?php $pdo = database::connect(); $sql = 'select * orders order id asc'; foreach ($pdo->query($sql) $row) { echo ('<td>a:'.$row['id'].'</td>'); echo ('<td>b:'.$row['animal'].'</td>'); echo ('<td>c:'.$row['animal'].'</td>'); } database::disconnect(); ?>
now want check if in mysql table "animal" animal has name. if yes print @ position b name. if there no name print animal:
| a:1 | b:tom | c:cat | | a:2 | b:dog | c:dog |
thank answers! tried work answer of jayo2k. need little change in question, found out did little mistake. here try describe need specific possible:
table "animals":
| name | animal | |:-----------|------------:| | tom | cat | | jerry | dog | | alfred | duck | | sam | | | donald | |
table "orders":
| id | animal | |:-----------|------------:| | 1 | cat | | 2 | dog | | 3 | duck | | 4 | frog | | 5 | pig |
with following code jayo2k...
<?php $pdo = database::connect(); $sql = "select * animals, orders orders.animal = animals.animal"; foreach ($pdo->query($sql) $row) { echo '<tr> '; echo('<td>a:'.$row['id'].' </td>'); echo('<td>a:'.$row['animal'].' </td>'); echo('<td>b:'.$row['name'].' </td>'); echo '</tr> '; } database::disconnect(); ?>
... result:
| a:1 | b:cat | c:tom | | a:2 | b:dog | c:jerry | | a:3 | b:duck | c:alfred |
but need is:
| a:1 | b:cat | c:tom | | a:2 | b:dog | c:jerry | | a:3 | b:duck | c:alfred | | a:4 | b:frog | c:frog | | a:5 | b:pig | c:pig |
you can use left join
, , use if
condition check value not empty, along ifnull
, make null values in columns blank.
select o.id, if(ifnull(a.name, '') = '', a.animal, a.name) name, a.animal orders o left join animals on o.animal = a.animal order o.id desc
Comments
Post a Comment