How to insert data in a database with PHP and MySQL
To insert data into a MySQL database using PHP, you can use the following syntax:
$servername = "localhost"; $username = "root"; $password = ""; $dbname = "mydatabase"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Insert data $sql = "INSERT INTO users (name, email, age) VALUES ('John Doe', 'john.doe@email.com', 30)"; if ($conn->query($sql) === TRUE) { echo "Data inserted successfully"; } else { echo "Error: " . $sql . " " . $conn->error; } // Close connection $conn->close();
In the above example, we first create a connection to the MySQL database using the mysqli() function. We then check if the connection was successful, and if so, we use the INSERT INTO query to insert data into the “users” table.
Note that we use single quotes to enclose the data values we want to insert, and we separate them using commas. Also, we wrap the query within an if statement to check if the query was executed successfully, and we output an error message if it failed.
Here is another example that inserts data dynamically using a form:
$servername = "localhost"; $username = "root"; $password = ""; $dbname = "mydatabase"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Insert data if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['age'])) { $name = $_POST['name']; $email = $_POST['email']; $age = $_POST['age']; $sql = "INSERT INTO users (name, email, age) VALUES ('$name', '$email', '$age')"; if ($conn->query($sql) === TRUE) { echo "Data inserted successfully"; } else { echo "Error: " . $sql . " " . $conn->error; } } // Close connection $conn->close();
In this example, we first check if the form fields are set using the isset() function. We then retrieve the values entered by the user and insert them into the “users” table using the INSERT INTO query.
Here is a helpful resource for learning more about SQL queries: https://www.w3schools.com/sql/.
Written by: Michael from Beginnrtuts.com 13-06-2023 Written in: PHP tutorials
This tutorial was really helpful! I was struggling with inserting data into a database using PHP and MySQL, but this step-by-step guide made it so easy to understand . The explanations were clear, and the code examples were spot-on. Now I feel confident in my ability to insert data successfully. Thank you for sharing this valuable resource!