How to connect to a MySQL database in PHP

There are two ways to connect to a MySQL database in PHP:

Using the MySQLi extension: The MySQLi extension is a newer extension that provides a more object-oriented interface to MySQL.

Using the PDO extension: The PDO extension is a more versatile extension that can be used to connect to a variety of databases, including MySQL.

To connect to a MySQL database using the MySQLi extension, you need to create a new MySQLi object and pass in the following information:


The hostname of the MySQL server

The username of the MySQL user

The password of the MySQL user

The name of the database you want to connect to

For example, the following code will connect to a MySQL database named mydb on a server named localhost with the username root and the password password:


PHP

<?php

$mysqli = new mysqli('localhost', 'root', 'password', 'mydb');

?>


Once you have connected to the MySQL database, you can use the MySQLi object to execute SQL queries. For example, the following code will select all rows from the users table:


PHP

<?php

$result = $mysqli->query('SELECT * FROM users');

?>


The result variable will contain an object that represents the result set of the query. You can use the fetch_assoc() method to get an associative array of each row in the result set:


PHP

<?php

while ($row = $result->fetch_assoc()) {

    echo $row['username'] . ' ' . $row['email'] . '<br>';

}

?>


To connect to a MySQL database using the PDO extension, you need to create a new PDO object and pass in the following information:


The DSN (Data Source Name) of the MySQL database

The username of the MySQL user

The password of the MySQL user

For example, the following code will connect to a MySQL database named mydb on a server named localhost with the username root and the password password:


PHP

<?php

$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'root', 'password');

?>


Once you have connected to the MySQL database, you can use the PDO object to execute SQL queries. For example, the following code will select all rows from the users table:


PHP

<?php

$stmt = $pdo->prepare('SELECT * FROM users');

$stmt->execute();

$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>


The result variable will contain an array of associative arrays, one for each row in the result set. You can access the values in each row by their column name. For example, the following code will print the username and email address of the first row in the result set:


PHP

<?php

foreach ($result as $row) {

    echo $row['username'] . ' ' . $row['email'] . '<br>';

}

?>


I hope this helps! Let me know if you have any other questions.

No comments:

Post a Comment