Daniel Wohlgemuth Daniel Wohlgemuth - 1 month ago 6
PHP Question

SELECT ? FROM table WHERE id = ? not working correctly

I've got a little question. I want to get specific information out of my database via mysqli query:

public function get_searchorder_single_information($soid, $information) {

global $mysqli;

$stmt = $mysqli->prepare("SELECT ? FROM pr_hr_searchorders WHERE id = ?");
$stmt->bind_param('si', $information, $soid);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
echo $result;

$stmt->close();

}


In my example,
$information
is set 'job', but it can have other values, too (e.g. 'salary'). When I try to use my query with this variable, echo outputs just 'job' and not the value that is saved in my database. When I write 'job' instead of the '?', echo outputs the correct value.

So now I could make a function for each information I search, but this would end in spaghetti code. So I ask you if there is any possibility to use my search query like above with correct output. How would I do that?

Thanks in advance and sorry for my bad english writing.

Fky Fky
Answer

Read documentation : http://php.net/manual/en/mysqli.prepare.php

The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value. However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement, or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. It's not allowed to compare marker with NULL by ? IS NULL too. In general, parameters are legal only in Data Manipulation Language (DML) statements, and not in Data Definition Language (DDL) statements.

Modify your code :

$stmt= $mysqli->prepare("SELECT $information FROM pr_hr_searchorders WHERE id = ?");
$stmt->bind_param('i', $soid);