In my opinion i have a weird problem. The part below works fine
$sql = "
UPDATE
".$table[0]."
SET
p_title = '".$_POST['p_title']."',
p_date = '".$_POST['p_date']."'
WHERE
p_id = '".$_POST['p_id']."'
";
if(!$db->exec($sql)){
echo($defaults->throwError('MySql error',$sql,implode(":",$db->errorInfo())));
}else{
$defaults->writeLog($table,$db->lastInsertId(),'update');
}
But when i try the code below i get an ‘Fatal error: Call to a member function exec() on a non-object in’
class Defaults{
[..]
public function query($sql){
if(!$db->exec($sql)){
echo($defaults->throwError('MySql error',$sql,implode(":",$db->errorInfo())));
}else{
$defaults->writeLog($table,$db->lastInsertId(),'update');
}
}
[..]
}
and then on my page
$defaults = new Defaults();
$defaults->query("
UPDATE
".$table[0]."
SET
p_title = '".$_POST['p_title']."',
p_date = '".$_POST['p_date']."'
WHERE
p_id = '".$_POST['p_id']."'
");
How come?
Ah, it was about the $db in the class. However, when i do something like
public function query($sql){
$db = new PDO($dbdata->hostname,$dbdata->username,$dbdata->password);
if(!$db->exec($sql)){
echo($defaults->throwError('MySql error',$sql,implode(":",$db->errorInfo())));
}else{
$defaults->writeLog($table,$db->lastInsertId(),'update');
}
}
I get a nasty
Fatal error: Uncaught exception 'PDOException'
with message 'invalid data source name'
in /class.defaults.php:8
Stack trace:
#0 /class.defaults.php(8): PDO->__construct('', NULL, NULL)
#1 /class.form.php(269): Defaults->query('?????????UPDATE...')
#2 /module.projectbeheer.edit.php(25): Form->proceed('update', 'p_id', 'rows', Array, Array, '')
#3 /class.content.php(16): include_once('/path/')
#4 /administratie.php(72): Content->write('/BraamsArchief/...')
#5 {main} thrown in /class.defaults.php on line 8
You must provide $db either as a global or as a class property. Otherwise, you cannot access it in the method scope.
So either:
or else you have to set a class property (e.g. $this->db) with your database connection object and access it using $this->db in your method.
Note that if you use the
globalsolution, you will need to ensure that the variable is always called $db when it is initially defined. Otherwise, your method may not be able to find it and you will get the same error.