PHP MySQLi prepared statements - SELECT

I have problems with SELECT syntax. The code:

$stmt = $this->con->prepare("SELECT ? FROM `shop_items` WHERE `id` = ?");

$stmt->bind_param("si", $what, $itemsId);

$stmt->execute();

$stmt->bind_result($res);

$stmt->fetch();

echo $res;

When I want to select "name", it will echo "name" instead of the result from the database. How to solve it?

+4
source share
2 answers

It looks like you are using a question mark (?) After SELECT. It must be a * character, in which you can select everything from "shop_items". You can try again with this.

+2
source

A placeholder ?can only be used in a prepared statement when replacing values, and not for field names, table names, or statement names.

You are trying to use it for a field name.

You can create a query string

$stmt = $this->con->prepare("SELECT " . $what . " FROM `shop_items` WHERE `id` = ?");

, , $what, sql.

$stmt = $this->con->prepare("SELECT * FROM `shop_items` WHERE `id` = ?");

(. http://it1.php.net/manual/en/mysqli-result.fetch-assoc.php), , $what

+5

Source: https://habr.com/ru/post/1542969/


All Articles