I got this error whatever format i changed, i have no idea what else causes of this. Can someone help me on this? My csv excel dateTime format is yyyy/mm/dd H:mm
$i = 0;
$len = count($map_column);
$insData = array();
foreach ($map_column as $key => $value) {
$i++;
if ($key == 'dateTime') {
$date = date_create_from_format('Y/m/d H:i:s', $row[$value]);
$timestamp = $date->getTimestamp();
$sql .= 'UNIX_TIMESTAMP('.$key . ') = "' . $timestamp . '"';
} else {
$sql .= $key . ' = "' . $row[$value] . '"';
}
$insData[$key] = $row[$value];
if ($i < $len) {
$sql .= ' AND ';
}
}
$result = mysqli_query($cons, $sql);
$r = mysqli_fetch_array($result);
$count = (int)$r['count'];
if ($count) {
return;
}
// pr($insData);
$columns = implode(", ",array_keys($insData));
$escaped_values = array_values($insData);
$values = implode("', '", $escaped_values);
$sql = "INSERT INTO hrar($columns) VALUES ('$values')";
if ($cons->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
I don't know why the query is not working, might be a slight error that I have missed. I'm try to insert data into a table column depending if it is a match or not. I know data is in my array but I suspect it the query I'm writing out that is giving me an error.
Here is my code:
$querytwo = 'INSERT INTO `' . $tablename . '` ' . ' (`' . $match_player_in_game . '`) ' . 'VALUES' . '(' . 'yes' . ')';
foreach ($player_fromsite as $match_player_in_game) {
for ($a = 0; $a < 11; $a++) {
if ($match_player_in_game == $home_players[$a]) {
// Insert a row of information into the table "example"
mysql_query($querytwo) or die(mysql_error());
} else {
}
}
}
The message is returning 'Undefined variable: match_player_in_game'.
you need to put your $querytwo inside the for() loop, then it will work for you
It should be
foreach ($player_fromsite as $match_player_in_game) {
$querytwo = 'INSERT INTO `' . $tablename . '` ' . ' (`' . $match_player_in_game . '`) ' . 'VALUES' . '(' . 'yes' . ')';
for ($a = 0; $a < 11; $a++) {
if ($match_player_in_game == $home_players[$a]) {
// Insert a row of information into the table "example"
mysql_query($querytwo) or die(mysql_error());
} else {
}
}
}
i am working on dynamic array i need to insert these array in the database.when i insert dynamic array into the database instead of inserting all rows it only inserting one row in the database.
below is the array that contain result
$asma[]=GA::select($ga->population,'total',3);
below is code for inserting multiple array in database table ga
<?php
//code not tested check it
//Logic is changed instead of for looping many times
$data = array();
$j = 0;
foreach($asma as $key => $value)
{
$i = 0;
foreach ( $value as $ind => $hObject )
{
if($i==0)
{
$data[$j]['fe'] = mysql_escape_string($hObject->Voltage);
}else{
$data[$j]['fe'.$i] = mysql_escape_string($hObject->Voltage);
}
$i++;
$data[$j]['fe'.$i] = mysql_escape_string($hObject->Duration);
$i++;
$data[$j]['fe'.$i] = mysql_escape_string($hObject->Number);
$i++;
}
$j++;
}// endforeach
//multiple array
foreach($data as $array)
{
//unique array
//$array3 = array_merge($Voltage,$Duration,$Number);
$fields = implode(',',array_keys($array));
//if you want append any new field append it
$fields .= ','.'timestamp,username';
$vals = "'".implode("','",array_values($array))."'";
//if you want append any new values append it
$vals .= ",'".time()."','".$login_session."'";
$q = "INSERT INTO ga (".$fields.") VALUES(".$vals.")";
$result = mysql_query($q);
if ( ! $result ) {
die( 'Insert failed ' . mysql_errno() . ' ' . mysql_error() );
}
}
whenever user enter 3 then after computation result will store in array asma after store result will store in table ga that should be three rows but only one row insert in the table and display instead of three same in case the user enter any value in the text box.
I'm not sure what you mean, i think is an insert statement like this:
INSERT INTO `ga` (`field1`, `field2`, `field3`, `etc`)
VALUES (value11, value21, value31, more_values1),
(value12, value22, value32, more_values2),
(value13, value23, value33, more_values3)
So you should use your foreach cycle to create the values statement.
$sql = "INSERT INTO `ga` (`voltage`, `duration`, `number`, `timestamp`, `username`) VALUES ";
$values = "";
foreach ($asma as $row) {
$values .= ($values != "" ? "," : "") . "(" .
"'" . $row['voltage'] . "', " .
"'" . $row['voltage'] . "', " .
"'" . $row['number'] . "', " .
"'" . time() . "', " .
"'" . $login_session . "'" .
"),";
}
$sql .= substr($values, 0, -1) . ";";
hi am having this trouble trying to save in multiple rows in the table "notification" with a for of customers table ids but it only save me one row this is my code:
$customers = tep_get_customers();
$count = 0;
for ($i=0, $n=sizeof($customers); $i<$n; $i++) {
$count ++;
$insert_str_cony .= $customers[$i]['id'];
$split_customers_id = explode("||", $insert_str_cony.'||', -1);
$values .= "('','" . tep_db_input('1') . "', now(), '" . tep_db_input($products_id) . "', '" . tep_db_input($split_customers_id[$count]) . "'),";
$db_values = substr_replace($values, '', -1, 1);
}
if ($action == 'insert_product') {
tep_db_query("insert into notifications (notify_id, prod_notify, notify_added, prod_id, customers_id) values ". $db_values);
} elseif ($action == 'update_product') {
tep_db_query("update notifications set prod_notify = '" . tep_db_input('1mod') . "', notify_last_mod = now(), prod_id = '" . $HTTP_GET_VARS['pID'] . "', customers_id = '" . tep_db_input($customers['customers_id']) . "'");
}
and this is the function tep_get_customers();
function tep_get_customers() {
$customers_query = tep_db_query("select distinct customers_id from " . TABLE_CUSTOMERS . "");
while ($customers = tep_db_fetch_array($customers_query)) {
$customers_array[] = array('id' => '||'.$customers['customers_id']);
}
return $customers_array;
}
plase need help!!! thanks!
That is because Insert + values insert one row in the database . (You can use Insert with a SELECT query to insert multiple rows using Insert command but that's not your case as I can see ).
Therefore you should provide a script containing multiple insert commands (an insert command for each customer) in order to insert multiple rows into the database.
I use Zend Framework in my project. I need to insert multiple records and I found that Zend_Db suprisingly slower thatn my_sql query (several times), that made me think I did something wrong.
Here are two examples.
Zend_Db_Adapter:
$startTime = microtime(true);
$db = Zend_Db_Table::getDefaultAdapter();
$db->beginTransaction();
$dateAdded = date('Y-m-d H:i:s');
$lastChanged = $dateAdded;
foreach ($importDataNamespace->data as $subscriberNum => $subscriber)
{
foreach ($fieldsMap as $fieldNumber => $fieldTag) {
if (isset($subscriber[$fieldNumber])) {
$subscriberData[$fieldTag] = $subscriber[$fieldNumber];
} else {
$subscriberData[$fieldTag] = '';
}
}
$query = 'INSERT INTO subscribers (list_id, account_id, email_address, first_name, last_name, date_added, last_changed) ' .
'VALUES (' . 52 . ', ' . 29 . ', ' . $db->quote($subscriberData['EMAIL']) . ', ' . $db->quote($subscriberData['FNAME']) .
', ' . $db->quote($subscriberData['LNAME']) . ', ' . $db->quote($dateAdded) . ', ' . $db->quote($lastChanged) . ')';
$db->query($query);
}
$db->commit();
$this->view->time = microtime(true) - $startTime;
Example with mysql_query:
$startTime = microtime(true);
$user = 'root';
$password = 'password';
$db = 'database';
$connect = #mysql_connect('localhost',$user,$password) or die("Failed to connect database");
#mysql_select_db($db) or die("Failed to select database");
$dateAdded = date('Y-m-d H:i:s');
$lastChanged = $dateAdded;
$result = mysql_query('SET autocommit = 0');
foreach ($importDataNamespace->data as $subscriberNum => $subscriber)
{
foreach ($fieldsMap as $fieldNumber => $fieldTag) {
if (isset($subscriber[$fieldNumber])) {
$subscriberData[$fieldTag] = $subscriber[$fieldNumber];
} else {
$subscriberData[$fieldTag] = '';
}
}
$query = 'INSERT INTO subscribers (list_id, account_id, email_address, first_name, last_name, date_added, last_changed) ' .
'VALUES (' . 52 . ', ' . 29 . ', \'' . mysql_real_escape_string($subscriberData['EMAIL']) . '\', \'' . mysql_real_escape_string($subscriberData['FNAME']) .
'\', \'' . mysql_real_escape_string($subscriberData['LNAME']) . '\', \'' . $dateAdded . '\', \'' . $lastChanged . '\')';
mysql_query($query);
}
$result = mysql_query('SET autocommit = 1');
$result = mysql_query('COMMIT;');
$this->view->time = microtime(true) - $startTime;
In the first case it took 14.8 seconds, in the second 3.7.
Could you tell me why does it happend and what do you do wrong?
If I delete any quote for Zend_Db it took 12 seconds from 14 with quote, but it's still much more slower than with mysql_query:
$startTime = microtime(true);
$db = Zend_Db_Table::getDefaultAdapter();
$db->beginTransaction();
$dateAdded = date('Y-m-d H:i:s');
$lastChanged = $dateAdded;
foreach ($importDataNamespace->data as $subscriberNum => $subscriber)
{
foreach ($fieldsMap as $fieldNumber => $fieldTag) {
if (isset($subscriber[$fieldNumber])) {
$subscriberData[$fieldTag] = $subscriber[$fieldNumber];
} else {
$subscriberData[$fieldTag] = '';
}
}
$query = 'INSERT INTO subscribers (list_id, account_id, email_address, first_name, last_name, date_added, last_changed) ' .
'VALUES (' . 52 . ', ' . 29 . ', \'' . $subscriberData['EMAIL'] . '\', \'' . $subscriberData['FNAME'] .
'\', \'' . $subscriberData['LNAME'] . '\', \'' . $dateAdded . '\', \'' . $lastChanged . '\')';
$db->query($query);
}
$db->commit();
$this->view->time = microtime(true) - $startTime;
Thank you for any information about this issue.
This code takes about 0.065 seconds with mysql_query:
$dateAdded = date('Y-m-d H:i:s');
$lastChanged = $dateAdded;
$startTime = microtime(true);
$result = mysql_query('BEGIN');
for ($i = 0; $i < 100; $i++) {
$email = 'test_ ' . $i . '#gmail.com';
$query = 'INSERT INTO subscribers (list_id, account_id, email_address, first_name, last_name, date_added, last_changed) ' .
'VALUES (' . 52 . ', ' . 29 . ', \'' . mysql_real_escape_string($email) . '\', \'' . mysql_real_escape_string($firstName) .
'\', \'' . mysql_real_escape_string($lastName) . '\', \'' . mysql_real_escape_string($dateAdded) . '\', \'' . mysql_real_escape_string($lastChanged) . '\')';
mysql_query($query);
}
$result = mysql_query('COMMIT');
$time = microtime(true) - $startTime;
echo 'Using mysql_query: ' . $time . '<br />';
exit();
Code with benchmark of Zend_Db_Adapter (I didn't even use quote in this case):
$db = Zend_Db_Table::getDefaultAdapter();
$db->getProfiler()->setEnabled(true);
$profiler = $db->getProfiler();
$startTime = microtime(true);
$db->beginTransaction();
for ($i = 0; $i < 100; $i++)
{
$email = 'test_' . $i . '#gmail.com';
$query = 'INSERT INTO subscribers (list_id, account_id, email_address, first_name, last_name, date_added, last_changed) ' .
'VALUES (' . 52 . ', ' . 29 . ', \'' . $email . '\', \'' . $firstName .
'\', \'' . $lastName . '\', \'' . $dateAdded . '\', \'' . $lastChanged . '\')';
$db->query($query);
}
$db->commit();
$time = microtime(true) - $startTime;
echo 'Time of transaction Zend_Db_Adapter query: ' . $time . '<br />';
echo 'Total time ' . $profiler->getTotalElapsedSecs() . '<br />';
$count = 0;
$totalTime = 0;
foreach ($profiler->getQueryProfiles() as $query) {
$count++;
$elapsedTime = $query->getElapsedSecs();
$totalTime += $elapsedTime;
echo $count . ' ' . $elapsedTime . ' ' . $query->getQuery() . '<br />';
}
echo 'Sum time: ' . $totalTime . '<br />';
Here are some results:
Time of transaction Zend_Db_Adapter query: 0.23094701767
Total time 0.0949234962463
1 0.00199699401855 connect
2 0.000336885452271 begin
3 0.000540018081665 INSERT INTO subscribers (list_id, account_id, email_address, first_name, last_name, date_added, last_changed) VALUES (52, 29, 'test_0#gmail.com', 'John', 'Clinton', '2011-01-28 15:25:21', '2011-01-28 15:25:21')
4 0.000504016876221 INSERT INTO subscribers (list_id, account_id, email_address, first_name, last_name, date_added, last_changed) VALUES (52, 29, 'test_1#gmail.com', 'John', 'Clinton', '2011-01-28 15:25:21', '2011-01-28 15:25:21')
It's very strange. The time of transacation to insert 100 records is 2.5 times more than executing of all queries.
If I try to meach the time of forming strings in the loop it (if we delete query) doesn't take so much time.
I think that one reason is that you execute $db->quote() too many times, which is unnecessary. Do you know that $db->quote() can take an array as its argument and you can basically reduce calls to $db->quote() to only one. In addition in your mysql_query version you do not escape $dateAdded and $lastChanged, while in zend_db version you do.
EDIT: Added an example below
$db = Zend_Db_Table::getDefaultAdapter();
$input = array(
'a' => "asd'lfksd",
'b' => "asdlfk'sdfasdf",
'c' => "asd fds f saf'sdfsd",
'd' => "asd fds f saf'sdfsd"
);
// separate calls to quote
$startTime = microtime(true);
$db->quote($input['a']);
$db->quote($input['b']);
$db->quote($input['c']);
$db->quote($input['d']);
$totalTime1 = microtime(true) - $startTime;
// one call to quote
$startTime = microtime(true);
$db->quote($input);
$totalTime2 = microtime(true) - $startTime;
// show results
var_dump("Sperate calls are ". $totalTime1/$totalTime2 . " times slower");
//output: string 'Sperate calls are 3.0875831485588 times slower' (length=46)
mysql_* functions are natives to PHP , so they are very fast.
Zend_Db_Adapter is working with PDO so you have a first absraction layer with PDO and a second with Zend_DB_Adapter.
More layer abstraction you 've got , more the code is slowing down.
That why the MVC framework in general are more slower than procedural code.
Try again your benchmark with prepared statement and a cache mechanism and you should be close of the mysql_* functions
This looks like you don't have a metadata cache in Zend_Db.