php pdo类无法运行执行

时间:2012-02-17 16:18:14

标签: php class object pdo execute

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

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

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

$newDailyTotal = array(
    array('date',time()),
    array('cash',300)
);

$db->insert('dailyTotals',$newDailyTotal);

它回显INSERT INTO dailyTotals(日期,现金)值(?,?)

所以这看起来也很好。 感谢所有的帮助。

<?

class Database {

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); 
}

}

&GT;

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

date是保留字,您需要向其添加反引号

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

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

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

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