Is there function encoding an associative array to use in a mySQL INSERT command?
This way you could do:
$array = mysql_fetch_assoc($result);
$array['key'] = 'updated_value';
mysql_query('INSERT INTO table ' . mysql_encode_assoc($array));
mysql_encode_assoc input:
array(
'name' => 'bob',
'vehicle' => 'car'
)
mysql_encode_assoc output:
'(name, vehicle) VALUES(bob, car)'
There is now:
function mysql_encode_assoc($array) {
$kenc = Array();
$venc = Array();
foreach($array as $k=>$v) {
$kenc[] = "`".mysql_real_escape_string($k)."`";
if( $v === null) $venc[] = "NULL";
else $venc[] = '"'.mysql_real_escape_string($v).'"';
}
$keys = "(".implode(",",$kenc).")";
$vals = "(".implode(",",$venc).")";
return $keys." VALUES ".$vals;
}
There's no built in function that I'm aware of. But you can quite easily make on using array_keys() and array_values().
No built-in function.
$sql = array();
foreach ($anArray as $f=>$v) $sql[] = "`{$f}`" = "'".mysql_real_escape_string($v)."'";
$query = "INSERT INTO table SET ".join(",", $sql);
Related
I want to insert an array ($array) into a Mysql table (notification), I tried this but nothing is entering. How do I solve this?
$select = "SELECT * FROM addclique WHERE adder_id = :session_id";
$param1 = array ('session_id' => $_SESSION['id']);
$cliques = $db->query($select, $param1);
foreach($cliques as $key)
{
$array[] = $key['clique_id'];
}
$array[] = $key['clique_id'];
$notijfy = new Notification();
$notijfy->addCircle($array);
function addCircle($id_involve){
$escaped_values = array_map('mysql_real_escape_string', array_values($array));
$sql2 = "INSERT INTO notification(id_involve) VALUES (:id_involve)";
$param2 = array ('id_involve' => implode(", ", $escaped_values));
$result2 = $this->db->query ($sql2, $param2);
}
There are several ways.
I would just do something simple like this:
foreach($cliques as $key){
$array[] = $key['clique_id'];
}
$notijfy = new Notification();
$notijfy->addCircle($array);
function addCircle($array){
$insert_string = '';
$count = 0;
foreach ($array as $k => $v){
$count++;
${$k} = mysqli_real_escape_string($this->db, $v);
$insert_string .= "(" . ${$k} . ")";
if ($count < sizeof($array)){
$insert_string .= ",";
}
}
$sql2 = "INSERT INTO notification(id_involve) VALUES $insert_string;";
$result2= $this->db->query ($sql2, $param2);
}
Your major error is that you are trying to pass ($passing an array when calling the function, but in the function itself your argument is listed as $id_involve, when you obviously need an $array variable that you are using in the function itself. I also can't understand why are you trying to add an element to the $array variable outside of foreach loop in the beginning. Doesn't make any sense.
Instead of $this->db just use your connection variable.
Currently, I have this dictionary object in my PHP script that was posted to my PHP implemented server through my iOS app:
{"command":"save","classname":"GameScore","cheatMode":"0","playerName":"SeanPlott","score":"1337"}
Now I need to create a MySQL table based off the data...
Here is my attempt to parse the data but all i get are the objects, not the keys...
foreach( $text as $stuff ) {
if( is_array( $stuff ) ) {
echo json_encode($stuff);
foreach( $stuff as $thing ) {
echo json_encode($thing);
}
} else {
echo json_encode($stuff);
}
}
Heres the result... "save""GameScore""0""SeanPlott""1337"
This is what I plan on making as a query
$result = query("INSERT INTO '%s'('%s', '%s', '%s', '%s')
VALUES('%s','%s','%s','%s')", $classname, $key1, $key2, $key3, $key4,
$object1, $object2, $$object3, $object4);
But the query should be dynamic, since the dictionary object can have 1 or many keys/objects...
So I figure I need to implement a parsing for loop that generates the query within the array and outputs a string which is the query...
Anyone have any ideas on how to fix my parser?
EDIT: heres my query function to handle MYSQL
function query() {
global $link;
$debug = false;
$args = func_get_args();
$sql = array_shift($args);
for ($i = 0; $i < count($args); $i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
$result = mysqli_query($link, $sql);
if (mysqli_errno($link) == 0 && $result) {
$rows = array();
if ($result !== true)
while ($d = mysqli_fetch_assoc($result))
array_push($rows,$d);
return array('result' => $rows);
} else {
return array('error' => 'Database error');
}
}
EDIT: Took me a while and a lot of help but I completed it... It takes care of the case of spaces in values and adds '`' characters around the keys if there corresponding value contains a space...
$raw_data = '{"command":"save","classname":"GameScore","cheatMode":"0","playerName":"Sean Plott","score":"1337"}';
$data = json_decode($raw_data, true);
$columns = array_slice(array_keys($data), 2);
array_shift($data);
$table_title = array_shift($data);
$values = array();
$num = 0;
foreach($data as $key => $value) {
if(strpos($value, " ") !== false) $columns[$num] = "`".$columns[$num]."`";
$num = $num + 1;
$values[] = (!is_numeric($value)) ? "'".$value."'" : $value;
}
$final_statement = "INSERT INTO " . $table_title . " (".implode(', ', $columns).") VALUES (".implode(', ', $values).")";
echo $final_statement;
If anyone sees any way to optimize this or make it cleaner... please feel free to post something!
Thanks again for everyones input!
You could just use a simple json_decode() and implode() to format it and prepare to insertion. Consider this example:
$raw_data = '{"command":"save","classname":"GameScore","cheatMode":"0","playerName":"SeanPlott","score":"1337"}';
$data = json_decode($raw_data, true);
$columns = array_keys($data); // get the columns
$final_statement = "INSERT INTO `table` (".implode(', ', $columns).") VALUES ('".implode("','", $data)."')";
echo $final_statement;
// outputs: INSERT INTO `table` (command, classname, cheatMode, playerName, score) VALUES ('save','GameScore','0','SeanPlott','1337')
EDIT: Suppose your columns has int types (especially the ones that has numeric values). For whatever reason it doesn't work, because of a mismatch, if so, you could probably do this. Consider this example:
$raw_data = '{"command":"save","classname":"GameScore","cheatMode":"0","playerName":"SeanPlott","score":"1337"}';
$data = json_decode($raw_data, true);
$columns = array_keys($data); // get the columns
$values = array();
foreach($data as $key => $value) {
// if not numeric, add quotes, if not, leave it as it is
$values[] = (!is_numeric($value)) ? "'".$value."'" : $value;
}
$final_statement = "INSERT INTO `table` (".implode(', ', $columns).") VALUES (".implode(', ', $values).")";
echo $final_statement;
// outputs: INSERT INTO `table` (command, classname, cheatMode, playerName, score) VALUES ('save', 'GameScore', 0, 'SeanPlott', 1337)
// Note: numbers has no qoutes
Hy every one I have this problem with an array I start like this...
$name = array($_POST['names']);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
$nameId[] = array('ids' => $row['id'] );
}
which gives me arrays like this..
$name:
array('0'=>'name1,name2,name3')
$names:
array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
how can I bring this in an string/form like this..
array('0'=>'61,6,1')
The idea is to save the ids to the Database.
Or is the a better more efficent way to get names from a form compare them with a database and get the ids back to save them to the Database?
many thanks in advance.
Change your assignment to this:
$nameId[] = $row['id'];
$name = array(name1,name2,name3);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
//below line changed
$nameId[] = $row['id'] ;
}
$string = implode(',',$nameId);
Try this :
$array = array(0=>array(0=>'61'),1=>array(0=>'6'),2=>array(0=>'1'));
$result = implode(",",call_user_func_array('array_merge', $array));
Please note : Here all are numeric keys, so change your code to :
$nameId[] = array($row['id'] ); , remove key 'ids' from here
Output :
61,6,1
Thats what I think
$nameId[] = $row['id'];
$stringId = implode(',',$name);
Use following function that will loop through array and find ids key and merge it into other array and after that when you calling this function it will impload it.
function CustomFindJoinArray( $needly, $array )
{
$results = array();
foreach ( $array as $key => $value )
{
if ( is_array( $value ) )
{
$results = array_merge($results, foo( $needly, $value ));
}
else if ( $key == $needly )
{
$results[] = $value;
}
}
return $results;
}
echo implode( ",", CustomFindJoinArray( "ids", $your_array ) );
where $your_array will be array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
OR More simple
foreach ($your_array as $key => $ids) {
$newArray[] = $array[$key]["ids"];
}
$string = implode(',', $newArray);
$ids = array();
foreach($nameId as $curr) {
$ids[] = $curr['ids'];
}
$str = "(".implode(",",$ids).")";
I want to use foreach in my following code only one time.and i need to paas two array value that is store_data and store_control_text to my database respective fields.Need suggestions for not using foreach loop for multiple array values..
$data = $_REQUEST['columns_one'];
$controlText = $_REQUEST['controlText'];
$store_control_text = explode(",",$controlText);
$store_data = explode(",",$data);
$query = "INSERT INTO formdetailstemp(FormId,ControlType,ControlText,ControlPara1,Mandatory) VALUES ";
$values = array(); //store all the new rows
foreach($store_data as $key =>$value){
$values[] = "('','".$value."','".$controlText."','".$controlPara."','".$mandatoryValue."')";
}
You can use array_map
foreach ( array_map(null, $store_control_text, $store_data) as $join ) {
list($text, $data) = $join;
//Do your stuff
}
See Simple Example
I believe you're looking for a MultipleIterator, which will iterate over both arrays easily with a single foreach loop:
$iter = new MultipleIterator;
$iter->attachIterator( new ArrayIterator( $store_control_text));
$iter->attachIterator( new ArrayIterator( $store_data));
foreach( $iter as $data) {
list( $a, $b) = $data;
var_dump( $a, $b);
// Do your SQL insert with $a and $b
}
you can use .implode();
foreach ($_POST['description'] as $row=>$name){
$description = $name;
$supplier = $_POST['supplier']; //Normal textbox value
$quantity = $_POST['quantity'][$row]; //Array text box 1
$partnumber = $_POST['partnumber'][$row]; // Array text box 2
$unitcost = $_POST['unitcost'][$row]; // Array text box 3
$sql_array[] = '("NULL","' . $partnumber . '","' . $supplier . '","'.$description.'", "'.$quantity.'","'.$unitcost.'")';
}
$query_single = 'INSERT INTO `inwards` (`id`, `partnumber`, `suppliers`, `description`, `quantity`,`unitcost`) VALUES '. implode(', ', $sql_array);
the given code below insert data from an array to the mysql table.as its not the full code but what i want to know is available in this code. my question is that there is a field in table named "image_url" but the data in that field only have image name and i want to append http://www.xxxxxx.com at the start of every image name and the replace it with the image name in the field but i dont know how to do that plz help me out
thanks in advance
function putTest($t) {
//$c = connect();
foreach ($t as $k => $v) {
$query = "INSERT INTO test (".implode(',',array_keys($v)).") VALUES ('".implode("','",$v)."')";
//echo "<pre>";
// echo $query;
$r = mysql_query($query);
}
//mysql_close($c);
}
This snippet should do what you want:
if (isset($v['image_url'])) {
$v['image_url'] = 'http://www.xxxxxx.com/' . $v['image_url'];
}
You can concatenate strings with the dot "."!
At first... Is your application protected against SQL injection? If not you should build two methods/functions like this using mysql_real_escape_string():
function sqlSafeKey( $key){
return '`' . mysql_real_escape_string( $key) . `'`;
}
function sqlSafeValue( $value){
return "'" . mysql_real_escape_string( $value) . "'";
}
And than use array_map() to escape your values like this:
$keys = array_map( 'sqlSafeKey', array_keys( $v));
$values = array_map( 'sqlSafeValue', $v);
About your question... The matzino's answer is correct and whole loop should look like this:
function putTest($t) {
//$c = connect();
foreach ($t as $k => $v) {
$v['image_url'] = 'http://www.xxxxxx.com/' . $v['image_url'];
$keys = array_map( 'sqlSafeKey', array_keys( $v));
$values = array_map( 'sqlSafeValue', $v);
$query = "INSERT INTO test (".implode(',', $keys).
") VALUES ('".implode("','",$values)."')";
//echo "<pre>";
// echo $query;
$r = mysql_query($query);
}
//mysql_close($c);
}