After creating a database and a table, the next step is to add data into it. In PHP, you use the INSERT INTO SQL statement to add new records (rows) to a MySQL table.
To insert data, you must specify the table name and the columns you want to fill, followed by the values for those columns:
INSERT INTO Users (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com');
') or double quotes ("). Numeric values do not need quotes.
In this example, we connect to a database named "myDB" and insert a single record into a table named "Users".
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Users (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
<?php
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO Users (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO Users (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
$conn->exec($sql);
echo "New record created successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Sometimes you need to know the ID of the record you just inserted (e.g., to link it to another table). PHP makes this easy:
$conn->insert_id;mysqli_insert_id($conn);$conn->lastInsertId();