SQL - How insert into one single table column a array? - php

I'm currently working on a personnal project and I would to register the data provided by the user.
The data looks like that :
$array = (1,2,3,4,5);
I would like to register this array in ONE SINGLE table column. I would like to do that (I know this request will not work):
INSERT INTO `test`(`user_data`) VALUES ($array)
What can I do in order to do that ?
Thanks

To do so
use implode
$array = (1,2,3,4,5);
$str = implode(",",$array);
INSERT INTO `test`(`user_data`) VALUES ($str);
or
use json_encode
$array = (1,2,3,4,5);
$json_str= json_encode($array);
INSERT INTO `test`(`user_data`) VALUES ($json_str);

Related

Insert array and non array values to database using a single sql statement

I have this, working, code, for inserting array to database:
$c = array_map(function ($reqNo,$officer,$product,$quantity){return "'$reqNo','$officer','$product','$quantity'";} , $reqNo,$officer,$product,$quantity);
if(!$insert = mysql_query("INSERT INTO request (RNO,UID,PID,QtyR) VALUES (".implode('),(', $c).")"))
Now, the problems is that i would like also to insert, alongside the array, none array values to the same database table, using the same sql insert statement..here's my code so far,
if(!$insert = mysql_query("INSERT INTO request (RNO,UID,PID,QtyR,Iuse,Designation,QtyA,QtyA1,QtyI,Rdate,Rtime,bar) VALUES (".implode('),(', $c).",'replacement','ICTU','-1','-1','-1',CURDATE(),CURTIME(),'1' )"))
and here's the error i'm getting:
Column count doesn't match value count at row 1
Any ideas on how to go about this?
I did get a way around it, though not sure if it's the correct way..this' how i did it:
//first, i got the length of the array
for($i=0;$i<count($product);$i++){}
//i used array_fill() to duplicate the single values into the length of the array
$new_usage = array_fill(0,$i,$usage);
$new_designation = array_fill(0,$i,$designation);
$QtyA = array_fill(0,$i,"-1");
$QtyA1 = array_fill(0,$i,"-1");
$QtyI = array_fill(0,$i,"-1");
$date = array_fill(0,$i,date("Y-m-d"));
$time = array_fill(0,$i,date("H:i:s"));
$bar = array_fill(0,$i,"1");
//then i put the above new arrays into array_map(), together with the original array
$c = array_map(function ($reqNo,$officer,$product,$quantity,$new_usage,$new_designation,$QtyA,$QtyA1,$QtyI,$date,$time,$bar){return "'$reqNo','$officer','$product','$quantity','$new_usage','$new_designation','$QtyA','$QtyA1','$QtyI','$date','$time','$bar'";} , $reqNo,$officer,$product,$quantity,$new_usage,$new_designation,$QtyA,$QtyA1,$QtyI,$date,$time,$bar);
//from there, i imploded the array_map into the sql insert statement
if(!$insert = mysql_query("INSERT INTO request (RNO,UID,PID,QtyR,Iuse,Designation,QtyA,QtyA1,QtyI,Rdate,Rtime,bar) VALUES (".implode('),(', $c).")")){
...
I still don't know if this' the right way to go about it, but all in all, it did work.

Getting values inside an array to the database

hi im trying to fill a database table from the code below, but afterwards it fills the table coloumn just saying "Array" is there anyway to get the values inside this array and make them print in the table.
$query_new = "INSERT INTO red_message (message) VALUES ('$attributes')";
$result = mysql_query($query_new, $link_local);
P.S i use the print_r once it returns 1.. so print_r diont work either.. can anybody help me to get the values inside this $attributes array
Do you mean the implode()?
http://php.net/manual/en/function.implode.php
Example code from php.net:
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
try to use json_encode. If your array will be of several steps it is better to initially encode rhis array and then insert into the database. You also keep structure of the array.
Example:
$farr=array('user1'=>array('name'=>$name,'phone'=>$phone),'user2'=>array('name'=>$name,'phone'=>$phone));
$sarr=json_encode($farr);
mysql_query("Insert INTO .......");
After:
$query=mysql_query("SELECT ......");
$res=mysql_fetch_assoc($query);
$finaly=json_decode($res, true);
print_r($finaly);
This simply means that $attributes is of Array type. You should make sure that $attributes is of String type (which you can achieve with implode()) before using it in mysql_query().

php array implode for insert

I'm passing an html array to php using jquery serializearray() function.
In php I can access the array using $_POST like
$a = $_POST['htmlarray']
The html array, however, is an array of arrays like so
htmlarray[] = [[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18]]
I want to format the variable $a so that I can insert all the html array values in one single insert query like
INSERT INTO table
(val1, val2, val3, val4, val5, val6)
VALUES
(1,2,3,4,5,6),
(7,8,9,10,11,12),
(13,14,15,16,17,18)
I know I have to use an implode function, can anyone show how this could be done.
I'm not quite sure what an html array is, but try the following:
$a = $_POST['htmlarray'];
// unserialize $a
// build sql query up to '...VALUES '
foreach ($a as $row) {
$sql .= '(';
$sql .= implode(',', $row);
$sql .= ')',
}
This should iterate through the arrays and append all your rows to the string. Note, however, that this code does not take care of SQL Injections at all! Not to be meant for production.

How to add to an array in a database and get back each array and display it

How can I add a value into an array in a database row, and then later on, when I want to get values of the array, simply display each different array value on a new line?
Also, how do arrays work in mysql and how to get the value of it?
Filed testField has serialized data.
$arrayData = array('one','two','three');
$serializedData = serialize($arrayData);
Mysql insertion:
insert INTO table ('testField') Values ($serializedData);
To get data:
select testField from table where id=1
You are getting here some string value. Then you should unserialize this string to get array:
$arrayData = unserialize($selectResultValue);
Look here for more details about serialize function:
http://php.net/manual/en/function.unserialize.php
MySQL does not have a native array data type. So, your first step is to figure out how you will store the elements of the array in a MySQL table.
Will you store each array element in its own database row?
elem val
1 value1
2 value2
...
n valuen
Or will you store the arraw as a series of concatenated values in a single row, something like this?
values
value1,value2,value3,...,valuen
In the first case, you can update a single array element easily:
UPDATE array SET val=newValue
WHERE elem=updatedElement
In the second case, you'll have to read the values column, break it out (deserialize it) into an array, change the element or elements you want to change, then gather it up (serialize it) back into a values column, and update your mySQL table. #Anthony pointed this out.
You need to answer the question about how you're storing the array before you can start to figure out how you will update it.
save array
$foo = array(1,2,3);
mysql_query(sprintf("INSERT INTO some_table ('foo') VALUES ('%s')", serialize($foo));
foo will appear as a string 1,2,3 in the database now
fetch array
$result = mysql_query("SELECT id, foo FROM some_table")
$item = mysql_fetch_object($result);
$foo = $item->foo;
$foo = unserialize($foo);
add data to array
$foo[] = 4;
$foo = array_uniq($foo); // you might want to ensure only unique values
mysql_query(sprintf("UPDATE some_table SET foo='%s' WHERE id=%d", serialize($foo), $item->id);
foo will appear as a string 1,2,3,4 in the database now

cast text field to array in mysql select query

I have a table in MySQL database. In that table there is a text field called 'selection' that hold numbered values, separated by a pipe char (example: 44|5|23|546|.....). I also have a php array: $values = array(63,35,7,5);
I need to refer to the 'selection' field as array of options (separated by '|') and select only the rows that contain at least one of the number in $values array.
I hope i explained my problem accurately enough, because my English is very poor... Thanks.
If you want to get row that contains at least one number in $values array, the SQL looks like this:
$values = array(63,35,7,5);
foreach ($values as $value) {
$sql = "select * from tablename where selection like '%{$value}|%' or '%|{$value}%'";
}
If the values in the array are in the appropriate order for search already, you can build your query with something like this:
$selection_searched = implode('|', $values);
$query = "SELECT * FROM your_table WHERE selection = '$selection_searched'";
Beware that you would probably want to validate the array $values fisrt, to check if it isn't empty, etc. Check out the manual for: http://php.net/implode

Categories