How To Crud PHP
How To Crud PHP
ChatGPT
ChatGPT
CRUD (Create, Read, Update, Delete) operations are fundamental in web development for
interacting with databases. Here’s a basic guide on how to perform CRUD operations in PHP:
First, you need to set up your database and table(s). Here's a simple example using MySQL:
sql
Copy code
CREATE DATABASE my_database;
USE my_database;
In your PHP script, establish a connection to your MySQL database using mysqli or PDO.
Here’s an example using mysqli:
php
Copy code
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "my_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Create (Insert)
php
Copy code
$name = "John Doe";
$email = "[email protected]";
$age = 30;
$sql = "INSERT INTO users (name, email, age) VALUES ('$name', '$email',
$age)";
Read (Select)
php
Copy code
$sql = "SELECT id, name, email, age FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email:
" . $row["email"]. " - Age: " . $row["age"]. "<br>";
}
} else {
echo "0 results";
}
Update
php
Copy code
$id = 1;
$newAge = 35;
Delete
php
Copy code
$id = 2;
After performing database operations, it’s important to close the database connection:
php
Copy code
$conn->close();
Important Notes:
This basic guide covers the essentials of CRUD operations in PHP. Adjust the database
credentials ($servername, $username, $password, $dbname) and SQL queries according to
your specific setup and requirements.