Wednesday, October 19, 2016

Tutorial to connect MySQL database using PDO

Here i will show you how to connect with mysql database using PDO in four simple steps:-

1. Connect to database: create object of class PDO and pass $host(hostname/servername), $dbname(database name), $username (database username) and $passowrd (database user password).

$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);

2. cool.. now we will create a select query and execute the query using query() method of pdo class/object.

$sql = 'SELECT lastname, firstname, course FROM students ORDER BY lastname';
$q = $pdo->query($sql);

The query() method of the PDO object returns a PDOStatement object, or false on failure.

3. Next, set the PDO::FETCH_ASSOC fetch mode for the PDOStatement object by using the setFetchMode() method.
 The PDO::FETCH_ASSOC mode instructs the fetch() method to return a result set as an array indexed by column name.

$q->setFetchMode(PDO::FETCH_ASSOC);

4. Now we will fetch row one by one from result set ($q) using fetch() method of PDOStatement object.

       while ($r = $q->fetch()):
<?php echo htmlspecialchars($r['lastname'])
            <?php echo htmlspecialchars($r['firstname']);
            <?php echo htmlspecialchars($r['course']);        
        endwhile;

 ======================================================================


Putting it all together.


<?php

    $host = 'localhost';
    $dbname = 'classicmodels';
    $username = 'root';
    $password = '';

try
{
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $sql = 'SELECT lastname,firstname,course from students ORDER BY lastname';    
    $q = $pdo->query($sql);
    $q->setFetchMode(PDO::FETCH_ASSOC);
}
catch (PDOException $e)
{
    die("Could not connect to the database $dbname :" . $e->getMessage());
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>PHP MySQL Query Data Demo</title>
        <link href="css/bootstrap.min.css" rel="stylesheet">
        <link href="css/style.css" rel="stylesheet">
    </head>
    <body>
        <div id="container">
            <h1>Employees</h1>
            <table class="table table-bordered table-condensed">
                <thead>
                    <tr>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Job Title</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while ($row = $q->fetch()): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($row['lastname']) ?></td>
                            <td><?php echo htmlspecialchars($row['firstname']); ?></td>
                            <td><?php echo htmlspecialchars($row['course']); ?></td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
    </body>
</div>
</html>

Database connection in PHP

Database connection in PHP (How to store data in Mysql database using php).

There are (more than) three popular ways to use MySQL from PHP.
  1. (DEPRECATED) The mysql functions are procedural and use manual escaping.
  2. MySQLi is a replacement for the mysql functions, with object-oriented and procedural versions. It has support for prepared statements.
  3. PDO (PHP Data Objects) is a general database abstraction layer with support for MySQL among many other databases. It provides prepared statements, and significant flexibility in how data is returned.

I would recommend using PDO with prepared statements. It is a well-designed API and will let you more easily move to another database (including any that supports ODBC) if necessary.

PDO is a database access tool in PHP which enables uniform access across multiple databases. It does not support syntaxes specific to databases, but it permits relatively seamless switching between different platforms and databases, which can simply be done by changing the connection string.
The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions. Note that you cannot perform any database functions using the PDO extension by itself; you must use a database-specific PDO driver to access a database server.

PDO provides a data-access abstraction layer, which means that, regardless of which database you're using, you use the same functions to issue queries and fetch data. The PDO extension has the capability to access any database which the PDO driver has been written for. There are many PDO drivers available, a few of which include PDO drivers meant to access Free TDS, Sybase, Microsoft SQL Server, IBM DB2, Firebird/Interbase 6, Oracle Call Interface and PostgreSQL databases, among many more.

PDO ships with PHP 5.1, and is available as a PECL extension for PHP 5.0; PDO requires the new OO features in the core of PHP 5, and so will not run with earlier versions of PHP.