php-pdo类无法运行execute


php pdo class cannot run execute

我正在尝试创建一个PDO类,但我得到了错误:

PHP致命错误:在第39行的非对象上调用成员函数execute()

为了调用这个类,我创建了一个连接起来没有问题的新数据库对象,然后我这样做:

$newDailyTotal = array(
    array('date',time()),
    array('cash',300)
);
$db->insert('dailyTotals',$newDailyTotal);

它回应了INSERT INTO每日总计(日期,现金)值(?,?)

所以这看起来也不错。谢谢你的帮助。

<?

类数据库{

private $DBH;

//connects to the database
function __construct($host,$dbname,$user,$pass) {    
    try {  
        $this->DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);  
        $this->DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); 
    }  
        catch(PDOException $e) {  
        echo $e->getMessage();  
    }
}
//inserts into the database
//$tableName name of the table to insert the info into
//$items is a multidimensional array of array(column name, value)
public function insert($tableName,$items){
    $values = array();
    $sql = "INSERT INTO $tableName(";
    $valuePlaceHolder = ''; // holds the question marks at the end of the PDO sql string
    foreach($items as $item){
        $sql .= $item[0] . ',';
        array_push($values, $item[1]);
        $valuePlaceHolder .= '?,';
    }
    // remove the last comma from the sql statement
    $sql = substr($sql,0,-1);
    $valuePlaceHolder  = substr($valuePlaceHolder, 0, -1);
    $sql .= ") values ($valuePlaceHolder)";
    echo $sql;
    $SHT = $this->DBH->prepare($sql);
    $STH->execute($values); 
}

}

?>

   $SHT = $this->DBH->prepare($sql);
   $STH->execute($values); 

变量拼写不同。。。。漫长的一天?;-)

date是一个保留字,您需要向它添加反标记

INSERT INTO dailyTotals(date,cash) values (?,?)

INSERT INTO dailyTotals(`date`,`cash`) values (?,?)

您需要将循环中的sql .= ...更改为

$sql .= '`' . $item[0] . '`,';