dynamo
dynamo

Reputation: 382

PHP Dropdown mySQL two tables

Edited version with working code:

Table schema:

category (catid, catname)

product (productid, catid, productname)

if(isset($_POST['submit'])); {

if(isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0) {
//get the id
$productid = (int) $_GET['id'];
} else {
    echo 'error'; }

$sql = $link->prepare("SELECT p.productid, p.catid pid, p.productname, c.catid cid, c.catname FROM product p
JOIN category c
WHERE p.productid = $productid");
$sql-> execute();
$result = $sql-> fetchall(PDO::FETCH_ASSOC);
    $option = '';
foreach ($result as $row) {
    $pid = $row['pid'];
    $productname = $row['productname'];
    $catid = $row['cid'];
    $catname = $row['catname'];
    $option .= '<option name="'.$catname.'" value="'.$catid.'" '.($pid==$catid ? 'selected="selected"' : '').'>'.$catname.'</option>'."\r\n";
}

then in page:

<select name="xxx">
<? echo $option ?>
</select>

Upvotes: 2

Views: 388

Answers (1)

Arun Jain
Arun Jain

Reputation: 5464

In your foreach loop you are executing only a query not iterating the result set data. If it is not, then please explain your query() method.

Upvotes: 1

Related Questions