We are showing how to insert new record into MySQL database. We will explain both MySQLi and PDO approaches.
Let's start with MySQLi extension. Jump straight with an example. We are using OOP approach.
First of all we are establishing the connection with the database.
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn-gt;connect_error) {
die("Connection failed: " . $conn-gt;connect_error);
}
Now, we are inserting a new record into table users. Just watch that string values are quoted and numeric values are not quoted. Finally, we are closing the connection.
$sql = "INSERT INTO users (firstname, lastname, age, email)
VALUES ('John', 'Doe', 35, 'john@example.com')";
if ($conn-gt;query($sql) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "lt;brgt;" . $conn-gt;error;
}
$conn-gt;close();
Now, we are going to add a new record using PDO approach.
First of all, we are creating database connection. Then we set PDO error mode to exception. We merge the entire code within try-catch block.
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn-gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Now, we are inserting a new record by calling the exec() function and passed the SQL query into it as a parameter. Finally, we are closing the connection after completing all the tasks.
$sql = "INSERT INTO users (firstname, lastname, age, email)
VALUES ('John', 'Doe', 35, 'john@example.com')";
$conn-gt;exec($sql);
echo "New record created successfully";
} catch(PDOException $e) {
echo $sql . "lt;brgt;" . $e-gt;getMessage();
}
$conn = null;
Auf dieser Seite können Sie das Online-Video How to insert data into a database using PHP mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer PHP Explained 24 April 2025 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 145 Mal angesehen und es wurde von 1 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!