Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
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.
$host = '127.0.0.1';
$db = 'YourDatabase';
$user = 'YourDBUser';
$pass = 'YourDBPass';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dbh = new PDO($dsn, $user, $pass, $opt);
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.
<?php
class Connection
{
private $host = "127.0.0.1";
private $dbName = "YourDB";
private $user = "YourUser";
private $pass = "YourPass";
private $charset = 'utf8';
private $dbh;
private $error;
private $stmt;
//connection
public function __construct()
{
$dsn = "mysql:host=" . $this->host . ";dbname=" . $this->dbName . ";charset=" . $this->charset;
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
);
try {
// setup connection
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
//catch any errors
catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
//prepare statement
public function insertUserValues($query)
{
$this->stmt = $this->dbh->prepare($query);
}
//bind values
public function bind($param, $value, $type = null)
{
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
//actual value binding
$this->stmt->bindValue($param, $value, $type);
}
//execute statement
public function run()
{
return $this->stmt->execute();
}
}
?>
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
<?php
include'pdoClass.php';
$users = new Connection();
$users->insertUserValues('INSERT INTO test (name, age, description) VALUES(?,?,?)');
$users->bind(1, 'User'); //bind each value
$users->bind(2, 391); // bind
$users->bind(3, 'This is a value');
if($database->run()){
echo "record inserted";
}
?>
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 :
public function SingleRow(){
$this->run();
return $this->stmt->fetch();
}
see we use fetch();
to only fetch one row. most people when they fetch results will fetch them like this fetch(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 use fetch()
;
to display those results on your index.php file this is how you will do :
$users->insertUserValues("SELECT name, age, description FROM test WHERE name = :name");
$users->bind(':name','joe');
$row = $users->SingleRow();
echo '<pre>';
print_r($row);
echo '</pre>';
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.
public function All(){
$this->run();
return $this->stmt->fetchall();
}
You see the difference now we use fetchall()
because we want all the results.
$users->insertUserValues("SELECT * FROM test");
$row = $users->All();
echo '<pre>';
print_r($row);
echo '</pre>';