I am having an issue with the object creation with PDO.
Below is my code and it gets hangs at "new PDO". and there is no response and no error.
<?php
$user = "root";
$password = "password";
$database = "test";
$table = "test";
try {
$db = new PDO("mysql:host=localhost;dbname=$database", $user, $password);
var_dump($db);
echo "<h2>TODO</h2><ol>";
foreach($db->query("SELECT content FROM $table") as $row) {
echo "<li>" . $row['content'] . "</li>";
}
echo "</ol>";
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
Can someone help me understand why I am getting this issue.
I am running ubuntu 20.04
In PHP Version blow 8 the default PDO-Errormode is ERRMODE_SILENT. Try to set Errmode to ERRMODE_EXCEPTION.
$db = new PDO("mysql:host=localhost;dbname=$database", $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
Related
Hello could anyone help me please with db connection, im using xampp, phpmyadmin, when i open the browser, DBConnection.class.php it shows blank and db doesnt work, thanks
<?php
class DBConnection{
public static function DbConn(){
$servername = "mysql:host=localhost;dbname=test";
$username = "root";
$password = "";
try{
$conn = new PDO($servername, $username, $password);
return $conn;
echo"Connection succesful :)";
}
catch (PDOException $e) {
echo "Connection failed :( :" . $e->getMessage();
}
}
}
?>
Modified Code. Try this:
class DBConnection{
public static function DbConn(){
$servername = "mysql:host=localhost;dbname=test";
$username = "root";
$password = "";
try{
$conn = new PDO($servername, $username, $password);
return "Connection succesfull :)";
//return $conn;
}
catch (PDOException $e) {
echo "Connection failed :( :" . $e->getMessage();
}
}
}
and then call like this
$Connection = new DBConnection();
print_r($Connection->DbConn());
This is my code:
<?php
//Connect to DB
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
function printResult($conn) {
$sql = 'SELECT name FROM info';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
}
}
?>
But, when I run it, nothing gets printed. What's wrong?
Yes, my table is not empty. I am 100% able select & print data using MySQLi Object-oriented, but not working with PDO. What's wrong in my code?
Call the function
<?php
//Connect to DB
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
function printResult($conn) {
$sql = 'SELECT name FROM info';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
}
}
//call the function here
printResult($conn);
?>
To run a function you must call it.
<?php
//Connect to DB
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
// and if this fails there is no point continuing so add an exit
exit;
}
function printResult($conn) {
$sql = 'SELECT name FROM info';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
}
}
printResult($conn); // call the function
?>
You don't call function printResult from anywhere.
Add to your code printResult($conn);
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.
I get this error on booking.php
bookings'unsuccessful entry: No database selected
I also have a db_connect.php
<?php
$dbname = "mysql:dbname=lessonbookings";
try{
$db = new PDO($dbname,'root','');
}catch(PDOException $ex){
echo 'connection error: ' . $ex->getMessage();
}
?>
)
I get this error message and I double/tripled checked my database name. I cant figure out what is wrong.
You have an extra space before lesson bookings
Try this one:
$host = "your host name"; //Add your Host Name (probably localhost)
$db = "lesson bookings";
$user = "root";
$password = "";
try{
$db = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
I've recently tried to convert my procedural MySQL queries to PDO statements. I've copied the following code from php official documentation and added my parameters to it. It is not showing any results in the page.
<?php
$dsn = 'mysql:host=localhost;dbname=database';
$user = 'user';
$pass = 'pass';
try {
$dbh = new PDO($dsn , $user, $pass);
$dbh = null;
} catch (PDOException $e) {
print "An error has occurred. Please contact support. <br/>" . $e->getMessage() . "<br/>";
die();
}
$value = 'user1';
$stmt = $dbh->prepare("SELECT * FROM table where username = ?");
if ($stmt->execute(array($value))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
?>
Try this:-
<?php
$dsn = 'mysql:host=localhost;dbname=databasename';
$user = 'user';
$pass = 'password';
try {
$dbh = new PDO($dsn , $user, $pass);
} catch (PDOException $e) {
print "An error has occurred. Please contact support. <br/>" .
$e->getMessage() . "<br/>";
die();
}
$value = 'user1';
$stmt = $dbh->prepare("SELECT * FROM table where column= ?");
if ($stmt->execute(array($value))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>