Certainly! Here’s an example of PHP code that demonstrates how to add data to a MySQL database:
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare the SQL statement
$sql = "INSERT INTO your_table (column1, column2) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
// Bind the parameters with values
$stmt->bind_param("ss", $column1, $column2);
// Set the parameter values
$column1 = "DataValue1";
$column2 = "DataValue2";
// Execute the statement
if ($stmt->execute()) {
echo "Data inserted successfully.";
} else {
echo "Error inserting data: " . $stmt->error;
}
// Close the statement and the database connection
$stmt->close();
$conn->close();
?>
Make sure to replace the following placeholders with your own values:
localhost
: The hostname or IP address of your MySQL server.your_username
: The username for accessing the MySQL database.your_password
: The password for accessing the MySQL database.your_database
: The name of the MySQL database.your_table
: The name of the table where you want to add data.column1, column2
: The names of the columns in the table where you want to add data.'DataValue1', 'DataValue2'
: The values you want to add tocolumn1
andcolumn2
respectively.
This code uses the MySQLi extension in PHP to establish a connection to the MySQL database, prepare an SQL INSERT statement with parameter placeholders, bind the parameter values, execute the statement, and handle any potential errors that may occur. The code also outputs a success message if the data insertion is successful.