Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MySQLi prepared statements - SELECT

Tags:

php

mysqli

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?

like image 520
Eakethet Avatar asked Mar 20 '23 10:03

Eakethet


1 Answers

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 http://it1.php.net/manual/en/mysqli-result.fetch-assoc.php) and then get only the field value pointed by $what

like image 66
Paolo Avatar answered Mar 22 '23 01:03

Paolo