Reputation: 682
I have problems with my SELECT syntax. 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 echo "name" instead of result from DB. How to solve it?
Upvotes: 4
Views: 5222
Reputation: 15827
Placeholder ?
can be used in prepared statement only in substitution of values, not for field names, table names or statement.
You're trying to use it for a field name.
You can build up your query string
$stmt = $this->con->prepare("SELECT " . $what . " FROM `shop_items` WHERE `id` = ?");
but you must be sure you can trust what's inside $what
in order to avoid sql injection.
Otherwise you may get all fields
$stmt = $this->con->prepare("SELECT * FROM `shop_items` WHERE `id` = ?");
Fetch results in an associative array (see https://www.php.net/manual/en/mysqli-result.fetch-assoc.php) and then get only the field value pointed by $what
Upvotes: 5
Reputation: 44
It looks like you use question mark (?) after SELECT. It should be * symbol where you can select it all from 'shop_items'. You can try again with that.
Upvotes: 2