How do you use PHP variables in mysqli query on the SELECT side?

I have the following query:

$mysqli -> prepare('SELECT $whatever FROM county_rates WHERE `id`=?')

For some reason, this does not work. I know that the $whatever is correct because I'm defining it right before the statement. When I replace the $whatever with the actual column name it works, but with the variable it does not.

I have also tried:

$mysqli -> prepare('SELECT ? FROM county_rates WHERE `id`=?')

and then defining the ? in the bind_param and all this returns is the column name itself.

Answers


you need to use double quotes to have the variable expanded

$mysqli -> prepare("SELECT $whatever FROM county_rates WHERE `id`=?")

currently you are looking for $whatever not the contents of the variable.

you should familiarise yourself with this section of the manual: Strings


Try this code, I tried it by myself and I hope it useful for you

<?php
$hostname = "your host";
$username = "username";
$password = "password";
$database = "database name";
$mysqli = new mysqli($hostname, $username, $password, $database);

//test connection
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

//declaring variable
$sql='name';

$prev=$mysqli->prepare("SELECT $sql FROM cs_product WHERE id=?");
    /*The types of data that can be bound [in bind_param()] are:
   i – integer
   d – double
   s – string
   b – blob
    */
$prev->bind_param('i',$_GET['pid']);
$prev->execute();
$prev->bind_result($name);
$prev->fetch();
$prev->close();

//showing the result
echo $name;

?>

Need Your Help

Closure doesn't work

ruby closures

If a block is a closure, why does this code does not work, and how to make it work?