MySQL Database Operations with PHP
MySQL Database Operations with PHP
Today, database management holds a very important place for web applications. PHP is frequently used with databases like MySQL due to its popularity. In this article, we will discuss the basic logic of MySQL database operations with PHP. You will see operations such as database connection, data insertion, update, and deletion.
Connecting to MySQL with PHP
As a first step, you need to connect to your MySQL database via PHP. Below is a basic code example required for connecting to a MySQL database.
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection successful";
?>
Adding, Updating, and Deleting Data
To add, update, or delete data in the database, you should use specific SQL commands in PHP. Below you can find examples of add, update, and delete operations.
Inserting Data
<?php
// Insert operation
$sql = "INSERT INTO user (name, surname) VALUES ('Ahmet', 'Yılmaz')";
if ($conn->query($sql) === TRUE) {
echo "New record added successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Updating Data
<?php
// Update operation
$sql = "UPDATE user SET name='Mehmet' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Deleting Data
<?php
// Delete operation
$sql = "DELETE FROM user WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Conclusion
MySQL database operations with PHP are an indispensable part of web development processes. In this article, we covered connecting, adding, updating, and deleting operations. The PHP and MySQL combination allows you to create powerful and dynamic web applications. By using this information to improve your applications, you can perform more complex database operations.

Yorum Gönder