我正在创建一个用于连接到数据库的类,但不断收到一条消息,说我的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
我很不高兴,请评论一下你为什么给我这个。我想我应该提到这只是出于学习目的,我实际上并不会在没有意义的应用程序中使用此类。
您不能使用:table或:row作为替换值,您必须知道表和列的名称。
SELECT ID,来自:table的用户名,其中:row =:value
应该
SELECT ID,表名中的用户名,其中columnname =:value
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句