Get values โ€‹โ€‹from several elements and enter them into the database

What is the best way to get all the values โ€‹โ€‹of one multiple selection window, and then I want to store these values โ€‹โ€‹in one row in the database, and then from this row I want to split each value. What is the best way to do this? My goal is to keep the values โ€‹โ€‹and then get each one separate.

+3
source share
4 answers

You could do it that way

<select name="foo[]" multiple="multiple">
     <option value="dog">Dog</option>
     <option value="cat">Cat</option>
     <option value="fish">Fish</option>
</select>

<?php

$pets = $_POST['foo'];

//sanitize and verify the input here. Escape properly and what not

$query = mysql_query("INSERT INTO `pets` (`pet1`, `pet2`, `pet3`) VALUES ('".$pets[0]."', '".$pets[1]."',  '".$pets[2]."')");
?>

But honestly, this is a terrible way to build a database. It will be very unpleasant or difficult to do something meaningful.

Why not create the following database setup:

users:

id | name 
----------
 1 | Tim

Pets:

id | user_id | type
-------------------
1  | 1       | Fish
2  | 1       | Cat
3  | 4       | Kakapo

, .

+4

, , $_POST, , name= ""

$_POST [ "products" ] , POST.

implode . :

$myProducts = implode("|", $_POST["products"]); //This will give you a pipeline delimeted string like : computer|laptop|monitor

$myProducts = mysql_real_escape_string($myProducts); //Just to santize before inserting in DB

.

, :

$myProducts = explode("|" , [The value retrieved from the database]); //This will give you an array which you can iterate and thus accessing the values individually.

, :)

+2

...

$dataFromMultipleBox = array('data1', 'data2', 'data3');
$data = implode("||", $dataFromMultipleBox);

/*
After that,
write $data into database

fetch from the database again
*/

$pieces = explode("||", $rowFromDatabase);

foreach($pieces as $value) {
  echo $value;
  echo '<br>';
}
+1

,

Since this is PHP. Give the select element a name ending in [], then you can access them as$_POST['foo'][]

and then I want to store these values โ€‹โ€‹in one row in the database, then from this row I want each value to be split.

Do not do that. You have a second table with two columns. The identifier (as a foreign key) of the row in another table (where you planned to store the data) and the value itself.

0
source

All Articles