How to insert data into a database using PHP

Publicado el: 24 abril 2025
en el canal de: PHP Explained
145
1

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;


En esta página del sitio puede ver el video en línea How to insert data into a database using PHP de Duración hora minuto segunda en buena calidad , que subió el usuario PHP Explained 24 abril 2025, comparta el enlace con amigos y conocidos, en youtube este video ya ha sido visto 145 veces y le gustó 1 a los espectadores. Disfruta viendo!