Insert array into a single field in a MYSQL database - php

I am creating a SELECT drown down list, I would like to have it loaded in 1 of 2 ways.
First way is pulling data from database with ID, name, and Value - This way will be loaded from other pages.
Second way, I would like to load from a Single line in the database with Name and Value. But I want to have that value be loaded with an array.
How do I load that array into the database?
$name = 'name';
$value = array( 'red' => 'Red', 'blue' => 'Blue' );
$SQL = 'INSERT INTO table_name (name, value) VALUES ($name,$value);
I expect when I run the SELECT * from table_name WHERE name = "name" to use that array in the value field right away.
With what "RakeshJakhar" said, to use the implode and explode onto $value
$value = array( 'red' => 'Red', 'blue' => 'Blue' );
print_r( $value );
echo "<br />";
echo implode( ",", $value );
echo "<br />";
$implode = implode( ",", $value );
$explode = explode( ',', $implode );
print_r( $explode );
Results:
Array ( [red] => Red [blue] => Blue )
Red,Blue
Array ( [0] => Red [1] => Blue )

You can use json_encode and json_decode
$value = array( 'red' => 'Red', 'blue' => 'Blue' );
$column = json_encode($value);
So the inserted value {"red":"Red","blue":"Blue"}
When you are fetching value use json_decode
$values = json_decode($column,true);

Related

How to join string after last array value? [duplicate]

This question already has answers here:
How add a link on comma separated multidimensional array
(2 answers)
Closed 7 months ago.
I am trying to generate a string from an array. Need to concatenate the array values with a small string AFTER the value. It doesn't work for the last value.
$data = array (
1 => array (
'symbol' => 'salad'
),
2 => array (
'symbol' => 'wine'
),
3 => array (
'symbol' => 'beer'
)
);
$symbols = array_column($data, 'symbol');
$string_from_array = join($symbols, 'bar');
echo($string_from_array);
// expected output: saladbar, winebar, beerbar
// output: saladbar, winebar, beer
You can achieve it a few different ways. One is actually by using implode(). If there is at least one element, we can just implode by the delimiter "bar, " and append a bar after. We do the check for count() to prevent printing bar if there are no results in the $symbols array.
$symbols = array_column($data, "symbol");
if (count($symbols)) {
echo implode("bar, ", $symbols)."bar";
}
Live demo at https://3v4l.org/ms5Ot
You can also achieve the desired result using array_map(), as follows:
<?php
$data = [
1 => ['symbol' => 'salad'],
2 => ['symbol' => 'wine'],
3 => ['symbol' => 'beer']
];
echo join(", ", array_map(
fn($v) => "{$v}bar",
array_column($data, 'symbol')
)
);
See live code
Array_map() takes every element of the array resulting from array_column() pulling out the values from $data and with an arrow function, appends the string "bar". Then the new array yielded by array_map has the values of its elements joined with ", " to form the expected output which is then displayed.
As a recent comment indicated you could eliminate array_column() and instead write code as follows:
<?php
$data = [
1 => ['symbol' => 'salad'],
2 => ['symbol' => 'wine'],
3 => ['symbol' => 'beer']
];
echo join(", ", array_map(
fn($row) => "{$row['symbol']}bar",
$data
)
);
See live code
Note while this 2nd way, may appear more direct, is it? The fact is that as array_map iterates over $data, the arrow function contains code that requires dereferencing behind the scenes, namely "$row['symbol']".
The join() function is an alias of implode() which
Returns a string containing a string representation of all the array
elements in the same order, with the glue string between each element.
So you need to add the last one by yourself
$data = array (
1 => array (
'symbol' => 'salad'
),
2 => array (
'symbol' => 'wine'
),
3 => array (
'symbol' => 'beer'
)
);
$symbols = array_column($data, 'symbol');
$string_from_array = join($symbols, 'bar');
if(strlen($string_from_array)>0)
$string_from_array .= "bar";
echo($string_from_array);
You can use array_column and implode
$data = array (
1 => array (
'symbol' => 'salad'
),
2 => array (
'symbol' => 'wine'
),
3 => array (
'symbol' => 'beer'
)
);
$res = implode("bar,", array_column($data, 'symbol'))."bar";
Live Demo
Try this:
$symbols = array_column($data, 'symbol');
foreach ($symbols as $symbol) {
$symbol = $symbol."bar";
echo $symbol;
}
btw, you can't expect implode to do what you expect, because it places "bar" between the strings, and there is no between after the last string you get from your array. ;)
Another way could be using a for loop:
$res = "";
$count = count($data);
for($i = 1; $i <= $count; $i++) {
$res .= $data[$i]["symbol"] . "bar" . ($i !== $count ? ", " : "");
}
echo $res; //saladbar, winebar, beerbar
Php demo

how to delete id from MySQL Database using query

I am trying to delete Id on SQL not working i got string(87) "DELETE FROM wp_availability WHEREidIN (Array,Array,Array,Array)"
get this kind value
if ( count( $remove ) > 0 ) {
$removeSQL = "DELETE FROM " . $this->table . " WHERE `id` IN (" .
implode( ",", $remove ) . ")";
if ( $wpdb->query( $removeSQL ) ) {
$saved = true;
}
}
Thanks in Advance
To expand on Vince0789's answer...
$remove looks to contain an array of arrays and not just an id string.
For example, $remove may be layed out as below;
[
[
'id' => 1,
'content' => "Foo"
],
[
'id' => 2,
'content' => "Bar"
],
]
What you will want to do is use array_column() on the $remove array to capture just the IDs from the array and then implode that new array and pass it to the query.
$to_remove = array_column($remove, 'id'); //assuming that id is the column you want
http://php.net/manual/en/function.array-column.php

How to use foreach loop using two array to get result

I have two array as follow
[1]=>Array(
[ingrediant]=>Array(
[A]=>Chicken [C]=>TomatoJuice
)
[price]=> 100
)
[2]=>Array(
[ingrediant]=>Array(
[A]=>Pork [C]=>LimeJuice
)
[price]=> 50
)
[3]=>Array(
[ingrediant]=>Array(
[B]=>Chille [C]=>TomatoJuice
)
[price]=>100
)
)
And
Array([A]=>Array([name]=>meat [code]=>001)
[B]=>Array([name]=>Vegetable [code]=>002)
[C]=>Array([name]=>Juice [code]=>003)
)
First Array Show the food combo and Second Array Show Type of the Ingredients
For example,
Chicken+tomatojuice Combo
Chicken is meat and tomatojuice is juice.
I would like to get the result as follow group by juice.
>Tomatojuice
-Meat:Chicken, price:100
-Vegetable:Chille, price:100
>LimeJuice
-Meat:Pork, price:100
How can I get these results by using php foreach. I have tried several time.Not Okay at all.
This code should solve your problem
Based on your array declaration :
$food_combo[] = array(
'ingrediant'=> array(
'A' => 'Chicken',
'C' => 'TomatoJuice'
),
'price'=>100
);
$food_combo[] = array(
'ingrediant'=> array(
'A' => 'Pork',
'C' => 'LimeJuice'
),
'price'=>50
);
$food_combo[] = array(
'ingrediant'=> array(
'B' => 'Chille',
'C' => 'TomatoJuice'
),
'price'=>100
);
$types['A'] = array('name'=>'meat','code'=>'001');
$types['B'] = array('name'=>'vegetable','code'=>'002');
$types['C'] = array('name'=>'juice','code'=>'003');
Here is the algorithmic :
$group_by = 'C';
$combo = $output = array();
foreach($food_combo as $food){
//array("A","B"....);
$missed = array_diff(
array_keys($food['ingrediant']),
isset($combo[$food['ingrediant'][$group_by]]) ?
$combo[$food['ingrediant'][$group_by]] : array()
);
if(count($missed)){
//remove initial group define as key
foreach(array_diff($missed,array($group_by)) as $type_code)
$output[$food['ingrediant'][$group_by]][] =
$types[$type_code]['name'] .
':' . $food['ingrediant'][$type_code] .
',' . 'price:' . $food['price'];
}
}
print_r($output);

Using an array value to retrieve from another array

I have created an array, one of the is intended to be a string used by php to display a field from a record retrieved from sqlite3.
My problem is that ... it doesn't.
The array is defined, "1" being the first database field, and "2" is the second database field:
EDIT : I have re-defined the problem as a script so you can see the whole thing:
//If I have an array (simulating a record retrieved from database):
$record = array(
name => 'Joe',
comments => 'Good Bloke',
);
//then I define an array to reference it:
$fields = array(
1 => array(
'db_index' => 'name',
'db_type' => 'TEXT',
'display' => '$record["name"]',
'form_label' => 'Name',
),
2 => array(
'db_index' => 'comments',
'db_type' => 'TEXT',
'display' => '$record["comments"]',
'form_label' => 'Comments',
),
);
//If I use the lines:
print "expected output:\n";
print " Name = " . $record["name"] ."\n";
print " Comments = " . $record["comments"] ."\n";
//I display the results from the $record array correctly.
//However if I try & use the fields array with something like:
Print "Output using Array values\n";
foreach($GLOBALS["fields"] as $field)
{
$label = $field['form_label'];
$it = $field['display'];
$line = "\"$label = \" . $it .\"\n\"";
print $line;
}
Output:
Expected output:
Name = Joe
Comments = Good Bloke
Output using Array values:
Name = $record["name"]
Comments = $record["comments"]
Don't call variable from string. Just concatenate it :
foreach($GLOBALS["fields"] as $field){
$label = $field['form_label'];
$it = $field['display'];
eval("$it = ".$it);
$line = $label." = ".$it."\n";
print $line;
}
Well, how do it looks ?

Algorithm to dynamically merge arrays [duplicate]

This question already has answers here:
Two arrays in foreach loop
(24 answers)
Closed 6 months ago.
I'm trying to create a INSERT statement for every row in a PHPExcel object. As I've struggled to iterate across the column (ie. go B1 C1 D1, get the values, and put them into an array), I've opted to get all the values for each column and put them into a multi-dimensional array that looks like this:
Array
(
[foo] => Array
(
[0] => 250
[1] => 247
[2] => 279
[3] => 249
)
[bar] => Array
(
[0] => AM PROV
[1] => AM PROV
[2] => AM PENS
[3] => AM PROV
)
[schoo] => Array
(
[0] => xxxx
[1] => yyy
[2] => zzz
[3] => aaa
)
)
I want to merge each of the arrays so that all the data at index 0 is in one array, etc. I've built a generic tool to allow you to select the columns you want from an uploaded spreadsheet. It needs to first merge the column data into a single array and then it should generate INSERT statements for each of the arrays. So the final deliverable is this:
INSERT INTO (foo, bar, schoo) VALUES (250, "AM PROV", "xxxx");
All help appreciated.
UPDATE: Hey all, thank you very much for your answers. I finally managed to get it working using row and cell iterators as per Mark's suggestion and it's working. I have a separate issue with it now, but I think it's something I can solve. Thanks again.
<?php
$uberArray = array(
"foo" => array(
0 => 250,
1 => 247,
2 => 279,
3 => 249,
),
"bar" => array(
0 => "AM PROV",
1 => "AM PROV",
2 => "AM PENS",
3 => "AM PROV",
),
"schoo" => array(
0 => "xxxx",
1 => "yyy",
2 => "zzz",
3 => "aaa",
)
);
$yourMysqlLink = mysql_connect('localhost', 'user', 'pass');
mysql_query('SET NAMES utf8'); // Adjust according to your encoding
$colNames = array_keys($uberArray);
$stringCols = array('bar', 'schoo');
$sqlInsertStr = 'INSERT INTO `your_table` (`'.implode('`, `', $colNames)."`) VALUES \n";
$rows = array();
// Not really for iterating the first array, we just need a loop
foreach ($uberArray[$colNames[0]] as $k => $v) {
$vals = array();
foreach ($colNames as $v2) {
$val = $uberArray[$v2][$k];
if (in_array($v2, $stringCols)) {
$val = "'".mysql_real_escape_string($val, $yourMysqlLink)."'";
}
$vals[] = $val;
}
$rows[] = "\t(".implode(', ', $vals).")";
}
$sqlInsertStr .= implode(",\n", $rows).';';
echo '<pre style="clear:both;">'.$sqlInsertStr.'</pre>'; ;
Note that you may need to do a few adjustments for performance reasons, if $uberArray is big (e.g. splitting the insert string into chunks). Or you can convert the data to CSV and use MySQL LOAD DATA INFILE method, which is real fast.
Not sure if this is what you were after but...
<?php
# Given this array
$arrays = array(
'foo' => array(
0 => 250,
1 => 247,
2 => 279,
3 => 249
),
'bar' => array(
0 => 'AM PROV',
1 => 'AM PROV',
2 => 'AM PENS',
3 => 'AM PROV'
),
'schoo' => array(
0 => 'xxxx',
1 => 'yyy',
2 => 'zzz',
3 => 'aaa'
)
);
# This code generates...
$fields = array();
$inserts = array();
foreach ($arrays as $k => $v) {
$fields[] = $k;
}
for ($i = 0; $i < count($arrays[$fields[0]]); $i++) {
$vals = array();
foreach ($fields as $field) {
$vals[] = $arrays[$field][$i];
}
$inserts[] = 'INSERT INTO (' . implode(',', $fields) . ') VALUES ("' . implode('","', $vals) . '")';
}
# This array
/* $inserts = array(
'INSERT INTO (foo, bar, schoo) VALUES ("250", "AM PROV", "xxxx")',
'INSERT INTO (foo, bar, schoo) VALUES ("247", "AM PROV", "yyy")',
'INSERT INTO (foo, bar, schoo) VALUES ("279", "AM PENS", "zzz")',
'INSERT INTO (foo, bar, schoo) VALUES ("249", "AM PROV", "aaa")'
); */
var_dump($inserts);
Edit: Though I think you're missing a table name from your INSERT statements.
Edit2: You could shorten the code using array_keys like Frosty Z does and skip the first foreach.
$inputArray = array('a' => array(1, 2, 3), 'b' => array("X'", 'Y', 'Z'));
$finalArray = array();
// build array with appropriate data rows
$finalIndex = 0;
foreach($inputArray as $key => $row)
{
foreach($row as $value)
$finalArray[$finalIndex][] = $value;
$finalIndex++;
}
// format it as SQL insert queries
$fields = array_keys($inputArray);
foreach($finalArray as $row)
{
echo "INSERT INTO table (".implode(", ", $fields).") "
. " VALUES (".implode(", ", array_map("format_data", $row)).");\n";
}
function format_data($value)
{
// assuming you're using MySQL. Replace the escape function by
// the appropriate one
if (is_string($value))
return "'".mysql_real_escape_string($value)."'";
else
return $value;
}
You can use one of those strange spl iterators for this :)
$iter = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);
foreach ($uberArray as $colName => $colValues) {
$iter->attachIterator(new ArrayIterator($colValues), $colName);
}
foreach ($iter as $vals) {
print_r($vals);
//or $pdoStmt->execute($vals);
}
But really, a simple for loop is the tool to use here.
I see no reason to merge the array unless you feel like wasting memory. You've already probably made a copy of the data. This just inserts the data row by row.
$data = array('foo' => array(...), ... );
$fields = array('foo', 'bar', 'schoo');
$c = count($data[$fields[0]));
$base_sql = 'INSERT INTO tbl ('.implode(',', $fields).') VALUES ';
for ($i = 0; $i < $c; ++$i)
{
$row_data = array();
foreach ($fields as $field)
$row_data[] = "'".escape_func($data[$field][$i])."'";
$sql = $base_sql . '(' . implode(',', $row_data). ')';
db_query($sql);
}
I would actually use prepared statements.
And you really should try to figure out how to iterate through the original dataset in one pass.

Categories