PDO_MYSQL is a driver that allows us to establish a connection from PHP to a MySQL database.
In this article, we will build an example step by step that will show how to connect a MySQL database from PHP using PDO_MYSQL.
In the example, we will cover the following points:
- Establish a connection to a MySQL database
- Run a query to retrieve the rows of a table
- Show the query results
First, let’s create a database in MySQL with an Orders table that has the following structure and data:
CREATE DATABASE IF NOT EXISTS `mydatabase` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; |
Script 1. Creation of database to use in the example
Establish a connection to a MySQL database with PDO_MYSQL
Opening a connection with PDO_MYSQL is really simple. We only have to use the connection parameters that we normally use in the following structure:
<?php |
Script 2. Opening connection to the database with PDO_MYSQL
Run a query to retrieve the rows of a table
To execute a query, we first build a text string that contains the command, then we can execute it with the “query” function.
$sql = 'SELECT id, processed, total, paid FROM orders ORDER BY id'; |
Script 3. Executing a query
Show the query results
To show the results, we are going to use a table. We will fill the rows of the table through a loop.
<table> |
Script 4. Showing query results in a table
Finally, the complete code of our example should look like this:
<?php
$pdo_connection = new PDO($pdo_parameters, $database_user, $user_password); |
Script 5. Complete example code
0 comments:
Post a Comment