PHP & MySQL in PHP Language
PHP and MySQL are like the Batman and Robin of web development.
PHP and MySQL are like the Batman and Robin of web development.
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.
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 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.
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.
Subscribe to get the latest posts sent to your email.