im new here and im also pretty new to php and OOP so if i dont ask the right question also tell me ;p
im trying to make a class that handles all the queries from and to the database. I want to make this class as reusable as plossible so i dont have to keep writing selects and insert statements in all my methods and functions.
my question is: is it plossible to call on an method with parameters and then have those parameters finish the query for me ?
this is what i had come up with so far:
Database connection class:
class Database {
private $host;
private $user;
private $pass;
private $dbname;
private $charset;
public function connect() {
$this->host = 'localhost:3306';
$this->user = 'root';
$this->pass = '';
$this->dbname = 'Testdb';
$this->charset = 'utf8mb4';
try {
$dsn = 'mysql:host='.$this->host.';dbname='.$this->dbname.';charset='.$this->charset;
$pdo = new PDO($dsn, $this->user, $this->pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch (PDOException $e) {
echo "Connection failed:".$e->getMessage();
}
}
}
this is my query's class:
class QueryDatabase extends Database {
public function getData($tablename, $selector, $value) {
if (!isset($selector)){
echo 'Something went wrong!';
} else if ($selector == ''){
$stmt = $this->connect()->query("SELECT * FROM $tablename");
while ($row = $stmt->fetch()){
return $row;
}
}else {
$stmt = $this->connect()->query("SELECT * FROM $tablename where $selector = $value");
while ($row = $stmt->fetch()){
return $row;
}
}
}
public function setData($tablename, $colums, $data) {
if (!isset($tablename) or !isset($data)) {
echo 'Something went wrong!';
} else {
$sql = "INSERT INTO $tablename ($colums) VALUES ($data)";
$q = $this->connect()->prepare($sql);
$q->execute();
}
}
protected function addData() {
}
protected function delData() {
}
}
and this is what i mean with the parameters for example:
$test = new QueryDatabase;
$test->setData('contact_form_messages', 'u_id, name, email, subject, message, date', ' , Kees, Kees@gmail.com, Test, Hopefully it works, ');
i get this error message :
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' Kees, Kees@gmail.com, Test, Hopelijk werkt hij, )' at line 1 in D:\webProjects\project\classes\querydatabase.class.php:31
Stack trace: #0 D:\webProjects\project\classes\querydatabase.class.php(31): PDOStatement->execute() #1 D:\webProjects\project\includes\header.inc.php(5):
QueryDatabase->setData('contact_form_me...', 'u_id, name, ema...', ' , Kees, Kees@g...') #2 D:\webProjects\project\contact.php(1): include('D:\\webProjects\\...') #3 {main} thrown in D:\webProjects\project\classes\querydatabase.class.php on line 31
if you have any suggestions i'd be happy to hear them!
thanks a lot!
Floris