Hi, I'm new to PHP and I'm having trouble getting a prepared statement to work properly using a "dynamic" sort clause. I'm trying to create a generic function that accepts sortOrder and sortDirection as parameters. It works fine if I only use a single parameter (order by ?) but when I add the second, it breaks.
How do you specify the sort direction using a prepared statement in mysqi/php?
Here's what I'm trying to do:
public function __construct()
{
$this->init();
}
private function init() {
$this->conn = new mysqli("localhost","my_user","my_pass","my_db");
if($this->conn) {
$this->sqlGetAllCmds = "select id,url,type,name,label from commands order by ? ?";
$this->getCmdsStmt = $this->conn->prepare($this->sqlGetAllCmds);
}
else {
echo "Error: Database connection failed: " . mysql_error();
}
}
public function getAllCommands($sortOrder = "id", $sortDirection = "asc") {
$cmds = array();
if($this->getCmdsStmt != FALSE) {
$this->getCmdsStmt->bind_param('ss',$sortOrder,$sortDirection); // <= Error occurs here!
....
return $cmds;
}
When I try to run this, I get:
Call to a member function bind_param() on a non-object
If I remove the second parameter ($sortDirection) and manually set it to either ASC or DESC, it works fine. If I make the direction the sole parameter, that fails with the same error so apparently that's the part that can't be parameterized.
How do you make the direction dynamic?
Thanks!