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, ',');
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, ', ').');');
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";
}
}
I have this in my DB: 3,14,12,13
Called $user['buddylist']
And this is my code, but the output is 1 instead of 4, What's wrong?
$prefix = '"';
$tag = explode( ',', $user['buddylist'] );
$foll = $prefix . implode( '",' . $prefix, $tag ) . '",';
$following = array($foll );
$nr = count($following);
The output of $foll is "3","14","12","13", :/
Because foll is a string when you do this:
$foll = $prefix . implode( '",' . $prefix, $tag ) . '",';
You are creating an array with one element when you do this:
$following = array($foll );
If you want to count, you need to count the array before you turn it into a string:
$prefix = '"';
$tag = explode( ',', $user['buddylist'] );
$nr = count($tag);
$foll = $prefix . implode( '",' . $prefix, $tag ) . '",';
$following = array($foll );
I would probably code it like this:
class Buddies {
private $buddies;
public function __construct($buddy_list_string) {
$this->buddies = explode( ',', $buddy_list_string);
}
public function count() {
return count($this->buddies);
}
public function __toString() {
return '"' . implode('","', $this->buddies) . '"';
}
public function toArray() {
return $this->buddies;
}
}
$buddies = new Buddies($user['buddylist']);
echo $buddies->count(); //4
echo $buddies; //"3","14","12","13"
foreach($buddies->toArray() as $buddy) {
//do stuff
}
I am trying to implode some variables and insert them into a MySql database, but for some reason it is not working. I have been trying for hours and I''m just not sure what I'm doing wrong.
If you can help it would be much appreciated.
$AddressString = "address1,address2,address3,address5,postcode";
$AddressSplit = explode( ",", $AddressString ); //split the address string
$StringLength = count( $AddressSplit ) - 1;
$s = 0; //trim any white spaces from the address string
while ( $s < count( $AddressSplit ) ) {
$AddressSplit[$s] = trim( $AddressSplit[$s] );
$s++;
}
//Create the Values to insert into DB
$MysqlValues = implode( "','", $AddressSplit );
$MysqlValues = "'$MysqlValues'";
$NumberVals = count( $AddressSplit );
$t = 1;
while ( $t < $NumberVals ) {
$ad[$i] = "add$i";
$t++;
}
$TableNames = implode( ", ", $ad );
mysql_query( "INSERT INTO pstc_add_main (" . $TableNames . ",add10,date)
VALUES (" . $MysqlValues . ",'$cdate')" );
}
Because you start making the field names 1 based, your are one field short!
In the end you must end with a equal number of fields and values.
Try this:
$t = 0;
while ( $t < $NumberVals ) {
$ad[$i] = "add$i";
$t++;
}
Or, if you do not want the first field to be "add", change it like this:
$t = 1;
while ( $t <= $NumberVals ) {
$ad[$i] = "add$i";
$t++;
}
Of course, it would have been a easy test to do:
$sql = "INSERT INTO pstc_add_main (" . $TableNames . ",add10,date)
VALUES (" . $MysqlValues . ",'$cdate')";
var_dump($sql);
mysql_query($sql);
Not tested,
I doubt you change,
$MysqlValues = implode("','", $AddressSplit);
to
$MysqlValues = implode(",", $AddressSplit);
Just use
$MysqlValues = implode( ",", $AddressSplit );
and try to edit the code like
mysql_query( "INSERT INTO pstc_add_main (".$TableNames." ,add10,date)
VALUES (" . $MysqlValues . ",$cdate)" );
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));