If you use a prepared statement, you can $JSON_data
over the $JSON_data
array using the foreach loop and run INSERT
with this piece of data.
Using prepared statements will reduce the overhead of building a query by simply sending new data to the database at each iteration of the loop.
$query = mysqli_prepare("INSERT INTO `MyTable` (`col1`,`col2`,`col3`) VALUES(?,?,?)"); foreach($JSON_data as $key => $value) { $query->bind_param('sss',$value["prop1"],$value["prop2"],$value["prop3"]; $query->execute(); }
Note that the first argument to bind_param()
tells it how many values ββyou will bind, as well as the type for each value.
s
corresponds to string data, i
corresponds to integer data, d
corresponds to double (floating point), and b
corresponds to binary data.
Another caveat: DO NOT quote any string data since the data type s
tells mysql to expect a string. If you specify ?
in the prepared statement, it will tell you that the number of parameters is incorrect. If you specify strings, it will be specified in mysql.
EDIT:
If you want to use the same paradigm (inserting multiple rows with one query), there are ways to do this. One way is to create a class that will aggregate calls to bind_param
and make one bind_param when executing the request. The code for this is here .
source share