I need to insert array data into MySQL DB. My code is provided below. The problem is that query is equal to
INSERT INTO MyTab (Array) VALUES
(Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array)
So, why do I get Array instead of array values?
$columns = array();
$values = array();
$columns[] = array('Num','appearanceTime');
$curr_time = new DateTime();
while($row=mysql_fetch_assoc($result_arr)) {
$values[] = array($row['Num_arr'],$curr_time);
}
$cols = implode(",",$columns);
$vals = implode(",",$values);
$query = "INSERT INTO `MyTab` ($cols) VALUES ($vals)";
UPDATE
This code returns Internal Server Error at the line $vals = implode(...).
$columns = array('Num','appearanceTime','earliestTime');
$values = array();
$curr_time = new DateTime();
while($row=mysql_fetch_assoc($result_arr)) {
$values[] = array($row['Num_arr'],$curr_time,$row['ETA']);
}
$cols = implode(",",$columns);
function get_values($arr) {
return '(' . implode(',', $arr) . ')';
}
$vals = implode(',', array_map('get_values', $values));
$query_queue = "INSERT INTO `MyTab` ('" . $cols . "') VALUES ('" . $vals . "')";
The values inside the arrays are arrays. You need to implode each of them, too:
$vals = implode(',', array_map(function($arr) {
return '(' . implode(',', $arr) . ')';
}, $values));
As for the columns, I think you want:
$columns = array('Num','appearanceTime');
$values = array();
Not:
$columns = array();
$values = array();
$columns[] = array('Num','appearanceTime');
You'll also need to quote everything to put it in the query. You should use PDO or MySQLi and prepared statements instead of mysql_ if you can.
Given PHP 5.2, the first example needs to be changed to:
function implode_comma($arr) {
return '(' . implode(',', $arr) . ')';
}
# ...
$vals = implode(',', array_map('implode_comma', $values));
Related
I am attempting to dynamically create an INSERT statement based on JSON key/value pairs where the $key is the database field of string or integer data type and $value is an integer or string. I haven't had issues inserting numeric strings into Postgres before but it is failing.
Example:
$json = '{"stringField":"string","intString":"42"}';
$columns = $values = '';
foreach (json_decode($json, true) as $key => $value) {
if ($value != NULL) {
$columns .= $key . ', ';
$values .= "'" . $value . "', ";
}
}
$query = ('INSERT INTO table ('.rtrim($columns, ', ').') VALUES ('.trim($values, ', ').');');
This is cleaner PHP:
$json = '{"stringField":"string","numberField":"42"}';
$columns = $values = '';
foreach (json_decode($json, true) as $key => $value) {
if ($value !== NULL) {
$columns .= $key . ', ';
$values .= is_numeric($value) ? $value : "'" . $value . "', ";
}
}
$query = 'INSERT INTO table ('.rtrim($columns, ', ').') VALUES ('.trim($values, ', ').');';
Please think about escaping your values.
The issue turned out to be that one of the values was actually a float numeric string failing on insert into an integer field, rounding the value if it is a numeric string solves this. The is_numeric check avoids string fields being converted to 0.
Solution:
$json = '{"stringField":"string","floatString":"42.0","intString":"42"}';
$columns = $values = '';
foreach (json_decode($json, true) as $key => $value) {
if ($value != NULL) {
$columns .= $key . ', ';
$values .= is_numeric($value) ? round($value) . "," : "'" . $value . "', ";
}
}
$query = ('INSERT INTO table ('.rtrim($columns, ', ').') VALUES ('.trim($values, ', ').');');
how to add comma in query for next item? Add more details to the question.
// Indented the codes to make it more readable
$participants = [602, 600];
$query = array();
$query[] = 'INSERT INTO ' .
$db->nameQuote( '#__social_conversations_participants' );
$query[] = '(' . $db->nameQuote( 'conversation_id' ) .',' .
$db->nameQuote( 'user_id' ) . ',' . $db->nameQuote( 'state' ) . ')';
$query[] = 'VALUES';
foreach( $participants as $userId ){
$query[] = '(' . $db->Quote( $conversationId ) . ',' .
$db->Quote( $userId ) . ',' . $db->Quote( 1 ) . ')';
//this is not working because next() in this case always return
false
// Indented the codes to make it more readable
if( next( $participants ) !== false ){
$query[] = ',';
}
}
// Glue query back.
$query = implode( ' ' , $query );
var_dump($query);exit;
Found solution from here: PHP: Insert separated comma string value with as multiple array value Into MySql
<?php
$myString = "Red,Blue,Black";// incoming string comma names
$myArray = explode(',', $myString);
print_r($myArray);
$sql = "INSERT INTO `cat_interest`(`id`,`categories`) VALUES";
foreach($myArray as $value){
$sql .= " (1, '{$value}'),";
}
echo rtrim($sql, ',');
public function update($id, $table, $data, $exclude = array()){
$query = "UPDATE $table SET";
$fields = $values = array();
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . $this->db->real_escape_string($data[$key]) . "'";
}
$fields = implode(" ", $fields);
$values = implode(" ", $values);
$query .= $fields . "=" . $values . ",";
}
$query = $query . "WHERE id = '".$id."' ";
if(!$this->db->query($query)){
echo "Something wrong with query ";
}
else{
echo "successfully updated";
}
}
Got error
Fatal error: [] operator not supported for strings
Tweaked code from add function which worked. Wanted to have fields and values updated dynamically without using variables, i.e. $_POST['address'].
$query .= $fields . "=" . $values . ", ";
seem not to be working. Not sure what cause the error: Fatal error: [] operator not supported for strings. How to insert field = value in sql query?
Use like this
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$query .= $key . "='" . $data[$key] . "' ,";
}
}
$query = substr($query,0,strlen($query)-1);
$query = $query . " WHERE id = '".$id."' ";
Look at the foreach loop!!!
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . $this->db->real_escape_string($data[$key]) . "'";
}
$fields = implode(" ", $fields); // Mistake done here
$values = implode(" ", $values); // Mistake done here
$query .= $fields . "=" . $values . ",";
}
Change your those two line and the next line outside the loop. May be this solve your problem.
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . $this->db->real_escape_string($data[$key]) . "'";
}
}
$fields = implode(" ", $fields);
$values = implode(" ", $values);
$query .= $fields . "=" . $values . ",";
Follow my code. Where no need implementation implode() function. I have changed your function code. try it.
public function update($id, $table, $data, $exclude = array()){
$query = "UPDATE $table SET";
$fields = $values = array();
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$queryArr[] = $key . "='" . $this->db->real_escape_string($data[$key]);
}
}
$query = implode(" ,", $queryArr);
$query = $query . "WHERE id = '".$id."' ";
if(!$this->db->query($query)){
echo "Something wrong with query ";
}
else{
echo "successfully updated";
}
}
how i can make a insert using this fuctions
I m learning php, as using this functions (mysqli abstract) but after update wont work any more.
/** insert data array */
public function insert(array $arr)
{
if ($arr)
{
$q = $this->make_insert_query($arr);
$return = $this->modifying_query($q);
$this->autoreset();
return $return;
}
else
{
$this->autoreset();
return false;
}
}
complement
/** insert query constructor */
protected function make_insert_query($data)
{
$this->get_table_info();
$this->set_field_types();
if (!is_array(reset($data)))
{
$data = array($data);
}
$keys = array();
$values = array();
$keys_set = false;
foreach ($data as $data_key => $data_item)
{
$values[$data_key] = array();
$fdata = $this->parse_field_names($data);
foreach ($fdata as $key => $val)
{
if (!$keys_set)
{
if (isset($this->field_type[$key]))
{
$keys[] = '`' . $val['table'] . '`.`' . $val['field'] . '`';
}
else
{
$keys[] = '`' . $val['field'] . '`';
}
}
$values[$data_key][] = $this->escape($val['value'], $this->is_noquotes($key), $this->field_type($key), $this->is_null($key),
$this->is_bit($key));
}
$keys_set = true;
$values[$data_key] = '(' . implode(',', $values[$data_key]) . ')';
}
$ignore = $this->ignore ? ' IGNORE' : '';
$delayed = $this->delayed ? ' DELAYED' : '';
$query = 'INSERT' . $ignore . $delayed . ' INTO `' . $this->table . '` (' . implode(',', $keys) . ') VALUES ' . implode(',',
$values);
return $query;
}
before update this class i used to insert data like this
$db = Sdba::table('users');
$data = array('name'=>'adam');
$db->insert($data);
this method of insert dont works on new class.
if i try like this i got empty columns and empty values.
thanks for any help
complete class download http://goo.gl/GK3s4E
Try using set instead of insert:
$users = Sdba::table('users');
$user['name'] = 'Alvaro';
$users->set($user);
I need to add data in my database and one way or the other the format must be like,
0 - 0 or 1 - 5
i have tryed =>
mysqli_real_escape_string();
but did not work.
i have also tryed changing the sign to / , * , +, exp.
PHP
$dataBase->_insertDataBase('tableNaam', $input);
function _insertDataBase($tabel,$input){
$velden='';
$waarden='';
$i=0;
foreach($input AS $key=>$value){
$i=$i+1;
if($i !== count($input)){
$a=', ';
}else{
$a='';
}
$velden.=$key.$a;
$waarden.=$value.$a;
unset($a);
}
$sql = "INSERT INTO `$tabel`($velden) VALUES ($waarden)";
$this->_conn()->query($sql);
}
The problem is your SQL statement is giving the equation 5-1 as a value, so the server is doing the math and inserting 4 just like you told it to. You need tell it that it's a literal string by surrounding the values with apostrophe's (i.e. '5-1').
Replace:
foreach ($input AS $key => $value) {
$i = $i + 1;
if ($i !== count($input)) {
$a = ', ';
} else {
$a = '';
}
$velden .= $key . $a;
$waarden .= $value . $a;
unset($a);
}
With:
$velden = array();
$waarden = array();
foreach ($input AS $key => $value) {
$velden[] = $key;
$waarden[] = $value;
}
$velden = implode(',', $velden);
$waarden = "'" . implode("','", $waarden) . "'";
Or possibly even:
$velden = array_keys($input);
$waarden = array_values($input);
$velden = implode(',', $velden);
$waarden = "'" . implode("','", $waarden) . "'";