Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

CRUD in php

CRUD in php

CRUD in php

Here’s an example of full PHP code using mysqli_query() for different queries like SELECT, INSERT, UPDATE, and DELETE:

1. Connecting to the Database

 

<?php
// Database connection
$conn = mysqli_connect("localhost", "username", "password", "database_name");

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>

2. SELECT Query

 

<?php
$id = $_GET['id']; // Assuming ID is passed via GET request

// SELECT query
$query = "SELECT * FROM table_name WHERE id = $id";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) > 0) {
// Output data for each row
while($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>";
}
} else {
echo "0 results";
}
?>

3. INSERT Query

 

<?php
$name = "John Doe";
$email = "john@example.com";

// INSERT query
$query = "INSERT INTO table_name (name, email) VALUES ('$name', '$email')";
if (mysqli_query($conn, $query)) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . mysqli_error($conn);
}
?>

4. UPDATE Query

 

<?php
$id = 1; // Example ID
$name = "John Updated";
$email = "john_updated@example.com";

// UPDATE query
$query = "UPDATE table_name SET name='$name', email='$email' WHERE id=$id";
if (mysqli_query($conn, $query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
?>

5. DELETE Query

 

<?php
$id = 1; // Example ID

// DELETE query
$query = "DELETE FROM table_name WHERE id=$id";
if (mysqli_query($conn, $query)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
?>

6. Closing the Database Connection

 

<?php
// Close the connection
mysqli_close($conn);
?>

Notes:

  • This code directly uses mysqli_query(), but for security (e.g., preventing SQL injection), consider using prepared statements (mysqli_stmt_prepare()).
  • Make sure to replace "username", "password", and "database_name" with your actual database credentials.
Scroll to Top