How to run an INSERT query using Mysqli
- Running INSERT query with raw Mysqli
- Explanation
- INSERT query with a helper function
- Insert multiple rows in one query
- INSERT query from associative array
- Comments (5)
It goes without saying that you must use prepared statements for any SQL query that would contain a PHP variable. Therefore, as usually the INSERT query makes little sense without variables, it should always run through a prepared statement. To do so:
- create a correct SQL INSERT statement
- replace all variables in the query with with question marks (called placeholders or parameters)
- prepare the resulting query
- bind variables to placeholders
- execute the query
Just make sure you've got a properly configured mysqli connection variable that is required in order to run SQL queries and to inform you of the possible errors.
Running INSERT query with raw Mysqli
Just write a code like in this example
$sql = "INSERT INTO users (name, email, password) VALUES (?,?,?)";
$stmt= $db->prepare($sql);
$stmt->bind_param("sss", $name, $email, $password);
$stmt->execute();
and have your query executed without a single syntax error or SQL injection!
Explanation
What is going on here?
$sql = "INSERT INTO users (name, email, password) VALUES (?,?,?)";
Like it was said above, first we are writing an SQL query where all variables are substituted with question marks.
IMPORTANT! there should be no quotes around question marks, you are adding placeholders, not strings.
$stmt= $db->prepare($sql);
Then, the query is prepared. The idea is very smart. To avoid even a possibility of the SQL injection or a syntax error caused by the input data, the query and the data are sent to database server separately. So it goes on here: with prepare() we are sending the query to database server ahead. A special variable, a statement is created as a result. We would use this variable from now on.
$stmt->bind_param("sss", $name, $email, $passwor);
Then variables must be bound to the statement. The call consists of two parts - the string with types and the list of variables. With mysqli, you have to designate the type for each bound variable. It is represented by a single letter in the first parameter. The number of letters should be always equal to the number of variables. The possible types are
- i for integer
- d fof double (float)
- s for string
- b for blobs
NOTE that you can almost always safely use "s" for any variable.
So you can tell now that "sss" means "there would be 3 variables, all of string type". And then, naturally, three variables obediently follow.
$stmt->execute();
Then the query finally gets executed. Means variables get sent to database server and the query is actually executed.
NOTE that you don't have to check the execution result. Given you have the proper connection code mentioned above, in case of error mysqli will raise an error automatically.
INSERT query with a helper function
As you may noted, the code is quite verbose. Luckily, in the recent PHP version (8.2) another function has been added to ease the task
$sql = "INSERT INTO users (name, email, password) VALUES (?,?,?)";
$db->execute_query($sql, [$name, $email, $password]);
Simple, clean and safe!
In case your PHP version is not that recent, I encourage you to upgrade, but if it's impossible at the moment, then there is a simple temporary substitution that you can add to your code.
Insert multiple rows in one query
Assuming you have array of arrays, something like this
$data = [
4, 'foo', 10,
2, 'bar', 15,
5, 'baz', 20,
];
You can write a code that would create a query with multiple VALUES clauses, like this
INSERT INTO t (col1,col2,col3) VALUES (?,?,?),(?,?,?),(?,?,?)
And then execute it with all data in one go:
$sql = "INSERT INTO t (col1,col2,col3) VALUES ";
$values = "(?".str_repeat(",?",count($data[0])-1).")"; // (?,?,?)
$sql .= $values.str_repeat(",$values",count($data)-1); // (?,?,?),(?,?,?)
$stmt = $mysqli->prepare($sql);
$types = str_repeat("s", count($data) * count($data[0])); // sss
$params = array_merge(...$data);
$stmt->bind_param($types, ...$params);
$stmt->execute();
Or the same with execute_query() (instead of prepare and below):
$mysqli->execute_query($sql, array_merge(...$data));
INSERT query from associative array
It is often happens that we have an array consists of fields and their values that represents a row to be inserted into a database. And naturally it would be a good idea to have a function to convert such an array into a correct SQL INSERT statement and execute it. So here it goes (utilizing a helper function mentioned above but you can easily rewrite it to raw mysqli if you'd like to):
First of all this function will need a helper function of its own. We will need a function to escape MySQL identifiers. Yes, all identifiers must be quoted and escaped, according to MySQL standards, in order to avoid various syntax issues.
function escape_mysql_identifier($field){
return "`".str_replace("`", "``", $field)."`";
}
And now we can finally have a function that accepts a table name and an array with data and runs a prepared INSERT query against a database:
function prepared_insert($db, $table, $data) {
$keys = array_keys($data);
$keys = array_map('escape_mysql_identifier', $keys);
$fields = implode(",", $keys);
$table = escape_mysql_identifier($table);
$placeholders = str_repeat('?,', count($keys) - 1) . '?';
$sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";
prepared_query($db, $sql, array_values($data));
}Related articles:
- Mysqli SELECT query with prepared statements
- How to run a SELECT query using Mysqli
- How to run an UPDATE query using Mysqli
- Mysqli prepared statement with multiple values for IN clause
- Using mysqli prepared statements with LIKE operator in SQL
- How to create a search filter for mysqli
- Mysqli examples
- How to call stored procedures with mysqli
- How to run 1000s insert queries with mysqli?
Comments:
I'm trying to create a workable INSERT query but am having trouble with NULL as an input parameter.
In my example IDno is AUTO_INCREMENT therefore value has to input as NULL. How to make this work with prepare???
Please help be get this working!
//$query='INSERT INTO
accountVALUES (NULL, "", "", "Anita Johnson Accounting", "Accounting", "", "", "", "", "", "", "", "", "", "");';// =========== trying out prepare ===================
$query="INSERT INTO
accountVALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";$null="NULL";
$stmt= $cxn->prepare($query); $stmt->bind_param("sssssssssssssss", $null, $null, $null, $company, $category, $null, $null, $null, $null, $null, $null, $null, $null, $null, $null); //$stmt->bind_param("sssssssssssssss", "", "", "", $company, $category, "", "", "", "", "", "", "", "", "", ""); // didn't work $stmt->execute();
// ================== OUTPUT ===============================
Fatal error: Uncaught mysqli_sql_exception: Incorrect integer value: 'NULL' for column
accounts.account.IDnoat row 1 in .......What is the license of prepared_query() and other helper functions (if any?)
Reply:
Oh come on It's just functions. Code examples. You can use them as well as any other information from this site.
Besides, they are obsoleted, use execute_query() instead.
Love your prepared_query() method. I use it all he time. How I can get the last insert ID from this function?
Reply:
Hello Christie!
Thank you for such a nice feedback! You don't get the last insert ID from the function because it's a property of mysqli object. So it would be $mysqli->insert_id or similar, depends on how you name your mysqli variable.
Hi,
Can you make a tutorial about using MySQLi UPDATE with 'column => value' associative array and your helper function, just as you did with INSERT? It will be really appreciated.
Thank you, Boris
Reply:
Hello Boris!
An UPDATE function is a tricky business, as it requires a WHERE clause which at best requires a full featured Query Builder. But I am not sure I am to go down that rabbit hole for a simple helper function.
All I can suggest is a quick palliative, a function where a WHERE clause limited to the primary key lookup with the primary key field name hardcoded, in this case as
id:so it can be called this way
But to be honest, I don't like the idea. Such a function is good for an ORM - a class where you could define all the field names beforehand. But as a function is looks awkward. Better to write the UPDATE statement by hand.
Greetings,
I would like to ask you a big favor. I know this may be a long shot but long story short, I am currently hitting my head on the wall because of my Final Year Project. The problem is, the code works perfectly fine on my localhost but after I uploaded it, there were many errors and things that were supposed to work, didn't work, without a single error code. This makes it hard for me to even know what my problems even were. I am a student and a complete novice in PHP, and I'm too broke to pay someone even if I want to. If it's okay with you, may I upload my .php and .sql files for you to look at? Also I will send the connection info for uploading to the server.
If you don't want to listen to my selfish request, I completely understand, please just ignore this message.
Have a nice day.
Reply:
Hello Muhammad
Indeed I won't go into great lengths running your code on my own server, but I am sure I can help you anyway.
First of all you must configure PHP on your new server to report PHP errors. How to do it is described in the article https://phpdelusions.net/articles/error_reporting
As soon as you will get hold of PHP errors you will have a clue what to do next.