Advertisement

Google Ad Slot: content-top

MySQL Insert Data

~1 min read · PHP
On this page

To insert data into a MySQL database using PHP, you can use MySQLi (Procedural & Object-Oriented) or PDO.


The INSERT INTO statement is used to add new records to a MySQL table


Syntax:


INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)


The following examples add a new record to the "users" table:

Example (MySQLi Procedural)
" . mysqli_error($conn); } // Close connection mysqli_close($conn); ?>
Example (MySQLi Object-oriented)
connect_error) { die("Connection failed: " . $conn->connect_error); } // Insert query $sql = "INSERT INTO users (name, email, password) VALUES ('John Doe', 'john@example.com', '123456')"; if ($conn->query($sql) === TRUE) { echo "New record inserted successfully. Last inserted ID is: " . $conn->insert_id; } else { echo "Error: " . $sql . "
" . $conn->error; } // Close connection $conn->close(); ?>
Example (PDO)
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Insert query with placeholders $sql = "INSERT INTO users (name, email, password) VALUES (:name, :email, :password)"; // Prepare statement $stmt = $conn->prepare($sql); // Bind parameters $stmt->bindParam(':name', $name); $stmt->bindParam(':email', $email); $stmt->bindParam(':password', $password); // Values to insert $name = "John Doe"; $email = "john@example.com"; $password = "123456"; // Execute the query $stmt->execute(); // Get last inserted ID echo "New record inserted successfully. Last inserted ID is: " . $conn->lastInsertId(); } catch (PDOException $e) { echo "Error: " . $e->getMessage(); } // Close connection $conn = null; ?>