I am trying to create a PDO class and I get the error:
PHP Fatal error: Call to a member function execute() on a non-object on line 39
to call this class I create a new database object that connects with no problems then I do this:
$newDailyTotal = array(
array('date',time()),
array('cash',300)
);
$db->insert('dailyTotals',$newDailyTotal);
it echos out INSERT INTO dailyTotals(date,cash) values (?,?)
so that seems fine too.
thanks for all the help.
<?
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);
}
}
?>
Variables are spelled differently…. long day? 😉