Connecting to and querying a MySQL database in PHP is an essential part of web development. PHP provides functions and methods that allow us to connect to a MySQL database, perform queries, and interact with data.
To connect to a MySQL database, we use the mysqli_connect() or mysqli function to establish a connection and pass in parameters such as the server name, username, password, and database name. Once the connection is established, we can execute SQL queries such as SELECT, INSERT, UPDATE, DELETE to retrieve and manipulate data in the database.
Connect to MySQL database
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
// Connect to MySQL database
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
?>
Querying MySQL Database in PHP
After successfully connecting, we can perform database queries using the mysqli_query() function. Here is an example of how to perform a SELECT query in PHP:
<?php
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// Loop through records and display data
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
} else {
echo "No records found.";
}
// Free memory of query result
mysqli_free_result($result);
// Close database connection
mysqli_close($conn);
?>
nserting Data into MySQL Database in PHP
To insert data into a MySQL database using PHP, we use the mysqli_query() function with the INSERT INTO statement. Here's an example:
<?php
$name = "John Doe";
$email = "[email protected]";
$age = 30;
$sql = "INSERT INTO users (name, email, age) VALUES ('$name', '$email', '$age')";
if (mysqli_query($conn, $sql)) {
echo "Data inserted successfully!";
} else {
echo "Error: " . mysqli_error($conn);
}
?>
Updating Data in MySQL Database in PHP
To update data in a MySQL database using PHP, we use the mysqli_query() function with the UPDATE statement. Here's an example:
<?php
$id = 1;
$newEmail = "[email protected]";
$sql = "UPDATE users SET email='$newEmail' WHERE id=$id";
if (mysqli_query($conn, $sql)) {
echo "Data updated successfully!";
} else {
echo "Error: " . mysqli_error($conn);
}
?>
Deleting Data from MySQL Database in PHP
To delete data from a MySQL database using PHP, we use the mysqli_query() function with the DELETE statement. Here's an example
<?php
$id = 1;
$sql = "DELETE FROM users WHERE id=$id";
if (mysqli_query($conn, $sql)) {
echo "Data deleted successfully!";
} else {
echo "Error: " . mysqli_error($conn);
}
?>



