简体   繁体   中英

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.

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;

?>

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