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;
In questa pagina del sito puoi guardare il video online How to insert data into a database using PHP della durata di ore minuti seconda in buona qualità , che l'utente ha caricato PHP Explained 24 aprile 2025, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 145 volte e gli è piaciuto 1 spettatori. Buona visione!