Categories

Articles in MySQL Category

Using MySQL Insert Statement in PHP

In this article, we are going to look at how to use MySQL insert statements in PHP scripts. For examples in this article, we populate the values to be inserted within the scripts.

However in most PHP applications, values will come from user inputs via web forms or by other means like CSV files.

You can find the SQL commands for creating and truncating the data table used in examples (`employee`) here. Make sure you change database connection details before running the PHP scripts.

Inserting a Single Row

Following PHP script shows how to insert a single row into a database table.

<?php

/* Change database details according to your database */
$dbConnection = mysqli_connect('localhost', 'robin', 'robin123', 'company_db');

$firstName  = "Robin";
$lastName   = "Jackman";

$query = "INSERT INTO `employee` (`first_name`, `last_name`) VALUES ('$firstName', '$lastName')";

if (mysqli_query($dbConnection, $query)) {
    echo "Successfully inserted " . mysqli_affected_rows($dbConnection) . " row";
} else {
    echo "Error occurred: " . mysqli_error($dbConnection);
}

?>
  • Query is enclosed with double quotes. This is to include variables inside the query. If you used single quotes, including variables is not possible.
  • There is no semicolon at the end of query (after last right parenthesis) as when you run insert statement in command-line or in a GUI tool. There is a semicolon at the end of line which ends the PHP expression.
  • Make sure single quotes are present around string values. If you had following statement (no single quotes around $firstName and $lastName), it would throw an error.
$query = "INSERT INTO `employee` (`first_name`, `last_name`) VALUES ($firstName, $lastName)";

Inserting Multiple Rows

Inserting multiple rows involves bit of iterating for generating the value part of the statement.

<?php

/* Change database details according to your database */
$dbConnection = mysqli_connect('localhost', 'robin', 'robin123', 'company_db');

$employees[0]['first_name'] = 'Robin';
$employees[0]['last_name']  = 'Jackman';
$employees[0]['job_title']  = 'Software Engineer';
$employees[0]['salary']     = 5500;

$employees[1]['first_name'] = 'Taylor';
$employees[1]['last_name']  = 'Edward';
$employees[1]['job_title']  = 'Software Architect';
$employees[1]['salary']     = 7200;

$employees[2]['first_name'] = 'Vivian';
$employees[2]['last_name']  = 'Dickens';
$employees[2]['job_title']  = 'Database Administrator';
$employees[2]['salary']     = 6000;

$query = "INSERT INTO `employee` (`first_name`, `last_name`, `job_title`, `salary`) VALUES ";

$count = count($employees);

for ($i=0; $i<$count; $i++) {

    $query .= "('{$employees[$i]['first_name']}', '{$employees[$i]['last_name']}', '{$employees[$i]['job_title']}', {$employees[$i]['salary']})";

    /* If not last iteration, add a comma and a space */
    if ($i < ($count - 1)) {
        $query .= ", ";
    }

}

if (mysqli_query($dbConnection, $query)) {
    echo "Successfully inserted " . mysqli_affected_rows($dbConnection) . " rows";
} else {
    echo "Error occurred: " . mysqli_error($dbConnection);
}

?>
  • First part of the INSERT statement is assigned to $query and value part is generated by a for loop and append to $query by string concatenation.
  • Curly brackets are used around array elements since otherwise it will lead to a syntax error (If you want to use array elements and method calls inside an expression enclosed with double quotes, you need to use curly brackets).
  • Salary values are not enclosed with single quotes since they are numerical values (If you wish, you can enclose numerical values with single quotes too).
  • As described in multiple inserts, except for last value segment, you need to add a comma after every other segment. if condition is used for this purpose.

Escaping Values

Having single quotes (and few other special characters) in your insert query can cause errors when executing. Consider following PHP script.

<?php

/* Change database details according to your database */
$dbConnection = mysqli_connect('localhost', 'robin', 'robin123', 'company_db');

$firstName  = "William";
$lastName   = "O'Neil";

$query = "INSERT INTO `employee` (`first_name`, `last_name`) VALUES ('$firstName', '$lastName')";

if (mysqli_query($dbConnection, $query)) {
    echo "Successfully inserted " . mysqli_affected_rows($dbConnection) . " row";
} else {
    echo "Error occurred: " . mysqli_error($dbConnection);
}

?>

When running above PHP script, a MySQL error will be thrown since $lastName contains a single quote. You will need to escape it with mysqli_real_escape_string() as below.

$lastName = mysqli_real_escape_string($dbConnection, "O'Neil");

Additionally, if you are getting values from an external source (like user inputs via a web form), as a security precaution, you need to escape the values to be used in SQL statements since there can be malicious user inputs attempting SQL injections.

Where to Head from Here...
Share with Your Peers...

We Value Your Feedback...

We love to hear what you think about this article. Please provide your opinion, suggestions and improvements using following form. Note that submitted feedback is not displayed but we will get back to you if it needs a reply.