need to store check boxes array in db - php

Iam trying to insert Array data (ie., checkbox values) into Mysql db (using Phpmyadmin)
when I try to store, iam getting as 'Array' for the field "forms" in db..
please someone tell me what changes I have to do for the below code, so I can store all the array values (seperated with commas in my db)
here is the code:
if(isset($_POST['forms']) && $_POST['forms']!=''){
$table = $wpdb->prefix . "eshop_orders";
$forms=$wpdb->escape($_POST['forms']);
$query1=$wpdb->query("UPDATE $table SET forms='$forms' where checkid='$checkid' limit 1");
}

Use serialize on the array before inserting the values, and unserialize when you call the values from memory.
For example:
$data = serialize($_POST['forms']);

You can change the array value to string using comma seperator and store it to db.
In Php there is an implode function to convert the array value to string using seperator.
$value = implode(",", $forms);
echo $value;
http://php.net/manual/en/function.implode.php

Related

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().

Assign POST values to an array in a loop and put array into a database

I have an array containing the names of form input names:
$minmax = array('bed_min', 'bed_max', 'rec_min', 'rec_max', 'bath_min', 'bath_max', 'value_min', 'value_max');
The names are identical to the corresponding columns in a database. Instead of using an sql query like so:
$bed_min=$_POST['bed_min'];
$bed_max=$_POST['bed_max'];
$rec_min=$_POST['rec_min'];
$rec_max=$_POST['rec_max'];
$bath_min=$_POST['bath_min'];
$bath_max=$_POST['bath_max'];
$value_min=$_POST['value_min'];
$value_max=$_POST['value_max'];
$query = "UPDATE first_page SET bed_min='$bed_min', bed_max='$bed_max', rec_min='$rec_min', rec_max='$rec_max', bath_min='$bath_min', bath_max='$bath_max', value_min='$value_min', value_max='$value_max', WHERE email_address='$email' ";
Is there a way to automate all this into a smaller lump of code? I know the POST values should not be added to the query diectly, so maybe a loop to assign the POST values to a corresponding array of variables using something like:
foreach ($minmax as $var){
$var = $_POST[$var]
}
(nb i dont think this snippet will work but ive added it because I think with a bit of editing it might!)
After the list of variables have been assigned the POST values, do the update in the $query using two arrays, one with the list of values and one with the list of database columns. Again I dont know how this will work, so pointers would be helpful!
You don't really need the $minmax array of form input names since you can get those from the keys of $_POST.
If the values are all numbers, like they seem to be, then you could do it all in one line like this:
$query = "UPDATE first_page SET " . vsprintf(implode("='%d', ", array_keys($sanitized_POST))."='%d'", array_values($sanitized_POST))." WHERE email_address='$email'";
That's assuming you have already sanitized the items from $_POST into a new array named $sanitized_POST. I know you said in the above comment to ignore sanitization, but I thought I'd add it so you know I'm not suggesting to use the values straight from $_POST.
You could sanitize the $_POST array with something like this:
$sanitized_POST = array_map(function($item) {
return mysqli::real_escape_string($item);
}, $_POST);
Honestly though, you should try to come up with a solution that uses prepared statements.
On a side note, if you have the sanitized post array, then this one line will essentially do what Quixrick has done with variable variables in one of the other answers:
extract($sanitized_POST);
If you assume that all of the values in post have the same names (array keys) as your columns, then something like this could work for you:
$query = "UPDATE first_page SET ";
foreach ($_POST as $key => $var){
$query .= " $key='$var',";
}
$query = rtrim($query,',') . " WHERE email_address='$email' ";
You probably want to use 'Variable Variables' here. Basically, you'd use a double dollar sign $$ to create a variable with the name of the array value.
$_POST['bed_min'] = 'Rick';
$minmax = array('bed_min', 'bed_max', 'rec_min', 'rec_max', 'bath_min', 'bath_max', 'value_min', 'value_max');
foreach ($minmax as $var){
$$var = $_POST[$var];
}
print "<BR>BED MIN: ".$bed_min;
This outputs:
BED MIN: Rick

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.

Trying to insert array into database... (implode() [function.implode]: Invalid arguments passed )

I have a select input where you can choose multiple options. Unfortunately, I have no clue how to insert the values selected into my database. Here is the code I am trying to use, which is giving me an invalid argument passed on my attempt to implode it.
Thanks for any help...
Here is my php:
$distribs = implode("|", $_POST["distributors"]);
$distribs = mysql_real_escape_string($distribs );
$distribs = mysql_real_escape_string($_POST['distributors']);
$sql="UPDATE customers SET distributors = '$distribs'
WHERE id='$id'";
Here is my select:
echo "<select name='distributors' multiple='multiple'>";
try like this
echo "<select name='distributors[]' multiple='multiple'>";
$_POST["distributors"]; is not an array, implode(); require an array to function,
PHP.net Function for implode();
If your $_POST is a correct array format; then implode will convert the array into a single string.
If your $_POST contains information from a <select> </select> Then the submission would be a single string which can be inserted into a database without the need for your implode(); function.
if you are certain that your $_POST is being submitted in an array format. Use as
DeDav
Has suggested.
Run this command when your $_POST is populated.
print_r($_POST['distributors'])
If your using a multiple select. Use as again DeDav suggested:
echo "<select name='distributors[]' multiple='multiple'>";

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

Categories