php inserting data in mysql from json runs too slowly - php

I have the following code to read a JSON and store the results in a DDBB.
The code works, but it takes more than a minute to insert just 400 records.
If I open the json, it loads pretty fast.
What I'm doing wrong?
$db = new PDO('', '', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(tableExists($db, 'locations') == 1)
{
$sql=$db->prepare("DROP TABLE locations");
$sql->execute();
}
$sql ="CREATE TABLE `locations` (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, evid INT(6) NOT NULL, place VARCHAR(150), country VARCHAR(150), reg_date TIMESTAMP)" ;
$db->exec($sql);
$json = file_get_contents('thejson.php');
$data = array();
$data = json_decode($json);
foreach ($data as $key => $object)
{
if(is_object($object))
{
$id = $object->id;
$place = $object->name;
$country = substr(strrchr($object->name, "-"), 2);
$stmt = $db->prepare("INSERT INTO `locations` (evid, place, country) VALUES (:evid, :places, :country)");
$stmt->bindValue(':evid', $id, PDO::PARAM_INT);
$stmt->bindValue(':places', $place, PDO::PARAM_STR);
$stmt->bindValue(':country', $country, PDO::PARAM_STR);
$stmt->execute();
}
}

So first 2 things i would try would be moving the prepare outside the loop, and wrapping it in a transaction:
try {
$db->beginTransaction();
$stmt = $db->prepare("INSERT INTO `locations` (evid, place, country) VALUES (:evid, :places, :country)");
foreach ($data as $key => $object)
{
if(is_object($object))
{
$id = $object->id;
$place = $object->name;
$country = substr(strrchr($object->name, "-"), 2);
$stmt->bindValue(':evid', $id, PDO::PARAM_INT);
$stmt->bindValue(':places', $place, PDO::PARAM_STR);
$stmt->bindValue(':country', $country, PDO::PARAM_STR);
$stmt->execute();
}
}
$db->commit();
} catch (Exception $e) {
$db->rollBack();
throw $e;
}
Another thing you could do is try using bindParam to bind the vars by reference - this way you only need to call bindParam once on each variable name at the start, then just overwrite the values of those variables on each iteration and call execute.
try {
$db->beginTransaction();
$stmt = $db->prepare("INSERT INTO `locations` (evid, place, country) VALUES (:evid, :places, :country)");
$id = 0;
$place = '';
$country = '';
$stmt->bindParam(':evid', $id, PDO::PARAM_INT);
$stmt->bindParam(':places', $place, PDO::PARAM_STR);
$stmt->bindParam(':country', $country, PDO::PARAM_STR);
foreach ($data as $key => $object)
{
if(is_object($object))
{
$id = $object->id;
$place = $object->name;
$country = substr(strrchr($object->name, "-"), 2);
$stmt->execute();
}
}
$db->commit();
} catch (Exception $e) {
$db->rollBack();
throw $e;
}
Similar to this instead of calling bind* you could just pass the values in via execute:
try {
$db->beginTransaction();
$stmt = $db->prepare("INSERT INTO `locations` (evid, place, country) VALUES (:evid, :places, :country)");
foreach ($data as $key => $object)
{
if(is_object($object))
{
$params = array(
':id' => $object->id,
':places' => $object->name,
':country' => substr(strrchr($object->name, "-"), 2)
);
$stmt->execute($params);
}
}
$db->commit();
} catch (Exception $e) {
$db->rollBack();
throw $e;
}
I suspect using a transaction will get you a performance gain, but I dont know that there will be a ton of difference between switching up the binding methods.
Your best bet is probably to insert all the records in a single query as #PavanJiwnani suggests:
// first we need to compile a structure of only items
// we will insert with the values properly transformed
$insertData = array_map(function ($object) {
if (is_object($object)) {
return array(
$object->id,
$object->name,
substr(strrchr($object->name, "-"), 2)
);
} else {
return false;
}
}, $data);
// filter out the FALSE values
$insertData = array_filter($insertData);
// get the number of records we have to insert
$nbRecords = count($insertData);
// $records is an array containing a (?,?,?)
// for each item we want to insert
$records = array_fill(0, $nbRecords, '(?,?,?)');
// now now use sprintf and implode to generate the SQL like:
// INSERT INTO `locations` (evid, place, country) VALUES (?,?,?),(?,?,?),(?,?,?),(?,?,?)
$sql = sprintf(
'INSERT INTO `locations` (evid, place, country) VALUES %s',
implode(',', $records)
);
$stmt = $db->prepare($sql);
// Now we need to flatten our array of insert values as that is what
// will be expected by execute()
$params = array();
foreach ($insertData as $datum) {
$params = array_merge($params, $datum);
}
// and finally we attempt to execute
$stmt->execute($params);

Try to echo timestamps with milliseconds to see what is running slow. Probably executing 400 insert queries (including opening/closing connections).

There are many factors that affects the performance of the database, please provide detailed information about the database system, PHP version and related hardware.
The bottleneck could be at:
file_get_contents('thejson.php')
if the JSON contents are fetched from a remote host, i.e. DB is running normally, network is slow.
You may also want to consider move:
$stmt = $db->prepare("INSERT INTO `locations` (evid, place, country) VALUES (:evid, :places, :country)");
out of the foreach loop.

Related

PDO in laravel is not going into the next loop after return

SO, I have a PDO statement that is working perfectly. It does what it should, and then it returns true (or false if I force bad data)
The issue is that it is not moving into the loop after the statement since it's returning true. How can I make it so that if the statement executes successfully without error, it moves into the foreach loop right after it?
$sql = "CALL TEST.PROCEDURE (
:id ,
:type ,
:name,
)";
try {
$pdo = DB::connection('odbc')->getPdo();
$pdoStatement = $pdo->prepare($sql);
$pdoStatement->bindParam(':id', $id, \PDO::PARAM_INT);
$pdoStatement->bindParam(':type', $type, \PDO::PARAM_STR);
$pdoStatement->bindParam(':name', $name, \PDO::PARAM_STR);
$pdoStatement->execute();
} catch (\Exception $e) {
throw $e;
return false;
}
return true;
$newData = 0;
foreach ($object->days as $key => $value) {
dd($value); //this isn't dumping because the loop isn;t being hit
}

Do While loop works well with echo but loops only once with a function inside loop

This code is supposed to insert 100 rows into the DB.
Yet when I run it, it loops only once, inserts one row and stops.
I replaced the function call with :
echo $keywords[4].'<br>';
It works perfectly. with no probleb
What is missing so that it will insert all rows into DB?
what should I change q add so that the code will insert all rows in the file
Here is the loop code:
do{
//Insert row content into array.
$keywords = preg_split("#\<(.*?)\>#", $row);
//Insert relevant data into DB
add_data($keywords);
}
else{
// If row is irrelevant - continue to next row
continue;
}
}while (strpos($row, 'Closed P/L') != true);
Here is the function
function add_data($keywords)
{
global $db;
$ticket =$keywords[2];
$o_time = $keywords[4];
$type = $keywords[6];
$size = $keywords[8];
$item = substr($keywords[10], 0, -1);
$o_price = $keywords[12];
$s_l = $keywords[14];
$t_p = $keywords[16];
$c_time = $keywords[18];
$c_price = $keywords[20];
$profit = $keywords[28];
try
{
$sql = "
INSERT INTO `data`
(ticket, o_time, type, size, item, o_price, s_l, t_p, c_time, c_price, profit)
VALUES
(:ticket, :o_time, :type, :size, :item, :o_price, :s_l, :t_p, :c_time, :c_price, :profit)";
$stmt = $db->prepare($sql);
$stmt->bindParam('ticket', $ticket, PDO::PARAM_STR);
$stmt->bindParam('o_time', $o_time, PDO::PARAM_STR);
$stmt->bindParam('type', $type, PDO::PARAM_STR);
$stmt->bindParam('size', $size, PDO::PARAM_STR);
$stmt->bindParam('item', $item, PDO::PARAM_STR);
$stmt->bindParam('o_price', $o_price, PDO::PARAM_STR);
$stmt->bindParam('s_l', $s_l, PDO::PARAM_STR);
$stmt->bindParam('t_p', $t_p, PDO::PARAM_STR);
$stmt->bindParam('c_time', $c_time, PDO::PARAM_STR);
$stmt->bindParam('c_price', $c_price, PDO::PARAM_STR);
$stmt->bindParam('profit', $profit, PDO::PARAM_STR);
$stmt->execute();
//return true;
}
catch(Exception $e)
{
return false;
echo 'something is wrong. Here is the system\'s message:<br>'.$e;
}
}

PDO binding two array of values

I add a lot a values with params ($queryArr) in INSERT statemnt in foreach
public function getClients()
{
helper::putToLog("\n----- getClients\n", true);
$managedCustomerService = $this->user->GetService('ManagedCustomerService', ADWORDS_VERSION);
$selector = new Selector();
$selector->fields = array("CustomerId", "Name", "CurrencyCode");
$graph = $managedCustomerService->get($selector);
if (isset($graph->entries)) {
$accounts = [];
foreach ($graph->entries as $account) {
$accounts[$account->customerId] = $account;
}
helper::putToLog('Clients found: '.count($accounts)."\n", true);
} else {
helper::putToLog('Clients not found'."\n", true);
return false;
}
$sth = $this->db->prepare('UPDATE `adwords_clients_google` set status = 2');
$sth->execute();
$sth = null;
$queryClients = "INSERT INTO `adwords_clients_google` (`client_foreign_id`, `status`, `client_name`, `client_currency`) VALUES";
foreach($accounts as $account) {
$queryArr[$account->customerId] = "(".$account->customerId.", 1, :".$account->customerId.", :".$account->customerId."_currencyCode)";
$nameArr[$account->customerId] = $account->name;
$currencyArr[$account->customerId."_currencyCode"] = $account->currencyCode;
}
$queryClients .= implode(',', $queryArr) . " ON DUPLICATE KEY UPDATE `status` = VALUES(`status`), `client_name` = VALUES(`client_name`) ";
$sth = $this->db->prepare($queryClients);
foreach ($nameArr as $key => $value) {
$sth->bindValue(":$key", str_replace("'", "\'", $value), PDO::PARAM_STR);
}
foreach ($currencyArr as $key => $value) {
$sth->bindValue(":$key", $value, PDO::PARAM_STR);
}
print_r($sth);
try {
if ($sth->execute()) {
helper::putToLog('ok queryCampaignArr, inserted rows: ' . $sth->rowCount());
} else {
helper::putToLog('not ok', true);
}
} catch (Exception $ex) {
helper::putToLog($sth->debugDumpParams(), true);
helper::putToLog("ERROR: ".$ex->getMessage(), true);
}
return true;
}
and there are 2 array of values I need to bind $nameArr and $currencyArr. I didn't get any errors but column client_currency is empty even though array $currencyArr contains all necessary values. What's wrong?
It looks like you haven't grasped the concept of prepared+paramterized statements yet.
You prepare them once and then execute them with varying parameters (one or) multiple times.
$sth = $this->db->prepare('
INSERT INTO
`adwords_clients_google`
(`client_foreign_id`, `status`, `client_name`, `client_currency`)
VALUES
(:id, 1, :name, :currency)
ON DUPLICATE KEY UPDATE
`status` = VALUES(`status`),
`client_name` = VALUES(`client_name`)
');
$sth->bindParam(':id', $id);
$sth->bindParam(':name', $name);
$sth->bindParam(':currency', $currency);
foreach($accounts as $account) {
$id = $account->customerId;
$name = $account->name;
$currency = $account->currencyCode;
$sth->execute();
}
if you haven't got any error message/log entries please make sure that the error handling mode of your PDO instance really is set to PDO::ERRMODE_EXCEPTION.
edit: to illustrate that, here's an sscce:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
PDO::ATTR_EMULATE_PREPARES=>false,
PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
setup($pdo); // creating temporary table + sample data for this example
printTable("before", $pdo);
$sth = $pdo->prepare('
INSERT INTO
`soFoo`
(`client_foreign_id`, `status`, `client_name`, `client_currency`)
VALUES
(:id, 1, :name, :currency)
ON DUPLICATE KEY UPDATE
`status` = VALUES(`status`),
`client_name` = VALUES(`client_name`)
');
$sth->bindParam(':id', $id);
$sth->bindParam(':name', $name);
$sth->bindParam(':currency', $currency);
$accounts = data();
foreach($accounts as $account) {
$id = $account->customerId;
$name = $account->name;
$currency = $account->currencyCode;
$sth->execute();
}
printTable("after", $pdo);
function data() {
return array_map(function($e) { return (object)$e; }, array(
array('customerId'=>1, 'name'=>'customerA', 'currencyCode'=>'cA'),
array('customerId'=>2, 'name'=>'customerB', 'currencyCode'=>'cB'),
));
}
function printTable($cap, $pdo) {
echo $cap, "\r\n";
foreach( $pdo->query('SELECT * FROM soFoo', PDO::FETCH_ASSOC) as $r ) {
echo join(', ', $r), "\r\n";
}
}
function setup($pdo) {
$pdo->exec('
CREATE TEMPORARY TABLE soFoo (
client_foreign_id int,
`status` int,
client_name varchar(32),
client_currency varchar(32),
unique(client_foreign_id)
)
');
$pdo->exec("INSERT INTO soFoo (client_foreign_id,status,client_name,client_currency) VALUES (1, 0, 'agent smith', 'kruegerrand')");
}
prints
before
1, 0, agent smith, kruegerrand
after
1, 1, customerA, kruegerrand
2, 1, customerB, cB

PHP - for statement in an array

For a PDO execution statement I am trying to make any static information such as column names and array strings to a dynamic array which contains every column from the MySQL table.
The original code was:
$stmt = $conn->prepare("INSERT into data (`username,` `password`, `email`) VALUES username = :username , password = :password , email = :email ");
$stmt->execute(array(
':username' => $entry_username,
':password' => $entry_password,
':email' => $entry_email
));
So far I have been able to change the sql statement to
$sql = "INSERT into DATA (`" . implode('`,`', $columns) . "`) values (:" . implode(',:', $columns) . ")";
$stmt = $conn->prepare($sql);
but have been unable to do a similar thing to the execution array to make it dynamically variating like the statement.
I have tried adding a for statement in the array
for ($i = 0; $i < count($columns); $i++) {
':'.$columns[$i] => ${'entry_'.$columns[$i]};
}
but this hasn't worked.
Any help would be much appreciated.
Thanks in advance!
This is a perfect situation to make good use of a prepared statement.
Try this:
I am kind of assuming what the varuables will be called in the $columns array here.
$stmt = $conn->prepare("INSERT into data
(username, password, email) VALUES( :username , :password, :email )");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
foreach ( $columns as $column ) {
$username = $column['username'];
$password = $column['password'];
$email = $column['email'];
$result = $stmt->execute();
if ( ! $result ) {
// add some error checking code here
}
}
Basically, your code would look like this.
$entry = array(
'username' => $_POST['username'], //assuming it's comming from the post data or for instance $row['username'] if from previous select statement
'password' => $_POST['password'],
'email' => $_POST['email']
);
$sth = $dbh->prepare('INSERT into data (`username,` `password`, `email`) VALUES (:username, :password, :email)');
$sth->bindValue(':username', $entry['username'], PDO::PARAM_INT);
$sth->bindValue(':password', $entry['password'], PDO::PARAM_STR);
$sth->bindValue(':email', $entry['email'], PDO::PARAM_STR);
$sth->execute();
If you want the bound variables to be dynamically created, then you need to create with a loop the bindValue rows:
$entry = array(
'username' => $_POST['username'], //assuming it's comming from the post data or for instance $row['username'] if from previous select statement
'password' => $_POST['password'],
'email' => $_POST['email']
);
$sth = $dbh->prepare('INSERT into data (`username,` `password`, `email`) VALUES (:username, :password, :email)');
foreach($entry as $key => $value) {
$sth->bindValue(':'.$key, $entry[$key], PDO::PARAM_STR);
}
$sth->execute();
or inside the foreach
$sth->bindValue(':'.$key, $value, PDO::PARAM_STR);
Since your keys are (username, password, email) their keynames will be initiated to $key variable, and their values to the $value variable. in the first case it will produce:
$sth->bindValue(':username', $entry['username'], PDO::PARAM_INT);
$sth->bindValue(':password', $entry['password'], PDO::PARAM_STR);
$sth->bindValue(':email', $entry['email'], PDO::PARAM_STR);
Which will be evaluated to:
$sth->bindValue(':username', $_POST['username'], PDO::PARAM_INT);
$sth->bindValue(':password', $_POST['password'], PDO::PARAM_STR);
$sth->bindValue(':email', $_POST['email'], PDO::PARAM_STR);
In the second case it will be directly evaluated.
Have in mind it's completely unacceptable to dynamically create the column names in the query. And you have to reason to do it. However, not a full query is also hard to be read from the other developers. It's enough for you to dynamically create the bound values. You can make a method do it for you. For instance, if you column names in the query are the same way aliased, as the names of the input fields, you will have nothing more to do, but to execute the query.
Let's say you have that helper method:
Class DBConnect {
private $_driver = "mysql";
private $_dbname = "xxxx";
private $_host = "xxxx";
private $_user = "xxxx";
private $_password = "xxxx";
private $_port = 3306;
private $_dbh;
public function __construct($driver = NULL, $dbname = NULL, $host = NULL, $user = NULL, $pass = NULL, $port = NULL) {
$driver = $driver ?: $this->_driver;
$dbname = $dbname ?: $this->_dbname;
$host = $host ?: $this->_host;
$user = $user ?: $this->_user;
$pass = $pass ?: $this->_password;
$port = $port ?: $this->_port;
try {
$this->_dbh = new PDO("$driver:host=$host;port=$port;dbname=$dbname", $user, $pass);
$this->_dbh->exec("set names utf8");
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function query($sql) {
$sth = $this->_dbh->prepare($sql);
foreach ($_REQUEST as $key => $value) {
if(is_int($value)) {
$param = PDO::PARAM_INT;
} elseif(is_bool($value)) {
$param = PDO::PARAM_BOOL;
} elseif(is_null($value)) {
$param = PDO::PARAM_NULL;
} elseif(is_string($value)) {
$param = PDO::PARAM_STR;
} else {
$param = FALSE;
}
$sth->bindValue(":$key", $value, $param);
}
$sth->execute();
$result = $sth->fetchAll();
return $result;
}
}
So, lets say in another class you have a lot of queries, separated by methods:
public function getFirstQuery() {
$sql = "SELECT
col1, col2
FROM table1
WHERE col3 = :col3;";
$query = $this->_db->query($sql);
return $query;
}
public function inserSecondquery() {
$sql = "INSERT INTO
`table1`
(col1, col2)
VALUES
((SELECT
id
FROM table2
WHERE col8 = :col8), :post_field_5);";
$query = $this->_db->query($sql);
return $query;
}
Assuming you have called these queries the query() method which also fetches the data, the select one you can foreach to retrieve the data, and the insert one you can just call, to insert data. The only rule here is the post fields should be named same way, for example <input name="post_field_5" />
You can also take a look here: PDO Dynamic Query Building
OK, it seems you need to find library for active record like the ones CodeIgniter uses, or... use CodeIgniter.
From the official documentation:
http://ellislab.com/codeigniter/user-guide/database/helpers.html
$this->db->insert_string();
This function simplifies the process of writing database inserts. It
returns a correctly formatted SQL insert string. Example: $data =
array('name' => $name, 'email' => $email, 'url' => $url);
$str = $this->db->insert_string('table_name', $data);
The first parameter is the table name, the second is an associative
array with the data to be inserted. The above example produces: INSERT
INTO table_name (name, email, url) VALUES ('Rick', 'rick#example.com',
'example.com')
So, in your case, you can have something like this:
<form action="" method="post">
<input type="text" name="username" value="testUser123" />
<input type="password" name="password" value="yourPass666" />
<input type="text" name="email" value="email#example.com" />
<input type="submit" value="submit" />
</form>
<?php
//... extending CI
//... opening a method
$table = 'data';
//comming from somewhere, let's dynamically populated array but for testing purpose I will hardcode:
$columns('username', 'password', 'email');
foreach($columns as $column) {
$data[$column] = $_POST[$column]; // this will produce $data=array('username'=>$_POST['username'],password=....);
}
$str = $this->db->insert_string($table, $data);
?>
If you submit the form in the beginning, you will have:
INSERT INTO data (username, password, email) VALUES ('testUser123', 'yourPass666', 'email#example.com');
The whole active record class doc (insert chosen here)
http://ellislab.com/codeigniter/user-guide/database/active_record.html#insert
If you don't have to stick to the for loop, I would suggest a foreach, which should be easier (I know the little problems with for too).
foreach ($element in $array)
{
code execution here
}
Your array element is then stored in the $element (or as you like to name it) and you can execute the command found there.
Is this what you're looking for or did I get you wrong?

How to insert multiple rows in a mysql database at once with prepared statements?

I am trying to use staticsanĀ“s answer in this question for prepared statements.
Lets take this example:
$stmt = $mysqli->prepare("INSERT INTO something (userid, time, title) VALUES (?, ?, ?)");
$stmt->bind_param('iis', $userid, time(), $title);
$stmt->execute();
In staticsanĀ“s answer imploding the array is adding all the values into the mysql statement so that in the end we can insert multiple data into the database with just one statement.
How would this be done in my example?
This is completely valid:
$stmt = $mysqli->prepare("INSERT INTO something (userid, time, title) VALUES (?, ?, ?)");
$stmt->bind_param('iis', $userid, time(), $title);
$stmt->execute();
$stmt->bind_param('iis', $userid, time(), $title);
$stmt->execute();
$stmt->bind_param('iis', $userid, time(), $title);
$stmt->execute();
$stmt->bind_param('iis', $userid, time(), $title);
$stmt->execute();
You can foreach over your array of values to insert and bind and execute each time. It wont be quite as fast as the bulk insert in the example you linked, but it will be more secure.
You can build prepared statement using code as mentioned here,
PDO Prepared Inserts multiple rows in single query
PHP logic will be sort of like,
/**
* Insert With Ignore duplicates in Mysql DB.
*/
public static function insertWithIgnore($em, $container, $tableName, $fields, $rows)
{
$query = "INSERT IGNORE INTO $tableName (`" . implode('`,`', $fields) . "`) VALUES ";
$placeHolr = array_fill(0, count($fields), "?");
$qPart = array_fill(0, count($rows), "(" . implode(',', $placeHolr) . ")");
$query .= implode(",", $qPart);
$pdo = self::getPDOFromEm($em, $container);
$stmt = $pdo->prepare($query);
$i = 1;
foreach ($rows as $row) {
$row['created_at'] = date("Y-m-d H:i:s");
foreach ($fields as $f) {
if (!isset($row[$f])) {
$row[$f] = null;
}
$stmt->bindValue($i++, $row[$f]);
}
}
$result = $stmt->execute();
if ($result == false) {
$str = print_r($stmt->errorInfo(), true);
throw new \Exception($str);
}
$stmt->closeCursor();
$pdo = null;
}
/**
* Replace old rows in Mysql DB.
*/
public static function replace($em, $container, $tableName, $fields, $rows, $extraFieldValues = null)
{
if ($extraFieldValues != null) {
$fields = array_unique(array_merge($fields, array_keys($extraFieldValues)));
}
$query = "REPLACE INTO $tableName (`" . implode('`,`', $fields) . "`) VALUES ";
$placeHolr = array_fill(0, count($fields), "?");
$qPart = array_fill(0, count($rows), "(" . implode(',', $placeHolr) . ")");
$query .= implode(",", $qPart);
$pdo = self::getPDOFromEm($em, $container);
$stmt = $pdo->prepare($query);
$i = 1;
foreach ($rows as $row) {
if ($extraFieldValues != null) {
$row = array_merge($row, $extraFieldValues);
}
foreach ($fields as $f) {
$stmt->bindValue($i++, $row[$f]);
}
}
$stmt->execute();
if (!$stmt) {
throw new \Exception("PDO::errorInfo():" . print_r($stmt->errorInfo(), true));
}
$stmt->closeCursor();
$pdo = null;
}

Categories