How to use a $result variable with table object in

2019-07-28 23:11发布

问题:

I am trying to make this code work, but it only works until the second echo statement echo "Finished 2";.

<?php
if (count($_GET) > 0){
$sql = "SELECT * FROM winery WHERE winery_name='".$_GET['winery_name']."'";
echo "Finished 1";
$result = $db->query($sql);
echo "Finished 2";
$sql = "SELECT * FROM".$result."WHERE wine_type='".$_GET['wine_type']."'";
echo "Finished 3";
$result = $db->query($sql);
echo "Finished 4";
$sql = "SELECT * FROM".$result.", wine_variety WHERE wine_id=wine_variety.wine_id";
echo "Finished 5";
$result = $db->query($sql);
echo "Finished 6";
$sql = "SELECT * FROM".$result."WHERE variety_id='".$_GET['grape_variety']."'";
echo "Finished 7";
$result = $db->query($sql);
echo "Finished all queries";

}
?>

The problem from my understanding is that sql doesn't recognize $result as a table, but $result stores the return table from my query. How can I make SQL use the return table from $result in a new query?

回答1:

I think from your winery table you are fetching other table name???

If so you need to fetch row from the $result and then get appropriate column from winery table (i.e. column with other table name).

BTW best option would be joining two tables.

One more point where I think you are making mistake is

$sql = "SELECT * FROM".$result."WHERE wine_type='".$_GET['wine_type']."'";

should be

$sql = "SELECT * FROM ".$result." WHERE wine_type='".$_GET['wine_type']."'";

space between FROM & double quote and between double quote and WHERE

To get winery_id from winary_name you can write your HTML form like

<select name="winary_id">
    <option value="Winary ID HERE">Winary Name Here</option> // you can generate your dynamic options like this which will return id instead of name
</select>