PHP PDO passing variables in functions
Im just making the move to PDO as suggested by a bunch of people on here :)
Here is the code that currently works
<?php
$table = "tbl_staff";
$all = $database->find_by_sql('SELECT * FROM tbl_staff'); echo '<pre>';
echo "<b> Find by SQL</b></br>";
print_r($all);
echo '</pre>';
?>
public function find_by_sql($sql) {
$this->query($sql);
$rows = $this->resultset();
return $rows;
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function execute(){
return $this->stmt->execute();
}
So that all works as expected and returns all the tbl_staff details.
However i want to change the table name to pull the name from a variable
like this
<?php
$table = "tbl_staff";
$all = $database->find_by_sql('SELECT * FROM "'.$table.'"'); echo '<pre>';
echo "<b> Find all rows </b></br>";
print_r($all);
echo '</pre>';
?>
That returns a server error of Syntax error or access violation: 1064 You
have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near '"tbl_staff"'
at line 1'
Ive tried just $table, '$table' and {$table} but it seems to read the line
literally as $table and not replace with the variable. is there a
different rule with PDO statements? Im a bit lost with getting to grips
with PDO so apologies if this is a simple one
No comments:
Post a Comment