0

Hi,

I'm working on a small project and I like the Query to check something for me. However for that I need to select something which is also needed in the WHERE clause.

// Prepare Query
$sql = "SELECT ? FROM permissions WHERE (req = ? AND single_delete = '1')";
$stmt = $db->prepare($sql);

// Bind Parameters and execute.
$stmt->bind_param("si", $action, $user['permissions']);
$stmt->execute();

// Store result and make it a variable.
$stmt->store_result();
$permissioncount = $stmt->num_rows;

return $permissioncount;

Like this it's working. It returns the correct count. However as soon as I change single_delete to the variable $action, it will return 0. The variable $action contains single_delete. My Question is, why isn't it possible or what am I doing wrong?

The code

    // Prepare Query
$sql = "SELECT ? FROM permissions WHERE (req = ? AND ? = '1')";
$stmt = $db->prepare($sql);

// Bind Parameters and execute.
$stmt->bind_param("sis", $action, $user['permissions'], $action);
$stmt->execute();

// Store result and make it a variable.
$stmt->store_result();
$permissioncount = $stmt->num_rows;

return $permissioncount;
Dharman
  • 30,962
  • 25
  • 85
  • 135
Synthiatic
  • 261
  • 1
  • 16
  • You cannot use bound parameters for the table or column names in a prepared query – RiggsFolly Feb 27 '17 at 12:08
  • Thanks. Didn't know that. What is the best way to get the same effect of the code I need? – Synthiatic Feb 27 '17 at 12:15
  • You will have to concatenate the names when you build `$sql` like this `$sql = "SELECT $action FROM permissions WHERE (req = ? AND $action = '1')"` but that risks allowing an SQL Injection – RiggsFolly Feb 27 '17 at 12:18
  • Possible duplicate of [Can I parameterize the table name in a prepared statement?](https://stackoverflow.com/q/11312737/1839439) – Dharman Jul 28 '19 at 22:50

0 Answers0