I am creating a class for connecting to my database but I keep getting an message saying my sql syntax has an error, when echoing the query i get SELECT id, username from :table where :row = :value
and it seems fine with no errors.
<?php
class db{
protected $datab;
public function __construct($username, $password, $host, $dbname, $options){
try {
$this->datab = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex) {
die("Failed to connect to the database: " . $ex->getMessage());
}
$this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
public function select($array, $table, $row, $value){
$query = "SELECT";
foreach($array as $val) {
if ($val === end($array)){
$query.= " ".$val;
}else{
$query.= " ".$val.",";
}
}
$query.=" FROM :table WHERE :row = :value";
$query_params = array(
':table' => $table,
':row' => $row,
':value' => $value
);
echo $query; // SELECT id, username from :table where :row = :value
try{
$stmt = $this->datab->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
return $row;
}
}
$kit = new db("root", "", "localhost", "kit", array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$kit->select(array("id", "username"), "user", "username", "yusaf");
?>
Error message:
Failed to run query: SQLSTATE[42000]: 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 ''user' where 'username' = 'yusaf'' at line 1
EDIT
I got a downvote please comment why you have given me this. I guess I should have mentioned this is only for learning purposes I'm not actually going to use this class in an application it's pointless.