PHP Insert Data Into MySQL

Once you are done with creating the table in the MySQL database. The next step in the process is adding value to the database.

You can add new value by using INSERT INTO MySQL statement to add a new record in the database.

Example Code:

[php]<?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 MyGuests (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]

Code Explanation:

First we achieve server connection by running the serevr connect statement.

$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);
}

The next step is adding the value to the database by running SQL statement.

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

In the above code, we have instructed the php script to INSERT INTO MyGuests column the following values firstname, lastname, email. And to each entry give the following value 'John', 'Doe', 'john@example.com'.

Remember you must add the values to the quote. Each value is separated by the comma.

On the next line, we have checked if everything is ok by using if statement and then we closed the statement with the closing tag.

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();

Related Posts

Leave a Reply