Create Function to Insert Post and Update Post in Single Function using PHP


Hello there, In this tutorial we will learn how to create function to insert post and update post in single function using core php, here's an example function that can both insert a new post and update an existing post in a single function using PHP's core SQL functions:

function savePost($postData) {
  // Connect to the database
  $conn = mysqli_connect("localhost", "username", "password", "database_name");

  // Check if the connection was successful
  if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
  }

  // Escape the input data to prevent SQL injection attacks
  $id = mysqli_real_escape_string($conn, $postData['id']);
  $title = mysqli_real_escape_string($conn, $postData['title']);
  $content = mysqli_real_escape_string($conn, $postData['content']);
  $author = mysqli_real_escape_string($conn, $postData['author']);

  // Check if the ID is set to determine if we're inserting or updating
  if ($id) {
    // Construct the SQL query to update the post
    $sql = "UPDATE posts SET title='$title', content='$content', author='$author' WHERE id=$id";

    // Execute the SQL query
    if (mysqli_query($conn, $sql)) {
      echo "Post updated successfully!";
    } else {
      echo "Error updating post: " . mysqli_error($conn);
    }
  } else {
    // Construct the SQL query to insert the post
    $sql = "INSERT INTO posts (title, content, author) VALUES ('$title', '$content', '$author')";

    // Execute the SQL query
    if (mysqli_query($conn, $sql)) {
      echo "Post inserted successfully!";
    } else {
      echo "Error inserting post: " . mysqli_error($conn);
    }
  }

  // Close the database connection
  mysqli_close($conn);
}

You can then call this function with an array of post data that includes the post ID if you want to update an existing post, or omits the ID if you want to insert a new post, like this:

Example 1 : To Insert Post 

// Insert a new post
$postData = array(
  'title' => 'My first post',
  'content' => 'This is the content of my first post.',
  'author' => 'John Doe'
);
savePost($postData);

Example 2. To Update Post 

// Update an existing post
$postData = array(
  'id' => 1,
  'title' => 'Updated post',
  'content' => 'This is the updated content of the post.',
  'author' => 'Jane Smith'
);
savePost($postData);

Again, be sure to validate and sanitize user input to prevent security issues.

       

Advertisements

ads