PDO database connection. Code example open

PDO database connection. Code example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: PHP 5.6 +

To connect to the database, it is convenient to create a separate file in which to enter the parameters for connection. Let’s create this file and name it connection.php

Next add some content to connection.php file:

//сreate variables in which parameters for connection are entered
$host = 'localhost';
$db = 'my_db';
$user = 'root';
$pass = 'root';
$charset = 'utf8';

//from our variables we will form request for PDO connection
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";

$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,//set options for PDO connection
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,//Sets the default sampling mode
];

//make a PDO connection
$pdo = new PDO($dsn, $user, $pass, $options);

PDO functions

$res = $pdo->prepare("SELECT COUNT(*) FROM users WHERE login = ?");//prepares a query for execution and returns the object associated with the query
$res->execute([$login]);//runs a prepared query for execution
$res->fetchColumn();//returns data from one column of the next row in the resulting table. If there are no more rows as a result of the query, the function will return false.
$res->fetch();//retrieves the next row from the object's result set
$pdo->query("SELECT * FROM messages");//executes a SQL query in which receives all data from the messages table
$pdo->fetchAll();//convert data to an array of results

Read more about this functions or search a new – https://www.php.net/manual/en/book.pdo.php

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation