How to create database connection and query in PHP?

Since PHP 4.3, mysql_reate_db() is deprecated. Now you can use the following 2 alternatives.

  • mysqli_query()
  • PDO::_query()

To create a database connection and execute a query in PHP, you typically use the MySQLi (MySQL Improved) or PDO (PHP Data Objects) extension. Here’s a basic example using MySQLi:

php
<?php
// Database connection parameters
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database_name";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Example query
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}

// Close connection
$conn->close();
?>

Replace "localhost", "username", "password", and "database_name" with your actual database server details. Also, replace "table_name" with the name of your table.

This code connects to a MySQL database, executes a SELECT query, and outputs the results. It’s important to handle errors and to close the connection properly to avoid potential security vulnerabilities and resource leaks.