我正在创建一个用于连接到我的数据库的类,但我不断收到一条消息,说我的 sql 语法有错误,当回显我得到的查询时SELECT id, username from :table where :row = :value
,它似乎没有错误。
<?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");
?>
错误信息:
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
编辑
我投了反对票,请评论你为什么给我这个。我想我应该提到这只是为了学习目的,我实际上不会在应用程序中使用这个类,它没有意义。