Database
Database
To get started, ensure that you have the MySQLi extension enabled
in your PHP configuration. You can include it in your PHP script
using the require_once or include_once function:
<?php
// Include the MySQLi extension
require_once 'mysqli_connect.php';
?>
2. Establish a Connection:
<?php
// Database connection parameters
$hostname = 'localhost';
$username = 'your_username';
$password = 'your_password';
$database = 'your_database';
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
In this query, we’re inserting a new user into the users table with a
username, email, and hashed password.
<?php
$query = "INSERT INTO users (username, email, password) VALUES
('john_doe', '[email protected]', 'hashed_password')";
if (mysqli_query($conn, $query)) {
echo "Record inserted successfully.";
} else {
echo "Error: " . mysqli_error($conn);
}
?>
With these steps, you can effectively insert new data into your
MySQL database using PHP and MySQLi.
B. Read Data
After executing the SELECT query, you can fetch and display the
data using various functions. A common approach is to use
awhile loop to iterate through the result set and display each row of
data.
Just like with insertion, it’s crucial to handle potential errors when
reading data. Checking for errors using mysqli_error() is essential to
ensure robust error handling.
With these steps, you can effectively read data from your MySQL
database using PHP and MySQLi. Next, we’ll explore how to update
existing data.
C. Update Data
Updating data in a MySQL database is essential when you need to
modify existing records. Here’s how to update data using MySQLi:
In this query, we’re updating the email address of the user with the
username ‘john_doe.’
<?php
$query = "UPDATE users SET email='[email protected]' WHERE
username='john_doe'";
if (mysqli_query($conn, $query)) {
echo "Record updated successfully.";
} else {
echo "Error: " . mysqli_error($conn);
}
?>
if (mysqli_query($conn, $query)) {
echo "Record updated successfully.";
} else {
echo "Error: " . mysqli_error($conn);
}
With these steps, you can effectively update existing data in your
MySQL database using PHP and MySQLi.
D. Delete Data
In this query, we’re deleting the user with the username ‘john_doe.’
<?php
$query = "DELETE FROM users WHERE username='john_doe'";
if (mysqli_query($conn, $query)) {
echo "Record deleted successfully.";
} else {
echo "Error: " . mysqli_error($conn);
}
?>
if (mysqli_query($conn, $query)) {
echo "Record deleted successfully.";
} else {
echo "Error: " . mysqli_error($conn);
}
These steps enable you to delete data from your MySQL database
using PHP and MySQLi.
try {
// Database operation
} catch (Exception $e) {
// Handle the error
}
mysqli_close($conn);