Modify syntax of this function to exclude several arrays instead of one - php

I'm a newbie to PHP and don't know how to modify the syntax of this function so that it can be used to exclude several arrays instead of only one. This code automatically INSERTS every value that's input in a form without having to specify the fields and excludes one array (called 'submit'), and is a slightly modified version of code that I found at http://www.abeautifulsite.net/blog/2007/10/inserting-an-array-into-a-mysql-database-table/
I have several arrays which are being posted that I want to exclude from my INSERT function since they are either being processed and inserted separately or trigger where the user is redirected once the form is processed.
function mysql_insert_array($db, $data, $exclude = array()) {
$fields = $values = array();
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
}
}
$fields = implode(",", $fields);
$values = implode(",", $values);
if( mysql_query("INSERT INTO `$db` ($fields) VALUES ($values)") ) {
} else {
return array( "mysql_error" => mysql_error() );
}
}
$result = mysql_insert_array("db", $_POST, "submit");

The exclude argument could be an array of array:
function mysql_insert_array($db, $data, $excludes = array()) {
$fields = $values = array();
if( !is_array($excludes) ) $excludes = array($excludes);
foreach($excludes as $exclude ) {
$data = array_diff_assoc($data, $exclude);
}
foreach( array_keys($data) as $key ) {
$fields[] = "`$key`";
$values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
}
$fields = implode(",", $fields);
$values = implode(",", $values);
if( !mysql_query("INSERT INTO `$db` ($fields) VALUES ($values)") ) {
return array( "mysql_error" => mysql_error() );
}
}
Then, you could use it like this :
$array1 = array('toto', 'titi', 'tata');
$array2 = array('submit', 'foo');
$parent_array = array ($array1, $array2);
$result = mysql_insert_array("db", $_POST, $parent_array);

Related

insert array of values into a database using SQL query?

I have a PHP array of the column names in my SQL table. I also have an array of the values I want to assign to these columns. How do I put this in an SQL query. At present im writing out each column title like so:
$query = "INSERT INTO `first_page_data`(`a`, `b`, `c`, `d`, `e`, `f`, `g`, `h`)
VALUES ('$1','$2','$3','$4','$5','$6','$7','$8')";
But there must be a way of just using the arrays?
As an extra, is there a way of defining key/value pairs to keep the two pairs of data together, and then using these to insert into the database? how is this formatted in the SQL query?
Here's another similar solution.
Code:
<?php
function mysql_insert_array($table, $data, $exclude = array()) {
$fields = $values = array();
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
}
}
$fields = implode(",", $fields);
$values = implode(",", $values);
if( mysql_query("INSERT INTO `$table` ($fields) VALUES ($values)") ) {
return array( "mysql_error" => false,
"mysql_insert_id" => mysql_insert_id(),
"mysql_affected_rows" => mysql_affected_rows(),
"mysql_info" => mysql_info()
);
} else {
return array( "mysql_error" => mysql_error() );
}
}
?>
Example usage:
<?php
// Open database here
// Let's pretend these values were passed by a form
$_POST['name'] = "Bob Marley";
$_POST['country'] = "Jamaica";
$_POST['music'] = "Reggae";
$_POST['submit'] = "Submit";
// Insert all the values of $_POST into the database table `artists`, except
// for $_POST['submit']. Remember, field names are determined by array keys!
$result = mysql_insert_array("artists", $_POST, "submit");
// Results
if( $result['mysql_error'] ) {
echo "Query Failed: " . $result['mysql_error'];
} else {
echo "Query Succeeded! <br />";
echo "<pre>";
print_r($result);
echo "</pre>";
}
// Close database
?>
Source: Inserting An Array into a MySQL Database Table
//Insert ( var , Array )
function insert($table, $inserts) {
$values = array_map('mysql_real_escape_string', array_values($inserts));
$keys = array_keys($inserts);
return mysql_query('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')');
}
/* Samples
insert('first_page_data', array(
'a' => 'Just Persian Gulf',
'b' => 'DB9',
'c' => '2009'
));
*/
it's good And Rapid!
Using PHP:
Getting your values into an array as $key => $value depends on the situation, but manually it would happen like so:
$array = array(`a` => '$1',`b` => '$2', ...and so on); //I am assuming that $ is not a variable indicator since it is inside single quotes.
There are a variety of array functions that can help you if you have existing arrays that you would rather manipulate to create the final array.
Once you have it, however:
$query = 'INSTERT INTO `first_page_data` (';
foreach ($array as $key => $value) {
$query .= '`' . $key . '`';
}
$query .= ') VALUES (';
foreach ($array as $value) {
$query .= '`' . $value . '`';
}
$query .= ')';
The code runs a foreach on the array twice, once to get the key and append it to the appropriate part of the string, and the other to add the corresponding values.
Try serialize() before the INSERT and unserialize() to get the array after a SELECT.
You need only one field to insert all the data.
http://ca1.php.net/manual/fr/function.serialize.php
http://ca1.php.net/manual/fr/function.unserialize.php
# Insert this array
$arr = array("sounds" => "one", "sound" => "two", "big" => "blue");
function addQuotes($str){
return "'$str'";
}
# Surround values by quotes
foreach ($arr as $key => &$value) {
$value = addQuotes($value);
}
# Build the column
$columns = implode(",", array_keys($arr));
# Build the values
$values = implode(",", array_values($arr));
# Build the insert query
$query = "INSERT INTO table (".$columns.") VALUES (".$values.")";
echo $query;
// returns
INSERT INTO table (sounds,sound,big) VALUES ('one','two','blue')

array to string php

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).")";

how to store multiple array values with using foreach?

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);

MYSQL to JSON for Autocomplete jQueryUI

My code below show what I'm doing. Basically the aim is to retrieve data from a database and convert it to a JSON format for jQueryUI. With the method below and a method that didn't use the array_to_json function I was able to get JSON data returned. Eg.:
[ { "name": "Kurt Schneider" }, { "name": "Sam Tsui" }, { "name": "Christina Grimmie" } ]
But the issue is that it still doesn't function with the autocomplete. I replaced the below code with the search.php that was provided with the example, so it's obviously an issue with this code.
I began with only this code:
<?php
include 'connect.php';
mysql_select_db("database", $con);
$search = mysql_query("SELECT name FROM artist");
$rows = array();
while($row = mysql_fetch_assoc($search)) {
$result[] = $row;
}
print json_encode($result);
?>
Which achieved affectively the same results as the below code (besides some differences in spacing):
(The array_to_json function was copied direct from the example).
<?php
include 'connect.php';
mysql_select_db("database", $con);
$search = mysql_query("SELECT name FROM artist");
$rows = array();
while($row = mysql_fetch_assoc($search)) {
$result[] = $row;
}
function array_to_json( $array ){
if( !is_array( $array ) ){
return false;
}
$associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
if( $associative ){
$construct = array();
foreach( $array as $key => $value ){
// We first copy each key/value pair into a staging array,
// formatting each key and value properly as we go.
// Format the key:
if( is_numeric($key) ){
$key = "key_$key";
}
$key = "\"".addslashes($key)."\"";
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "\"".addslashes($value)."\"";
}
// Add to staging array:
$construct[] = "$key: $value";
}
// Then we collapse the staging array into the JSON form:
$result = "{ " . implode( ", ", $construct ) . " }";
} else { // If the array is a vector (not associative):
$construct = array();
foreach( $array as $value ){
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "'".addslashes($value)."'";
}
// Add to staging array:
$construct[] = $value;
}
// Then we collapse the staging array into the JSON form:
$result = "[ " . implode( ", ", $construct ) . " ]";
}
return $result;
}
echo array_to_json($result);
?>
<?php
include 'connect.php';
mysql_select_db("database", $con);
$search = mysql_query("SELECT name FROM artist");
$rows = array();
while($row = mysql_fetch_assoc($search)) {
//don't add the array, just the name.
$result[] = $row["name"];
}
print json_encode($result);
?>
The code above should return the JSON
["Kurt Schneider", "Sam Tsui", "Christina Grimmie"]

Concatenation of string with a specific array elements

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);
}

Categories