To insert data into a MySQL database table using PHP, you can use SQL INSERT INTO queries. Below are examples using both mysqli and PDO to insert data into a users table with columns name and email .
Here's an example using mysqli to insert a new row into the users table:
// Database credentials
$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);
}
// Data to be inserted
$name = "John Doe";
$email = "john@example.com";
// SQL query to insert data
$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;
}
// Close connection
$conn->close();
Here's the same example using PDO :
// Database credentials
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
try {
// Create connection
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Data to be inserted
$name = "John Doe";
$email = "john@example.com";
// SQL query to insert data
$sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
// Execute the query
$stmt->execute();
echo "New record created successfully";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
} finally {
// Close connection
$conn = null;
}
You can also insert multiple rows at once using INSERT INTO with multiple value sets:
// SQL query to insert multiple rows
$sql = "INSERT INTO users (name, email) VALUES
('Alice', 'alice@example.com'),
('Bob', 'bob@example.com'),
('Charlie', 'charlie@example.com')";
// Execute the query
$conn->query($sql);
Running these scripts will insert the specified data into the users table in your MySQL database.