I have a little problem here.I am new to OOP, so the question might sound stupid, but I couldn't find any helpful information.
I am trying to login to the database and put the user's entered values inside of it and I want to ask you, in which place should I write PDO prepare and execute statements? I know they're needed, but I have no idea how to write it corretly...Besides that, I also got an error "Object of class PDO could not be converted to string on line 24". Thank you for any help, here's my code:
<?php
class Connection {
public $connection;
public $dbHost = 'localhost';
public $dbName = 'employees';
public $charset = 'charset=utf8';
public $dbUser = 'root';
public $dbPassword = '';
public function __construct() {
try {
$this->connection = new PDO ("mysql:host=$this->dbHost;$this->dbName;$this->dbUser;
$this->dbPassword");
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo "There is something wrong with the database".$e->getMessage();
}
}
function insertUserValues($tableName, $data) {
$query = "INSERT INTO ".$tableName."(";
$query .= implode (",",array_keys($data)).') VALUES (';
$query .= "'" . implode ("','",array_values($data))."')";
}
}
$users = new Connection();
?>
I'm not really good with explanations bru, but I just see that there's no answer after a long time. I have created a basic class for you to insert values using PDO, I hope it will point you to the correct direction, I will also share some useful links for you.
First the connect.
I can see you have done the connection already in your class, but below is the proper best pdo connection.
that is how you set up proper PDO connection. dns stands for data source name Reference of the above https://phpdelusions.net/pdo#dsn this guy explains it better. everything you need to know.
Now how do you put that connection all together with your class?
well I will create a file collect pdoClass.php and work from that class.
basically that's all you need to setup the database and the function to insert in your db, I have tried to comment some sections.
Now to use this class create index.php or what ever you like. then include the class
Done, if you have any question or like me to explain anything, feel free to comment below I will try my best to assist u.
Edit : if you need to fetch the results, you can also make a new function in the class,
Single row :
see we use
fetch();
to only fetch one row. most people when they fetch results will fetch them like thisfetch(PDO::FETCH_ASSOC)
but because we did a proper connection and defined our default fetch mode in the connection we don't need all that we can just usefetch()
;to display those results on your index.php file this is how you will do :
this will display joe's result as an array.
to get all the results from our db
we do another function to display all results.
You see the difference now we use
fetchall()
because we want all the results.