How to connect properly to MySQL database?

Thiluxan :

I'm trying to connect MySQL to my PHP program. The database was properly connected as it doesn't show any error messages with database connection. But when I'm trying to fetch data from the table, the output doesn't show any outputs. It leaves a blank screen. No error messages are also shown. It displays only 'Database connected successfully'.

    <?php 
define('user', 'root');
define('pwd', '');

$dsn = "mysql:host=localhost:3307;db_name=mydatabase";
try{
    $db = new PDO($dsn,user,pwd);
    echo "Database connected successfully";
    $query = "SELECT * FROM student_detail";
    $statementss = $db->prepare($query);
    $statementss->execute();
    $detail = $statementss->fetchAll();
    foreach ($detail as $student) {
        echo $student['Name']." ";
        echo $student['Address']." ";
        echo $student['Age']." ";
        echo $student['Phone']." ";
        echo "<br>";
    }
    $statementss->closeCursor();

}
catch(Exception $e){
    echo $e->getMessage()."<br>";
}
?>
Dharman :

It's unclear whether you actually have any values in the database, but I will now explain how to connect properly to MySQL database using PDO extension in PHP.

There are 3 things you need to do always when opening DB connection:

  1. Enable error reporting. In PDO you can pass $options array containing \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION to enable error reporting.
  2. Set the correct charset. The most common one is utf8mb4. If you are using utf8 I strongly recommend to make the switch as soon as possible.
  3. Create an instance of PDO.

You should only catch exceptions if you know why you need to do it. Don't wrap everything in try-catch; this is a terrible idea. Especially don't ever catch exceptions just to echo the error message out; this is pointless. You can however wrap the new PDO(); line in try-catch and then throw a custom exception in catch block if you are paranoid about security.

The name of key-value pair for database name is dbname instead of db_name. Also, when specifying port, there is a separate key-value pair in DSN dedicated to it. It could be that your issue was because you were connecting on the wrong port or because the db_name was not recognized.

Your fixed code would look like this:

<?php

define('user', 'root');
define('pwd', '');

$dsn = "mysql:host=localhost;port=3307;dbname=mydatabase;charset=utf8mb4";
$db = new \PDO($dsn, user, pwd, [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false,
]);

echo "Database connected successfully";

$query = "SELECT * FROM student_detail";
$statementss = $db->prepare($query);
$statementss->execute();
$detail = $statementss->fetchAll();

foreach ($detail as $student) {
    echo $student['Name']." ";
    echo $student['Address']." ";
    echo $student['Age']." ";
    echo $student['Phone']." ";
    echo "<br>";
}

Unrelated issues:

  1. You probably don't need closeCursor(). I am not sure what the idea of it was in your example.
  2. It's always good idea to separate your database logic from your HTML. Use classes or functions to encapsulate the DB operations and then have the foreach loop in HTML.
  3. The convention for constant naming in PHP is that they should be written in uppercase, so it is easier to distinguish them.
  4. It's recommended to switch off emulated prepared statements. You can add \PDO::ATTR_EMULATE_PREPARES => false to the $options array.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=298217&siteId=1