crud operation via php mysql

crud operation via php mysql

CRUD operations (Create, Read, Update, Delete) allow you to interact with a MySQL database using PHP. Here's an example of how you can perform CRUD operations using PHP and MySQL:

  1. Establish a database connection:
$host = 'localhost';
$dbName = 'your_database_name';
$username = 'your_username';
$password = 'your_password';

$mysqli = new mysqli($host, $username, $password, $dbName);
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: " . $mysqli->connect_error;
    exit();
}

 

Replace 'localhost', 'your_database_name', 'your_username', and 'your_password' with your actual database credentials.

  1. Create a new record (Create operation):

$name = 'John Doe';
$email = '[email protected]';
$age = 25;

$query = "INSERT INTO your_table (name, email, age) VALUES ('$name', '$email', '$age')";
$result = $mysqli->query($query);

if ($result) {
    echo "Record created successfully.";
} else {
    echo "Error: " . $mysqli->error;
}

Replace 'your_table' with the name of your database table.

  1. Retrieve records (Read operation):

$query = "SELECT * FROM your_table";
$result = $mysqli->query($query);

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 "No records found.";
}

This code retrieves all records from the specified table and displays the results.

  1. Update a record (Update operation):

$id = 1;
$newName = 'Jane Smith';

$query = "UPDATE your_table SET name = '$newName' WHERE id = '$id'";
$result = $mysqli->query($query);

if ($result) {
    echo "Record updated successfully.";
} else {
    echo "Error: " . $mysqli->error;
}

This code updates the name of the record with the specified ID.

  1. Delete a record (Delete operation):

$id = 1;

$query = "DELETE FROM your_table WHERE id = '$id'";
$result = $mysqli->query($query);

if ($result) {
    echo "Record deleted successfully.";
} else {
    echo "Error: " . $mysqli->error;
}

This code deletes the record with the specified ID.

  1. Close the database connection:

$mysqli->close();

It's important to close the database connection when you're finished with the CRUD operations.

Remember to adjust the code based on your database structure and requirements, including table names and column names. Additionally, consider using prepared statements or input validation to prevent SQL injection attacks.




Share on Pinterest
Share on LinkedIn
Share on WhatsApp
Share on Telegram