What is the best way to get the all values of one multiple select box, and then i want to save those values in one row in the database, then from that row i want to get each value separate. What is the best way to do such a thing ? My goal is to save the values and then get each separate.
You could do it this 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 to be honest it's an awful way to go about building a database. It'll be very annoying or difficult to do anything meaningful with.
Why not have the following database setup:
users:
id | name
----------
1 | Tim
pets:
id | user_id | type
-------------------
1 | 1 | Fish
2 | 1 | Cat
3 | 4 | Kakapo
And then you would have a much more easily searchable and manipulatable database that's consistent.
I believe you should receive the value selected as an array in the $_POST variable so say your select has a name="products"
The values selected will be in $_POST["products"] assuming you are submitting the form via POST.
Then you can use the implode function to generate a string. For example:
$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
Then just insert that string into the DB.
When retrieving the data you can reverse the process by using the explode function:
$myProducts = explode("|" , [The value retrieved from the database]); //This will give you an array which you can iterate and thus accessing the values individually.
Hope this helps :)
if i understand your question well...
$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>';
}
What is the best way to get the all values of one multiple select box,
Since it is PHP. Give the select element a name ending in [], then you can access them as $_POST['foo'][]
and then i want to save those values in one row in the database, then from that row i want to get each value separate.
Don't do that. Have a second table with two columns. The id (as a foreign key) of the row in the other table (where you were planning to store the data) and the value itself.
Related
I am working on an existing HTML form used to collect data about a project and then inserts that project record into a MySQL database using PHP.
Inside the form, there is an input field named "staff[]". This field is a multi select element, that allows users to select more than one team member to handle the project.
<form action="" method="post">
<select multiple name="staff[]">
<option value="1">Mary</option>
<option value="2">Tyrone</option>
<option value="3">Rod</option>
<option value="4">Marcus</option>
<option value="5">David</option>
</select>
</form>
For example purposes, the user selects Tyrone, Rod and David for this particular project. If we insert the record at this point, the database only stores the first record value, which would be Tyrone's ID of 2. General practice is to store each instance in a separate table, however this is not our system and due to a restriction of 4 members for each project, management would prefer we insert a comma delimited array into each project's staff column for convenience.
In order to handle this issue, we've created a foreach loop that loops through the selected values from the dropdown menu, while ensuring a trailing comma doesn't exist:
// Add array into one variable
$staff_count = count($_POST['project_staff']);
$i = 0;
foreach($_POST['project_staff'] as $staff) {
if (++$i === $staff_count) {
$member_variable .= $staff;
} else {
$member_variable .= $staff . ", ";
}
}
After pressing the submit button, the above script is ran (which produces an array value of (2, 3, 5)) and the record is inserted into the 'projects' table with no issues.
HEREIN LIES THE PROBLEM.
Finally we have a view page, where we will call all employees assigned to a project, based on the query parameter, which would be the project ID. For example, if the previous project ID was 6, the following URL would be used:
site.com/project/view/?project=6
From this page, I am able to save the staff list using the following variable assignment:
$project = "SELECT * FROM projects WHERE project = 6";
$employee_chosen = $project['project_employee']
If the 'staff' column only accepted one employee (for example, just one value of 4), the variable would have a value of one number:
$project['project_employee'] (4)
I would then be able to run a secondary query for employees as such:
$employee_chosen = $project['project_employee']; (4)
query2 = "SELECT * FROM employees WHERE employee_ID = $employee_chosen";
This would very easily bring back the one employee that was entered in the "staff" column. However, we are dealing with an array in this column value (2, 3, 5) and so I have queried the following statement:
$employee_list = $project['project_staff']; (2,3,5)
$query_employees = "SELECT * FROM employees WHERE employee_id IN ($employee_list)";
When I run this query, I receive only the first result from the employee ID 2 (as initially stated with the HTML form).
However, if I use phpMyAdmin to directly type in the three numbers as a string:
$query_employees = "SELECT * FROM employees WHERE employee_id IN (2,3,5)";
I receive all three employee records.
Just to ensure that the column ARRAY was in fact behaving as a STRING, I initiated a var_dump on the value:
echo var_dump($project['project_staff']);
After which I received the following information:
string(7) "4, 5, 6"
Does anyone have any ideas?
I am satisfied with the idea that I am able to query the value, as before I received several non-object and array errors.
Thanks in advance for any assistance you may be able to provide.
I'm pretty sure from what you are saying that you are storing a string $employee_list that might be '2,3,4'. Then your IN ($employee_list) is really IN ('2,3,4') but what you really want is IN (2,3,4). There are various ways to get there but you could do
$employee_list = implode(','(explode(',', $employee_list));
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I have a database full of items for a video game. Swords, Shields, etc. I tagged all the items with level, effect, location found and stuff like that.
I can hard code pages to pull from the database. Such as a hard coded dagger that stuns query:
$results = $mysqli->query("SELECT name, type, level, effect
FROM Items
WHERE type = 'Dagger'
AND effect = "Stun"
ORDER BY name ASC");
while ($item= $results->fetch_assoc()) { $result_array[] = $item; }
However I want users to go through drop down menus so they can filter results from the database from themselves. I have no idea how to go about this. I have tried googling but a lot of it seems outdated or when I try it just doesn't work.
Something similair to this website - http://www.wowhead.com/items
So for example users could pick the "Effect" drop down and it creates another drop down where you can choose from; Freeze, Heal, Stun or whatever. Then pick level from drop down menu and enter 50. Then the database would pull the results from the database for daggers that stun and can be used at level 50.
Thanks!
It's pretty simple. First you have the form element.
<form type="post" action="controller.php">
<select name="weapon">
<option value="Dagger"> Dagger </option>
<option value="Sword"> Sword </option>
</select>
<select name="effect">
<option value="Stun"> Stun </option>
<option value="Knock Back"> Knock Back </option>
</select>
</form>
When the user selects a value from these dropdowns, they'll be sent over to the server in the $_POST array with their key's matching the "name" of the select element. The controller.php file is the file that will handle the form submission. You can change the location of this file etc.
Then in your form submission handler you want to handle the $_POST array and then create a prepared statement for security as we're dealing with user input.
/**
| ---------------------------------------------------
| controller.php
| ---------------------------------------------------
*/
if(isset($_POST)){
$weapon = isset($_POST['weapon']) ? $_POST['weapon'] : false;
$effect = isset($_POST['effect']) ? $_POST['effect'] : false;
if($weapon && $effect){
$mysqli = new mysqli('host', 'user', 'pass', 'database');
$result = $mysqli->prepare("SELECT name, type, level, effect
FROM Items
WHERE type = ?
AND effect = ?
ORDER BY name ASC");
$result->bind_param('ss', $weapon, $effect);
if($result->execute()){
while($row = $result->fetch_assoc()){
//access column names here by $row['index'];
}
}
}
}
The above script is checking if the post array is populated, then checks for our specific variables. from there, we establish the database connection, create the safe prepared statement, bind our parameters to our prepared statement, execute the query, then we iterate over the returned resultset with fetch_assoc.
I hope this helps you.
I have been trying to get data from exploded values, but I am failing miserably and I am completely clueless despite all the researching I've been doing.
This is how the code looks like:
$array = explode(",", $hos['prop_owner']);
list($a) = $array;
$gu = $db->prepare("SELECT * FROM users WHERE user_id = :id");
$gu->execute(array(':id' => $a));
$dau = $gu->fetch();
echo $hos['prop_name']."<br><small>";
if(end($array)){
echo "<a href='/user/view/".$dau['user_id']."' style='color:#".$dau['user_colour']."'>".$dau['user_name']."</a></small><br>";
} else {
echo "<a href='/user/view/".$dau['user_id']."' style='color:#".$dau['user_colour']."'>".$dau['user_name']."</a>,";
}
Currently, the database field $hos['prop_owner'] contains the values "2,20" which are IDs of users (this field can potentially contain more IDs in the future). What I want to do is get all the user data from the exploded values, in this case 2 and 20, and then echo the information out in order as well.
Re-explanation:
I have a field in my database called prop_owner which is supposed to contain an unlimited number of user IDs, seperated by comma. Format: 1,2,3,4.
I want to take the value from this field, then somehow separate the user IDs and separately retrieve the usernames and echo them out.
Example result: Darren, Eva, Miles, Lisbeth
I hope I explained myself good enough to understand where I am trying to go with this.
Thanks in advance!
First of all the query will be like
SELECT * FROM users WHERE user_id in (2,20)
You need the data of both the users so the query will return all the data of all the ids that are being passed here..
You can directly pass here but you need to take care of security... or may be you can check how to pass values securely in such queries ...
I am struggling a little bit with a tricky PHP array. I am trying to retrieve data from a database (a single row) and I want to plug this data in a bunch of dynamically generated fields on the page (PHP).
My DB is organised as follows
____________________________
| cats | dogs | birds | cows |
_____________________________
| 30 | 40 | 22 | 34 |
______________________________
I would like to build an array like this:
array(
$cats => $cats_value
$dogs => $dogs_value
etc...
)
Importantly: I want the array to ouput variables, where in the above example $cats outputs "cats" and $cats_value outputs "30". I am guessing once this is done that I can use the variable names directly, so I won't have to go nuts trying to pull them out of the array...
I have tried to put various bits of code but have failed miserably (i.e. nothing to show/embarrass myself with on here.)
Any help would be much appreciated.
OK, the code that provides the answer is as follows:
$query = "SELECT * FROM animals";
$result = mysqli_query($dbc, $query);
$data_array = array();
$row = mysqli_fetch_assoc($result);
print_r($row);
foreach($row as $key=>$value){ echo $key; echo $value;
${$key}=$key;
${$key."_value"}=$value;
}
echo "<br><br><br>";
echo $Cats." = ".$Cats_value."<br>";
echo $Dogs." = ".$Dogs_value."<br>";
echo ${"Cows"}." = ".$Cows_value."<br>";
echo ${"Birds"}." = ".$Birds_value."<br>";
I appreciate all the answers that helped me find the answer to this. As an aside, the whole reason I am doing this is because I need to populate a dynamically generated PHP page with a bunch of variables, and that I will likely need to populate these variables dynamically as well.
If you think I am approaching this problem the wrong way, then please let me know (i.e. is it dumb to convert an associative array into a bunch of $variables? Does that make sense, and/or could it really slow down my page?)
I have a question about how I can save different value in order if I GET 1 row in php.
For example, if I have like:
*Feder|100|50|10|5|9|0|0|0|0|0|0 PHP LINE
I need to save this row in the table like:
----------------------------------------------
name | score | status | point | level | bla | bla | bla....
----------------------------------------------
Feder| 100 | 50 | 10 | 5 | 0 | 0......
-------------------------------------------------
Now, I use easy method to get something in the database like:
$sql="INSERT INTO user (name, score, status)
VALUES
('$name','$score','$status')";
mysqli_query($con,$sql);
With this, when I get the value, I use like:
save.php?name=feder&score=100&status=50
But if I have to insert 40 values, will this be very hard? I think is possible to make easy, but I don't have any idea how I can do that... Someone know the best method to do this?
If I can use like: save.php?userdata=(all row)* is better...
What you ask for is not recommended for security reasons. It's one of the biggest no-nos to trust GET contents and put it straight into an SQL query.
But.
Of course you can foreach the variable $_GET like this:
$x="";
foreach($_GET as $key=>$val) {
$x.=" $key = '$val', ";
}
$sql = "insert into myTable set $x";
This is just the principle of it. You should ALWAYS check for the field names and values to avoid injection attacks. So a better approach would be like:
$isValid = array("name"=>1,"score"=>1,"status"=>1);
$x="";
foreach($_GET as $key=>$val) {
if(!$isValid[$key]) continue; // skip unknown fields!
$val = stripslashes($val); // remove magic quote junk
$val = mysql_real_escape_string($val); // protect mysql from attacks
$x.=" $key = '$val', "; // build the query
}
$sql = "insert into myTable set $x";
UPDATE
If you get all the values in one string like "aaa|bbb|ccc", you can use explode() to parse them into one array. But then you rely on the order of fields which is not a good practice. I'd recommend to always prefer "field1=aaa&field2=bbb" style.
Hope this helps.
Think about the risks and find your own way.
You said 40 row. You have to remember that the limitation of length of an URL. So the suitable way is to use POST method through a HTML form. Taking care in multible fields naming by adding [] to the field name:
<form method="post" action="some.php">
<input type="text" name="name[]" />
<input type="text" name="score[]" />
...
</form>
and from your PHP
for ($i = 0; $i < count($_POST['name']); $i++){
$name = $_POST['name'][$i];
$score = $_POST['score'][$i];
$status = $_POST['status'][$i];
$sql="INSERT INTO user (name, score, status)
VALUES
('$name','$score','$status')";
mysqli_query($con,$sql);
}
Notice: This answer is about the concept of inserting multiple records. It does not meant by the security of receiving data.