- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Environmental Science
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- articles and Answers
- Effective Resume Writing
- HR Interview articles
- Computer Glossary
- Who is Who
Create Function to Insert Post using core PHP
Hello there, In this tutorial we will learn how to create function to insert post to database using php. here's an example function to insert a post using PHP's core SQL functions:
PHP
function insertPost($title, $content, $author) {
// 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
$title = mysqli_real_escape_string($conn, $title);
$content = mysqli_real_escape_string($conn, $content);
$author = mysqli_real_escape_string($conn, $author);
// Construct the SQL query
$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 the appropriate values for the title, content, and author of the post you want to insert, like this:
insertPost("My first post", "This is the content of my first post.", "John Doe");
Note that this is just a simple example and you should always validate and sanitize user input to prevent security issues.
Advertisements
ads