简体   繁体   中英

How to use a $result variable with table object in SQL query using mySQLi

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?

在此处输入图片说明

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 (ie 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM