- 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.
- Related Questions & Answers
- How to Install PHP 8 on Ubuntu 20.04
- How to Send Realtime Notifications if User Follow using PHP & Mysql
- ChatGPT: The Ultimate AI Language Model for Conversational AI Solutions
- What is Search Engine Optimization (SEO) and It's Strategies ?
- DA PA Kya Hai ? How to Boost It in Hindi
- Write PHP Program To Print Sum Of Digits
- What is Backlink? How to Get High Quality Backlinks in 2022
- How To Clean Up Unnecessary Code From WordPress Header Without Plugins
- How to Check the URL Contains Certain String or Not Using PHP
- PHP क्या है (What is PHP in Hindi)? पुरी जानकारी in Hindi
- Create Function to Insert Post using core PHP
- How to Pass JSON Data in a URL using CURL in PHP ?
- What is the difference between echo, print, and print_r in PHP?
- How to Implementing User Verification Badge System using PHP
- Write Steps to create a functional and secure API using PHP
- Write PHP Program To Check Prime Number
Advertisements
ads