PHP & MySQL in PHP Language
PHP and MySQL are like the Batman and Robin of web development. PHP, a versatile s
erver-side scripting language, and MySQL, a powerful open-source relational database management system, form a dynamic duo that can handle everything from basic web applications to complex e-commerce sites. In this post, we’ll explore how PHP and MySQL work together, and provide practical examples to illustrate their synergy.Connecting to a MySQL Database
Before you can work with a MySQL database in PHP, you need to establish a connection. The mysqli_connect()
function is commonly used for this purpose. Here’s a basic example of how to connect to a MySQL database:
<?php
$server = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
// Create a connection
$connection = mysqli_connect($server, $username, $password, $database);
// Check the connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
This script connects to a MySQL database on a local server and displays a success message if the connection is established.
Executing SQL Queries
Once connected, you can perform various database operations using SQL queries. Let’s look at a simple example of inserting data into a MySQL database:
<?php
$first_name = "John";
$last_name = "Doe";
$email = "john@example.com";
$sql = "INSERT INTO users (first_name, last_name, email) VALUES ('$first_name', '$last_name', '$email')";
if (mysqli_query($connection, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
mysqli_close($connection);
?>
In this example, we insert a new user into a users
table in the MySQL database. We construct an SQL query, execute it, and display a success or error message.
Retrieving Data
Retrieving data from a MySQL database is equally straightforward. Here’s an example of how to retrieve and display user information from a database:
<?php
$sql = "SELECT * FROM users";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . " - Name: " . $row["first_name"] . " " . $row["last_name"] . "<br>";
}
} else {
echo "No records found";
}
mysqli_close($connection);
?>
This script fetches all user records from the users
table, loops through the result set, and displays user information.
Updating and Deleting Data
PHP also allows you to update and delete data in MySQL databases using SQL queries. Whether it’s editing a user’s details or removing outdated records, you have the power to control your data dynamically.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.