What could be causing the issue with inserting data into the database in PHP?
The issue with inserting data into the database in PHP could be due to errors in the SQL query, incorrect database connection settings, or missing input validation. To solve this issue, ensure that the SQL query is correctly formatted, the database connection is established successfully, and input data is sanitized before inserting into the database.
<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Sanitize input data
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
// Insert data into database
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Related questions
-
PHP JavaScript interactive elements
-
if statement $tel true
-
file_put_contents PHP web server