How to parse an array into variables (PHP)? - php

For the life of me I cannot get this to work. I've looked at many articles on stackoverflow so if you could help that would be wonderful! I am working on a form submission for a client. They want to be able to select multiple values from a dropdown, which in turn I will pull from a database to get their query results.
<form id="test" action="results.php" method="POST">
<select id="role" name="role[]" multiple>
<option value="Student">Student</option>
<option value="Faculty">Faculty</option>
<option value="Alumni">Alumni</option>
</select>
<?php
$query="SELECT City FROM Cities";
$result = mysqli_query($link, $query);
echo '<select name="city" id="city" multiple>';
while($r = mysqli_fetch_assoc($result)){
echo '<option value="'.$r['City'].'">'.$r['City'].'</option>'; }
?>
</select>
<input type="submit"/>
</form>
//results.php
$results=array();
$results[] = $_POST['role'];
$results[]= $_POST['city'];
echo "<pre>";
print_r($results);
echo "</pre>";
**How do I obtain all the values from the array and parse it into separate variables so I can use the variables in a SQL statement? Here is my output: **
Array
(
[0] => Array
(
[0] => Faculty
[1] => Alumni
)
[2] => Adams
)
Thanks so much for any help! :) And if there is a better way to do this, let me know.

[EDIT] : This code is wild open to SQL Injection , Please don't use it.
One submit options i already have in the question and one i created
dummy submit options for city, run this code in the different file,
than select different different options, and click on submit button,
to check how our query is getting built
Please read the note first and make sure you read the comment in the code, as they are more important than the code
Note 1-> in short you want to run the query, according to the selected options by the user,
make sure you read the comment to understand the logic, comments are more important than the code it's self,
Note 2-> and more thing i did not realize, you may be storing your value in different different table, if that's the case, code will change little bit, but basic shell will remain the same
Note 3-> To achieve the out come which you want to achieve, you basically have to create your query according to the set options, and than use IN keyword and you are good go,
Note 4-> I added echo statement, so you can see stage by stage how our query is developing, i added the comment, if you want see just remove the comment, I did not add the comment in the last echo so you can see the ready to use query string
Note Again-> one submit options i already have, one i created by my self, so you can see what happening, and you it going to work out for you.
as you said in the comment you may have 12 field, in your form, if that's the case, use this code, because lets say if you have to change
some thing in the future, and you have to change at tweleve places,
you will make mistake like miss some thing, or use the wrong variable
or some thing else, with this code, you have to change it one place,
and it will get apply to 12 or 24 places, number of places does not
matter,
and one more thing, it will better if you wrap this php code inside the function, the reason is lets say you have form on some other page, and you need same functionality only thing you have to do than, just call the function, and in the future if you have change some thing, just change the function code
I am giving you example on your code why it is better to wrap this in a function, lets say your table name are different than the given selected name in your form or you decided to hole values in different different table, than you have to change the code, if you wrote this twelve times or each form, and than you have to change it, than you are in big trouble, but if you use this code as function for different different form, you just have to do some changes in function or in here, and will get applied everywhere, in short chances of you screwing up some thing is just not their, so hope fully this will help you
SideNote -- one more thing i want to say, the reason this solution look big, is because of note, form and comment, if you count the php code line, with out the last echo statement, it actually only 10 lines of php code, so dont get afraid, becuase it's look big
<form id="test" action="" method="POST">
<select id="role" name="role[]" multiple>
<option value="Student">Student</option>
<option value="Faculty">Faculty</option>
<option value="Alumni">Alumni</option>
</select>
<select id="city" name="city[]" multiple>
<option value="London">London</option>
<option value="Paris">Paris</option>
<option value="New York">New York</option>
</select>
<input type="submit">
</form>
<?php
//creating variable and saying all the post request is equal to this variable
$selected_options=$_POST;
foreach($selected_options as $key=>$option){
$countValue = count($option);
for($i=0; $i<$countValue; $i++){
/*
* start adding the value seperated by coma, remember again it going to
* be on extra coma so we have to remove it.
*/
$queryString_start_with_coma .= ",$option[$i]";
}
/*
* come out of loop, and now remove that extra coma
*/
$queryString_remove_extra_come= preg_replace("/,/", "", $queryString_start_with_coma, 1);
/*
* start building your query, use variable $key, just check the line below,
* you will understand where and why i am using variable $key.
*/
$query_string_with_and .= " AND $key IN($queryString_remove_extra_come)";
/*
* now unset the variable, this line is very important, so please also check
* your out come without this line,
* what i am simply doing is emptying the variable, if you dont
* do it, it will add the value in the existing value, which i dont want, what
* i want when the loop run for the second selected options, i want my variable
* to be empty, so i can create new string
* you will understand more if you remove this line and compare your two outcome
* Note: you dont have to unset if you dont want to, but you have empty the
* variable, you can also do by creating a empty string, do what ever you want
* to do, just make sure the variable is empty for the second loop
*/
unset($queryString_start);
}
$query_string_second_part_ready = preg_replace("/AND/", "", $query_string_with_and, 1);
//echo "$query_string_second_part_ready<br>";
$query_string= "SELECT * FROM table_name WHERE ".$query_string_second_part_ready;
//see how your query look like
echo $query_string;

It sounds like you want to be able to build a query based on the data submitted by the user. This may be a little more complex if you have multiple tables, but the basic idea is to use the input names with the fields, assemble the query from them, prepare the statement and bind the parameters.
Name the inputs the same as the database fields they match to
// Identify which database fields can be searched
// These names must match the names of the inputs
// Each name has a type which will be used later
$databaseFields = [ 'city' => 's', 'name' => 's', 'grade' => 'i' ];
$databaseFieldNames = array_keys($databaseFields);
// Set up the beginning of the query
$query = 'SELECT * FROM some_table WHERE ';
// Initialize an array to use to store fields to be searched
$where = [];
// Loop through all the post data
foreach ($_POST as $name => $value) {
// If the name is in the database fields list, add it to the query
if (in_array($name,$databaseFieldNames)) {
$where[] = $name;
}
}
// Add all the requested columns to the where
if (!empty($where)) {
$query .= ' '.$where[0].'=?';
array_pop($where);
foreach ($where as $name) {
if (is_array($_POST[$name])) {
// Use any to check for multiple possible values
$query .= ' AND '.$name.' = ANY (?)';
} else {
$query .= ' AND '.$name.'=?';
}
}
} else {
// Avoid an empty WHERE which will cause an error
$query .= ' TRUE';
}
$stmt = mysqli_prepare($query);
/* Bind parameters */
foreach ($where as $name) {
// $_POST should be validated here
if (is_array($_POST[$name])) {
// Arrays are imploded to work in an ANY
$value = "'".implode("','",addslashes($_POST[$name]))."'";
} else {
// Other values are used as sent
$value = $_POST[$name];
}
$type = $databaseFields[$name];
$stmt->bind_param($type,$value);
}
$stmt->execute();

Related

If option value is not available in the select form, show error

Sorry if the title is not clear enough, here is the explaination :
I got a MYSQL Database named "perso", with "perso_name in it". The perso_name are the same as the values in my select form. Here is the HTML code :
<form method="post">
<select name="selectperso" onchange="showUser(this.value)">
<option value="op1">Option1</option>
<option value="op2">Option2</option>
</select>
<input type="submit" name="validperso" value="Confirm">
</form>
Here is the PHP code :
<?php
$error = 0;
if (isset($_POST['validperso'])) {
if ($error !== 0) {
echo"<script>alert(\"Error\")</script>"; }
else {
echo "<script>alert(\"Working\")</script>";
}
}
?>
Now, what i want to do is kinda tricky.
Let's say i have "op3" in my database, but the user can't have it. The problem is that the user can modify the value "op1" to "op3" and then he will have the op3. I want to make a condition which says "if the user select one of the "op" value available in the select, then it's ok. Else, error++."
Thanks for the help !
Okay, I write more info about your problem.
Usually what you need is called whitelisting - you create a list of some things, that are allowed for user.
It can be simple array like:
$allowed_options = ['op1','op2','op3'];
if (!in_array($userInput, $allowed_options)) {
// input not allowed, do something
}
Or more complicated logic like a query to mysql:
select * from table where option = "USER_INPUT" and user_role = 'SOME_ROLE'
Anyway, only you as a developer know how to limit user's activity.
If, for example, you create your select from array of values:
foreach ($values as $v) {
echo '<option value="' . $v . '">VALUE</option>";
}
Then use same array $values to check if user input is allowed.
Same to mysql queries or other ways of getting required content.
To achieve your target better way you bind user with options in DB (i.e. Like username and Password) and then every time you validate user and options.
Another way you can put a hidden field with correct option and user mapped. And every time you can matched user selected option with hidden field value. This is not secure method.

Using concatenated variables individually for database fields

I am new to stackoverflow and am after a little help. I have already tried searching for what I am about to ask, but cannot find any relevant topics, so here goes:
I have a PHP page, that gets a list of venues and it's town/city from a table within a MySQL database, which I have then concatenated to populate a dropdown, e.g. each <option> will display "[venue], [town/city]".
What I am trying to do is when the user selects one of the options, I want to store the [venue] and [town/city] as separate fields in another table within the MySQL database.
I would really appreciate any help.
More details might be needed. For instance do you need to know how to insert records on database? or are you also having trouble getting values of option tag?
But from what I understood:
First remember to set value attribute of option tags:
<option value="venue,town">venue,town</option>
Then after submitting the form, you can slice the returned string.
Assume you stored "venue,town" inside a variable named $str
$results = explode(",",$str);
$results will be an array with two elements. $results[0] contains "venue" and $results[1] contains "town"
I am not sure how much it helped but you can give more details and I'll get back
I think the best way is to put the datarecord ids (primary key value) into the value attribute of the <option> tags, then on the server side requery the data of the selected id from the database. This way your form can't be manipulated with unwanted data.
To be more clear, I would do it like in this simplified semi pseudocode:
<?php
$action = isset($_GET['action']) ? $_GET['action'] : null;
if($action == "save") {
$id = $_POST['venue'];
if(!empty($id)) {
/* fetch data belonging to $id from database and then save venue and town/city
as separate fields in another table */
}
}
/* fetch all data for the selectbox from the db and store it in $data */
?>
<form action="?action=save" method="post">
<select name="venue" size="1">
/* iterate through $data and create $id and $caption */
<option value="<?php echo $id; ?>"><?php echo $caption; ?></option>
/* iteration end */
</select>
<input type="submit" value="save" />
</form>

Post multiple values from database, in one Option

I am looking to populate a drop down field with a list of names from a database, and when an option is selected from that drop down, it will post all its values in the row, belonging to that chosen option.
This is probably hard to describe/understand, so to help illustrate, this is my table row:
I then proceed to populate the dropdown, and associate its value to whatever the selected option is posted
//////db_conx is db connection //////main_meal is table name
<form action="#" method="post">
<?php
$dropdown = $db_conx->query("SELECT * FROM main_meal") or die ("somethings broken");
while($array[] = $dropdown->fetch_object());
//echo '<option value ="'.$record['Mname'].'">'.$record['Mname'].'"</option>';
array_pop($array);
?>
<select name="changeCal">
<?php foreach($array as $option) :?>
<!--//get chosen value in drop down, and get its calories-->
<option value="<?php echo $option->calories;?>"><?php echo $option->Mname; ?></option>
<?php endforeach; ?>
</select>
This works great for one value, such as calories, in the above code, but I need more values.
For example, if choose Healthy egg and chips, the value will post 218, as the loop only associates calories and names at the moment.
I attempted various things, like this post:How to get multiple values from a single <select> variable in HTML/PHP?
But the foreach errors.
How can I something similar to what I have done, but store multiple values from one chosen option?
Thank you
Well, I think I understood your problem, but I think that the way you want to use is not usable, maybe I recommend that you put the id in the value of the option in the < select> and then with php you can get all the data from the data base.
For me that is the best way, but if you want do it like the example that you show, you can make an string, for example:
<option value="id:5_calories:258_protein:11g">Healthy eggs & Chips</option>
with your php should look like:
echo '<option value="id:'.$option->id.'_calories:'.$option->calories.'_protein:'.$option->protein.'">'.$option->Mname.'</option>';
you can make bigger the string with others values that you want to put.
In the backend when you send the select you can catch the data with a:
$myArray = explode("_", $_POST["changeCal"]);
Then you will get an array with values like:
$myArray[0]; // id:5
$myArray[1]; // calories:258
$myArray[2]; // protein:11g
Then if you need for example the calories you can make an explode like:
$calories = explode(":",$myArray[1]);
And you will have:
$calories[0]; //calories
$calories[1]; //258 <= Here are the calories.
Maybe if you want to do it of that way, this can be the easiest way, but I recommend send the ID.
Let me know if you need more help. Regards, Have a nice day.

submit all users values from form into db

This gives lists all people in the db and give a drop down for each one of them i want to make it so when i hit one submit button it enters individual values for each person.
so if you make yes for bobby no for mark and yes for dustin you can the pres submit and it will enter that for there values
$results = mysql_query("SELECT * FROM `$tabeluser` WHERE buss='$buss' ORDER BY id DESC LIMIT 1");
while($rows = mysql_fetch_array($results) )
{
fn = $_POST['firstname'];
echo $fn;
?>
<form>
<select name="check">
<option>no</option>
<option>yes</option>
</select>
<?php
<input type="submit" name="submit">
?>
<form>
<?php
}
mysql_query("INSERT INTO `$fn` (buss) VALUES ('$_POST[check]')");
First of all, you create a <form> and a submit button for each of the records you have. That is wrong, since you want to update multiple values at once.
What it should look like would be:
<form>
<?php
while($rows = mysql_fetch_array($results)) {
print '<select name="check[]"> .. </select>';
}
?>
<input type="submit" name="submit" />
</form>
Secondly, your code is formatted as if you are expecting to get $_POST[check] right after sending the code to the browser. That is not how PHP works. You need to separate the logic of having posted values, before printing the actual page contents. PHP is server side, which means that it won't get any data, unless the script is called with it from the beginning. So, that should look something like:
<?php
if (isset($_POST["check"])) {
// handle posted data.
}
else {
// show form
}
// or show form here, without an else, if you want to always show a form,
// even when you have posted values.
?>
Last but not least, you need to find a way to know which posted value belongs to each of your records. The way you have it now (<select name="check">') it will just return you one single value.
If you write it the way I intentionally did above (`) you will get all values, but still you won't be able to easily recognize which value is for each record.
Instead, you may want to do a final result of something like:
<?php
// get mysql records into an array (say $my_array)
if (isset($_POST["submit"])) {
foreach($my_array as $record) {
if (isset($_POST["select_of_id_".$record["id"])) {
// insert additional value into db
}
}
}
print '<form>';
foreach($my_array as $record) {
print '<select name="select_of_id_'.$record["id"].'">';
print '<option value="0">no</option><option value="1">yes</option>';
print '</select>';
}
print '<input type="submit" name="submit"/>';
print '</form>';
?>
Changes required in your code :-
<select name="check[]">
<option value="<?php echo $userId;?>_0">no</option>
<option value="<?php echo $userId;?>_1">yes</option>
</select>
You should make changes in you DB It help to easy maintaing your data.
Create new table where you can save multiple user check data with respective Post
for e.g post_id user_id check
101 111 0
101 112 1
How you can store data from you html
In you post array you will get check array in which you will get multiple check value like this
101_0 if no selected and 102_1 if yes selected. Now you need to explode this value.
$_POST['check'] = array(0 => `101_0`, 1 => 102_1);
Inside loop you can extract userid and respective checked value.
for e.g
$checked = explode('_','101_0');
$userId = $checked[0];
$check = $checked[1];

Changing options in second drop down menu by user input in first drop down menu

Thanks for taking time to look at this.
I have two drop down menus. The first is a list of clients, the second is a list of projects.
All projects are tied to just one client, so I'd like for the code to get user input for the client, then read that value, and modify the PHP code to only print out the values in the second drop down menu that correspond to the client selected.
Here's some code. For the first drop down menu:
<div class="item">
<label for='clSel' id='tsClLabel'>Client:</label>
<select name='clSel' id='wClient' onChange="bGroup();">
<option></option>
<?php
$cQuery = "SELECT * FROM Clients ORDER BY Client_Name";
$cResult = mysql_query($cQuery);
while($cData = mysql_fetch_assoc($cResult)) {
echo '<option id="Cid" value="'.$cData['Id'].'">'.$cData['Client_Name'].'</option>';
}
?>
</select>
Here's my jQuery function to get the user-selected value from the first drop down:
<script>
function bGroup(){
val1 = $("#wClient").val();
// window.alert(val1);
// $('#div1').html(val1);
return val1;
}
</script>
And the code for the second drop down menu:
<label for='billGroupId'>Billing Group: </label>
<select name='billGroupId'>
<option value=''></option>
<?php
$sql = "SELECT * FROM Billing_Groups ORDER BY Client_Id, Name";
$sth=$dbh->prepare($sql);
$sth->execute();
while ($row = $sth->fetch())
{
if ($row['Name']!= ''){
echo "<option value='".$row['Id']."' > ".$row['Name']."</option>";
echo "<script> bGroup(); </script>"
}
}
?>
</select>
I know I need to include a WHERE statement in the second drop down menu
Basically Select * FROM Clients WHERE Client_ID == $jsVAR.
I already have the value I need in the var1 JavaScript variable. How can I get this little piece of data either read by PHP or sent to PHP via JS code?
Thanks!!
You can SELECT all records from the database, and then insert them to your page HTML using json_encode(). Something like that:
<?php
$sql = "SELECT * FROM Billing_Groups ORDER BY Client_Id, Name";
$sth=$dbh->prepare($sql);
$sth->execute();
$projectData = array();
while ($row = $sth->fetch())
{
if ($row['Name']!= ''){
$projectData[$row['Client_Id']][] = $row;
}
}
echo '<script type="text/javascript">var projects=', json_encode($projectData), ';</script>';
?>
Then, in your JS, you use the variable projects as an associative array (object), eg.:
<script type="text/javascript">
for (p in projects[clientId]) {
alert(projects[p].Name);
}
</script>
Tricky one,
You have a choice. One way is to use Ajax to grab the second level menu structure upon getting the first level choice, and populate the second level once that succeeds. That's likely to be a problem, as there will likely be some sort of network delay while that happens, of which you have no control (unless you are in a closed environment). So from a user point of view it could be counter intuitive and sluggish feeling, especially on a slow connection or shared hosting solution where timings can vary enormously.
The other way is to somehow pull all values possible and filter them (so hide the ones that don't apply) using jQuery, perhaps utilising classes or some other attribute as a method of filtering data. Using jQuery you can assign data to elements so you could also use that too. The second method may not be so good if there's a lot of data (can't tell from the scenario you've described). Looking at your second level code I don't see a WHERE condition so I'm not sure how the value from the first level is affecting that of the second level, so it's hard to know how to deal with that for this method.

Categories