How to insert array in single field - php

I want to store ids in database like this 1,2,3,4,5 in one field from a while loop.
how can i do this.
I am trying this way.
$array = array();
while($row=mysqli_fetch_assoc($result)){
$array[] = array($row['id']);
}
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$array')");
print_r($array);
This is showing error Array to string conversion and value as Array is inserted in database.
Please see and suggest any possible way to do this.
Thanks.

Create another table and insert 5 rows into it.
entity_id | ids
1 1
1 2
1 3
1 4
1 5
that's the only proper way of doing such things
However, if it's really a temp table, there is probably a way to avoid these inserts at all.

You can use either serialize or json_encode:
$data = serialize($array);
// ...or...
$data = json_encode($array);
If the array just contains plain numbers you can also use implode:
$data = implode(',', $array);

$arrays = array();
while($row=mysqli_fetch_assoc($result)){
$arrays[] = $row['id'];
}
$arr_str = implode(",", $arrays);
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$arr_str')");
//print_r($array);
Detailed information about implode can be found here.

Use the implode() function:
$to_insert = implode(',', $array);
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$to_insert')");

$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES(".join(',', $array).")");

Try:
$ids = join(',',$array);
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$ids')");

Please use implode function before insert into database :-
Here is a example :-
$array = array(1,2,3);
$comma_separated = implode(",", $array);
echo $comma_separated;
Output :-
1,2,3
In your case :-
$array = array();
while($row=mysqli_fetch_assoc($result)){
$array[] = array($row['id']);
}
$comma_separated = implode(",", $array);
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$comma_separated')");
print_r($array);

Set the field type varchar(255) and do this with php
$array = array();
$value = serialize($array);
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$value')");
print_r($array);
To retrieve the value you should unserialize the column
$data = unserialize($result['temp']);
Here result is associative array. $data is an array you dont have to implode or explode or json_encode or json_decode

Related

How to iterate through database results, compare each value to that in an array and return the matching id?

I am trying to build a function that will be given an array. and from this array, iterate through an entire table in the database trying to find a match. If it does find a match. I would like it to echo out the ID of that match from the database table.
If possible I would also like it to say if it found any close matches?
What's making this tricky for me is that it needs to match all values despite their order.
for example, if the function is given this array:
$array = array(1,2,3,4,5)`
and finds this array in the database:
$array = array(2,3,5,1,4)
it should consider this a match
Also, if it finds
array(1,2,3,4,5,6)
It should output this this as a match except for value 6.
Let me refrase your question, is this correct?
Based on an array of ID's, return all records whose ID's are in the array.
If so, use the IN operator:
SELECT *
FROM tableName
WHERE columnName IN (value1, value2, value3, etc.)
So first we need to transform the given array into a comma-seperated list:
$comma_seperated = implode(', ', $array);
Now we have a comma-seperated list we can use in our query:
$comma_seperated = implode(', ', $array);
$query = "SELECT *
FROM tableName
WHERE id IN (" . $comma_seperated . ")";
// execute query, don't use mysql_* functions, etc. ;)
You could use any of the options:
option 1:
$array = array(1,2,3,4,5);
$query = "SELECT id FROM youtable WHERE id IN(".implode(",",$array).")";
option 2:
$array = array(1,2,3,4,5);
$query = "SELECT id FROM yourtable";//Select ids
Now iterate through query results, say results are stored in $query_results,
$result=array();
foreach($query_results as $row){
if(in_array($row['id'],$array)){
$result[] = $row['id'];
}
}
You can use array difference to get the result just run the code and you will understand
Case 1
$array1 = array(1,2,3,4,5);
$array2 = array(1,2,3,4,5,6);
$result = array_diff($array1, $array2);
print_r($result);
Case 2
$array1 = array(1,2,3,4,5);
$array2 = array(1,2,3,4,5,6);
$result = array_diff($array2, $array1);
print_r($result);
And after that you can the count of $result and put it in your logic.
Case 1:
Maybe you can select the unique values from the database.
SELECT DISTINCT unique_values_that_need_for_compare_column FROM table
This SQL result will be the $databaseValues variable value.
Than iterate through the array that the function gets.
foreach ($functionArray as $value) {
if (in_array($value, $databaseValues)) {
// you have a match
echo $value;
}
}
Case 2:
Or you can make a query for every value:
foreach ($functionArray as $value) {
$query = "SELECT COUNT(*) as match FROM table WHERE unique_values_that_need_for_compare_column = " . intval($value);
// fetch the result into the $queryResult variable and than check
if ($queryResult['match']) {
// you have a match
echo $value;
}
}

interleaving arrays for mysql update

I have two arrays, one containing the field names which are imploded into a string called $fields, and one containing the data imploded into $data.
When data is first entered using the INSERT command the query looks like...
mysql_query("UPDATE table ($fields) VALUES ($data)")
(BTW: all data is sanitised)
My goal is to build a mysql UPDATE statement where the syntax is
mysql_query("UPDATE table SET $field1=$data1, $field2=$data2 ...")
and update all fields at once, so I need to combine the two arrays to build the alternating field/data/field/data structure instead of all of the fields followed by all of the data.
My idea is to use array_combine or array_merge and then implode into a string that will then set the function to
mysql_query("UPDATE table SET $imploded-combined-arrays")
I recognise that this won't work as the "glue" of the implode statement has two different values depending upon whether it is equating or separating field/data pairs.
How can I step through both arrays and build a string that is appropriate for the UPDATE syntax?
Thanks,
Cam
Try this
$a = array('key1', 'key2', 'key3');
$b = array('value1', 'value2', 'value3');
$c = array_combine($a, $b);
foreach($c as $key=> $value){
$result[]=$key."='". $value."'";
}
$updatefields= implode (', ', $result);
echo ("update table set " .$updatefields);
OUTPUT
update table set key1='value1', key2='value2', key3='value3'
DEMO
$names = array ('foo', 'bar');
$values = array ('hello', 'world');
$pairs = array ();
foreach ($names as $i => $name)
{
$value = $values [$i];
// $name = mysql_real_escape_string ($name);
// $value = mysql_real_escape_string ($value);
$pairs [] = "`$name` = '$value'";
}
echo ("UPDATE t SET " . implode (', ', $pairs));
For me outputs is:
UPDATE t SET `foo` = 'hello', `bar` = 'world'

implode an array into a comma separated string from mysql query

For the last 1 1/2 days I've been trying to store 16 row id's into a string and separate each id with a comma. The array I am getting is from MySQL. The error I am getting is
implode() function:passed invalid arguments
$str=array();
$string="";
while($row = mysql_fetch_row($result))
{
$user_id=$row;
$str=$user_id;
foreach($str as $p=>$v){
comma($v);
}
}
function comma($v){
$string= implode(",",$v); echo $string;
}
Try something like this:
$ids = array();
while ($row = mysql_fetch_assoc($result))
{
$ids[] = $row["UserID"];
}
echo implode(", ", $ids);
Replace "UserID" with the columnname of the id in your table.
So: first you build the array, next you implode the array into a string.
There is my solution:
SELECT GROUP_CONCAT(UserID) as string FROM Users;
For this function the delimiter is ',' by default.
$query = 'SELECT id FROM your_table';
$rs = mysql_query($query);
$row = mysql_fetch_array($result);
return implode(',', $row);
the result 1,2,3...

MYSQL insert comma separated values into separate fields?

I know its a strange question, but I have one input field that does a live search for locations. The final value is displayed like this:
State,Suburb,Post Code
NSW,Sydney,2210
What I need to do now is split the three values into single values and update them into my separate fields for one row.
I don't want to update multiple rows but just one.
e.g.:
fields ( state | suburb | postcode )
values ( NSW | sydney | 2210 )
What php commands would I use to split those commas off and create single $values for each item?
Use explode on the string.
$values = 'A,B,C,D';
$values = explode(',', $values);
Each item can then be accessed from an array indexed from 0.
$val = "NSW,Sydney,2210";
$valArr = explode(",", $val);
$query = "UPDATE MyTbl SET State = '$valArr[0]', Suburb = '$valArr[1]', Post_Code = '$valArr[2]' WHERE ...";
The easiest way I think, see the manual for explode:
$result_array = explode(',', $your_variable);
list($state, $suburb, $postcode) = explode(',', $value);
Would this work?
$header = "State,Suburb,Post Code"
$items = explode(",", $input)
$output = implode("|", $items)
so the output would become State|Suburb|Post Code
to access each value separately, you can use $items[0], $items[1] ..
$data = "NSW,Sydney,2210"
$items = explode(",", $input)
$output = implode("|", $items)
so the output would become NSW|Sydney|2210

PHP - Add String to Array

I am wondering how I can add a string variable to the current array. For example, I have an array called $finalarray. Then I have a loop that adds a value on every run. Basically:
$finalarray = $results_array + string;
A very basic structure. I am using this for MySQL so that I can retrieve the final array of the column.
$query = "SELECT * FROM table";
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray = $finalarray + $results_array["column"];
}
Edit:
Currently using this code (still not working):
$query = “SELECT * FROM table”;
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray[] = $results_array["name"];
}
echo $finalarray;
The problem is that it just says "Array"
Thanks,
Kevin
Answer to your edited question:
You cannot use just a single echo to print the entire array contents. Instead
Use
var_dump($finalarray);
or
print_r($finalarray);
to print the array contents..
Use the [] notation. + is for unioning two arrays.
$array = array('foo');
$array[] = 'bar'.
// $array == array('foo', 'bar')
You can use the function array_push or [] notation:
array_push($array, 'hi');
$array[] = 'hi';
Take a look at this
$query = "SELECT * FROM table";
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray[] = $results_array["column"];
}
// Add X to the end of the array
$finalarray[] = "X";
Codaddict is correct. You are looking to output the last element that was added to the array.
echo end($final_array);
That will move the array's pointer to the last element added to it and then output it. Since you're adding the elements to the array in this manner...
$finalarray[] = $results_array["name"];
The key for each of your elements will be sequential, 0,1,2,3...so on and so forth. Another less elegant solution to get the last element would be...
echo $final_array[count($final_array) - 1];
echo implode($finalarray);
Or with a custom join "glue"
echo implode(', ', $finalarray);

Categories