Can I include one pdo connection - php

Im a just moving to using PDO for my development and I see in most tutorials that the connection is opend for each db query like in Jeffery Ways example below
$id = 5;
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Can I still do a connection in an external file and include it at the top of my page like with previous procedural coding and then do my queries below in the page?
<?php include 'includes/db.php';?>

You probably misunderstood what he says. To open one connection and use it throughout the whole application is not that something you "can" but actually you should.
So - yes, you are doing it right.
Also note that this thing with
try {
...
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
that Jeffery taught you is wrong. Never use a try catch to echo an error message. PHP will handle it better
So, your code should be like this
include 'includes/db.php';
$stmt = $pdo->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
while db.php has to contain something like this
<?php
$dsn = "mysql:host=localhost;dbname=test;charset=utf8mb4";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $username, $password, $opt);
Also note that when using this PDO object, you have to be aware of the variable scope.
Further reading: https://phpdelusions.net/pdo

The short answer is yes,
if you are farmilier with OOPHP it might be worth creating a wrapper class to help with running queries but just creating the connection in a file and including it will get the job done
in the above example you can put
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
into your db.php and the run the queries
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
wherever you need.
it may also be worth mentioning that you dont have to use prepared statements with PDO which can speed things up in coding however if you wish to do that i would highly recomend a database wrapper class
non prepared statement
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$query = "
SELECT
col_1,
col_2
FROM
table_1
WHERE
col_3 = " . $conn->quote($_POST['input']); //the quotr is important, it escapes dangerous characters to prevent SQL injection
//this will run the query for an insert this is all thats needed
$statement = $conn->query($query);
//fetch single col
$col = $statement->fetch(PDO::FETCH_ASSOC);
//fetch all collums
$cols = $statement->fetchAll(PDO::FETCH_ASSOC);
the advantage of this way is that you can build up the query SQL in a more simple to follow manner, i should not that i havent tested this code but in theory it should be fine as this is how i do database handling
Edit:
Your Common Sense brings up a good point about the echo 'ERROR: ' . $e->getMessage(); being a bad idea and this is a prime example of why you should NEVER blindly copy and paste code

Yes, example:
db.php
<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
FROM:
http://www.php.net/manual/en/pdo.error-handling.php
Then just include db.php. I name my connection $PDO, seems more implicit, especially when you are building a prepared statement on that.

Related

Separate connection from PDO

I am new to PDO. I try to understand.
What is the best way to separate the connection from the rest with PDO?
For instance. I have this code that works well:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully <br>";
$sql = "SELECT podcast, text
FROM bookmarks
WHERE data = :data";
$statement = $conn->prepare($sql);
$data = 1;
$statement->bindValue(':data', $data);
$statement->execute();
echo $statement->rowCount() . " records SELECTED successfully <br>";
$rows = $statement->fetchAll();
foreach($rows as $row){
echo $row['podcast'] . '<br>';
echo $row['text'] . '<br>';
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
It could be useful to have the connection in a separate file. I tried that and it works well but I am not sure if it is the best way to do it. Is it ok to have the try-catch only with the connection?
index.php:
include("includes/connetion.php")
$sql = "SELECT podcast, text
FROM bookmarks
WHERE data = :data";
$statement = $conn->prepare($sql);
$data = 1;
$statement->bindValue(':data', $data);
$statement->execute();
echo $statement->rowCount() . " records SELECTED successfully <br>";
$rows = $statement->fetchAll();
foreach($rows as $row){
echo $row['podcast'] . '<br>';
echo $row['text'] . '<br>';
}
$conn = null;
connection.php:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// $conn = new PDO("sqlite:/Applications/MAMP/db/sqlite/podcast", $username, $password); //Lite
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully <br>";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
I tried that and it works well but I am not sure if it is the best way to do it.
As long as your code is a usual spaghetti as shown above, it's all right with include.
Is it ok to have the try-catch only with the connection?
quite contrary, there shouldn't be a try catch with the connection as well:
"Catch an exception only if you have a handling scenario other than just reporting it. Otherwise just let it bubble up to a site-wide handler (note that you don't have to write one, there is a basic built-in handler in PHP, which is quite good)."
If you are trying to catch possible exception you have to do it everywhere you communicate with database. So you have to wrap try-catch also around code which ask database for some data.
Another step is to separate concepts of getting data from database representing them (sending them to output as you do it). You can check some MVC concept - how to do it.

How do I make an if statement which checks if a variable is in the mysql database

try {
$conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM us WHERE username='$suser' and password='$shashpass'"; // SQL Query
$conn->exec($sql);
Thats some of my code, how do I make it so if suser and shashpass are correct it can
execute some code, else it executes other code
This won't work either
<?php
try
{
$conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $con->prepare("SELECT * FROM us WHERE username=:user and password=:password"); $query->bindParam(':user',$suser);
$query->bindParam(':password',$shashpass); $query->execute(); $result = $query->fetch(PDO::FETCH_ASSOC);
if(!empty($result)){ } else { } }
catch(PDOException $e) {
echo $sql . $e->getMessage();
}
You don't pre-hash the password when verifying it. Instead you SELECT the password hash from that user (if it exists) and then use password_verify() to verify that it's correct based on the plain text password sent by the web form.
$stmt = $conn->prepare("SELECT password FROM us WHERE username=?");
$stmt->execute([$suser]);
if ($user = $stmt->fetch(PDO::FETCH_ASSOC)) {
if (password_verify($plain_text_password, $user['password'])) {
// Successful login
}
else {
// Valid user, but invalid password
}
}
else {
// User doesn't exist
}
If you're not using password_hash() and password_verify(), You're Doing It Wrong™.
you are using PDO in wrong way , you need to use prepared statements in PDO to be secure from mysql injections, try to use the code below:
try {
$conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $con->prepare("SELECT * FROM us WHERE username=:user and password=:password");
$query->bindParam(':user',$suser);
$query->bindParam(':password',$shashpass);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
if(!empty($result)){
// user is in database
} else {
// user is not there
}
exec will return the number of affected rows so:
$rows = $conn->exec($sql);
if($rows > 0){
//suser and shashpass are correct
}else{
//suser and shashpass are incorrect
}
//Use below PDO code
<?php
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
$sql = "SELECT * FROM us WHERE username='$suser' and password='$shashpass'";
// SQL Query
$conn->exec($sql);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>

Fetching PDO - $handler vs $stmt?

I am VERY new to PHP / PDO, so please be gentle...
I am trying to enter code into my database and then fetch it into a webpage. I am able to do the first but am having difficulty displaying it. I am wondering if it's because i'm trying to combine $stmt and $handler together?
This is my code for entering the information into the database:
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO survey (storename, receipt, date_visit)
VALUES (:storename, :receipt, :date_visit)");
$stmt->bindParam(':storename', $storename);
$stmt->bindParam(':receipt', $receipt);
$stmt->bindParam(':date_visit', $date_visit);
// insert a row
$storename = $_POST['storename'];
$receipt = $_POST['receipt'];
$date_visit = $_POST['date_visit'];
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
It works perfectly.
This is my code for fetching information from my database.
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=test', 'test', 'test');
$handler->setAttribute(PDO::ATRR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
class SurveyEntry {
public $id, $storename, $receipt, $date_visited,
$entry;
public function __construct() {
$this->entry = "{$this->storename} posted: {$this->receipt}";
}
}
$query = $handler->query('SELECT * FROM survey');
$query->setFetchMode(PDO::FETCH_CLASS, 'SurveyEntry');
while($r = $query->fetch()) {
echo $r->entry, '<br>';
}
?>
I can confirm that it connects correctly, but I can't get it to display any information. I'm wondering if it's something to do with the difference in $stmt and $handler that i'm using? I've been following tutorials online and have quite possibly mixed 2 tutorials together to try and achieve what i'm looking for.
UPDATE:
I managed to get it to work by updating how I called from the database:
$host = "localhost";
$dbname = "test";
$user = "test";
$password = "test";
$handler = new PDO( "mysql:dbname=$dbname;host=$host" , $user , $password );
Figured it out - I had 'ATRR_ERRMODE' instead of 'ATTR_ERRMODE' (typo)
how are you?
You should try to fix it:
1- Two different connections:
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$handler = new PDO('mysql:host=localhost;dbname=test', 'test', 'test');

Changing from mysqli to PDO did not work?

I previously used mysqli and now i would like to use PDO instead but I did not echo any result from my database. I have read so many articles about PDO tutorial but they teach different things. I tried to pick piece by piece and came up with this code, but i did not echo any result from my database or throw any error.
try{
$stmt = $conn->query("SELECT * FROM memberpost ORDER BY poststart DESC LIMIT $start_from,$num_rec_per_page");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt->fetch();
if(count($row)>0){
while($row = $stmt->fetch()) {
echo $row['title']."<br>";
}
}
else{
echo "NO result found";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Here is my database connect code:
try {
$conn = new PDO('mysql:host=localhost;dbname=mydatabase;charset=utf8', $username, $password); //new PDO
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Edit your database connection code to this:
<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
And try this code in your .php file :
$sth = $conn->prepare(SELECT * FROM memberpost)
$sth->execute();
$red = $sth->fetchAll();
print_r($red);
I found this on the internet, it might help:
// defining query
$sql = 'SELECT name, surname, zip FROM table';
// showing results
foreach($db->query($sql) as $row){
echo $row['name']. '<br>';
echo $row['surname']. '<br>';
echo $row['zip']. '<br>';
}
Source (ita): http://www.mrwebmaster.it/php/guida-utilizzo-pdo_7594_4.html

Want to delete a row from a table using php pdo

I want to delete a row from a table using php pdo.I am using the following code,
$dsn = 'mysql:host=127.0.0.1;dbname=as1';
$user = 'root';
$password = '';
try {
// Connect and create the PDO object
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo 'Database connection failed - ';
echo $e->getMessage();
exit;
}
$sql1="DELETE FROM photo WHERE id=?";
$q1=array($result);
try {
$stmt1 = $pdo->prepare($sql1);
$stmt1->execute($q1);
$stmt1->setFetchMode(PDO::FETCH_BOTH);
$result1= $stmt1->fetchColumn();
}
catch (PDOException $e) {
die("Failed to run query: " . $e->getMessage());
}
But my datas in a table are not deleting ...It shows failed to run query..
You did not provide a value for ?
$stmt1->execute($q); // Where is $q defined?
Should be something like
$q=array(1);
$stmt1->execute($q);

Categories