0

Having some difficulty echoing the results of a query using PHP. I'm referencing this answer to build my script. I believe I have everything copied (minus var names and the query) but I'm not getting the right result. When I query the database within MySQL Workbench via select name from restaurant, it returns the 4 restaurant names in the table as expected. My guess is that I'm not referencing the results correctly as the query does return 4 results.

PHP CODE:

// connect
$conn = mysqli_connect($hostname, $q_user, $q_pass, $db);    // these vars are initialized prior
// set params and query
$query = "select ? from restaurant";
$p1 = "name";
if($sql = $conn->prepare($query)) {
    // bind and execute
    $sql->bind_param("s", $p1);
    $sql->execute();
    $sql->store_result();
    $num_results = $sql->num_rows;
    echo "{$num_results} results<br>";
    $sql->bind_result($r_name);
    // populate page with all results
    while($sql->fetch()){
        echo "${r_name}<br>";
    }
    // free results and close query
    $sql->free_result();
    $sql->close();
}
//disconnet
mysqli_close($conn);

RESULT (body only)

<body>
4 reults
<br>
name
<br>
name
<br>
name
<br>
name
<br>
</body>
Josh Brown
  • 47
  • 1
  • 9
  • `select ? from restaurant` makes very little sense. Why do you select a literal value from a table? It's the same as `SELECT ?` without the `FROM` as the value will be the same from every table. – Dharman Jan 17 '22 at 17:03
  • As far as I know you cannot use `?` to pass column names to the db server, only values. This is also discussed in [this question](https://stackoverflow.com/questions/3135973/variable-column-names-using-prepared-statements). By the way, look closely at the answer you're referring to, it also passes in values, not names. – fvu Jan 17 '22 at 17:03
  • Thanks for the clarification! When I saw the set up, I thought it allowed me to use `?` anywhere in the query, not only values. I was only trying this to learn how to do prepared statements so I was just experimenting with it, still new to MySQL so knowing this helps a lot! – Josh Brown Jan 17 '22 at 17:28
  • If you are only starting to learn PHP then you should learn PDO instead of mysqli. PDO is much easier and more suitable for beginners. Start here https://phpdelusions.net/pdo & https://websitebeaver.com/php-pdo-prepared-statements-to-prevent-sql-injection – Dharman Jan 17 '22 at 17:33

0 Answers0