1

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.

Francesca
  • 71
  • 1
  • 8
  • 1
    It's not considered clean, but you can try [extract](http://php.net/manual/en/function.extract.php). I haven't read too deep into your question, so it might not work for you. – Pyromonk Apr 24 '17 at 00:51
  • Post the output that you want. – Ali Rasheed Apr 24 '17 at 01:06
  • @AliRasheed : I would like each dropdown selection to be a variable, so that if the user selects two options from a dropdown, they would be split. Ex: $ faculty and $alumni. I am building a query based off these to get survey data from the database that matches the user selections. – Francesca Apr 24 '17 at 14:17

2 Answers2

2

[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;
Community
  • 1
  • 1
user2860957
  • 456
  • 1
  • 7
  • 18
  • @tadman Here's some clarification: I would like each dropdown selection to be a variable so that if a user selects multiple values from the dropdown, they can be used for a database query. The database has survey data and the user wants to be able to pull in anyone who matches the selections. Ex: a student who has been placed for an internship at a medical clinic and lives in a certain city. – Francesca Apr 24 '17 at 14:26
  • @Francesca what you trying to achieve it is not that complicated, just give me column name for like student, internship medical clinic i am guessing your are storing city in the city column as i saw in your question, or if i am note here, just check my profile, i posted a answer for similiar question a week ago, get your clue from their, or just give me the column, for example, like you are student, alumni and faculty, in which column you are storing role name, or just post a picture of your database, i hope you understand what i am asking – user2860957 Apr 24 '17 at 18:51
  • I have twelve columns - I'll just give you the first six. I have role(student, alumni or faculty), internship placement, city (generated from database), congressional district (integer), target population and state. What I'm stuck on is how to pass these values to the mySQL query if the user selects more than one. – Francesca Apr 24 '17 at 19:04
  • tried to add you to this previous comment, user2860957 - not working on my end. – Francesca Apr 24 '17 at 19:12
  • @Francesca i edited my answer, and one more thing when last i commented i made two mistakes, i did not realize you are using two submit options with multiple, and one thing are you using different differnt table for different value, if that's the case in the given answer, code will change little bit, but the basic shell will remain the same, let me know if any confusion let me know that as well – user2860957 Apr 24 '17 at 21:13
  • Thank you so much for the clear notes and for the query! I need to adjust it a bit but I understand where I can go from here :) – Francesca Apr 25 '17 at 15:29
  • @Francesca thanks for accepting the answer, i read your another comment, below the another answer, that you may have tweleve select options, that's means you have to repeat the same code tweleve time and that's consider to be bad practise, i dont want to go in to the reason why it is bad practice, but if you have twelve select options in your form, than this answer is not right, let me know if that's the case, i will change my code, so you dont have to repeat the same damm thing again and again, and if in future you have to change it will be problem, so let me know that, i will edit the answer – user2860957 Apr 25 '17 at 18:34
  • Yes, the form has twelve select options -- not sure if I should have each select be in its own form or just iterate through it. – Francesca Apr 25 '17 at 18:38
  • @Francesca you should just iterate through, it will be easier, because if you create tweleve form, you will be in lot more trouble, i am kinda busy, i will post some thing may be after 7 or 8 hours, and if i got the time in between, i will post some thing, in the mean while what you can do ask a new question, in that question, leave the link to this question, so the people get context what kinda of answer you are looking for, and just add it is possible i dont have to repeat the same thing, 15 times, ............ – user2860957 Apr 25 '17 at 18:54
  • .......(read the above comment first)it's not that complicated, and if you want to try your self, just use the print_r($_POST) i think you will be able to do it your self, but make sure you dont write the same code 12 times, for example lets say you have to change some thing in the future, you probably going to miss place or two and than it will be a mess........ – user2860957 Apr 25 '17 at 18:55
  • .........(read the above two comment) this is hint--> You have to run a for each loop, with key and value, and keep on in the loop which key is set, and if that key is set, run the same code, which you have in this answer, and give dyanamic name to the variable or create an array – user2860957 Apr 25 '17 at 18:59
  • @Francesca i edited the answer, please read the comments above as well, – user2860957 Apr 25 '17 at 21:49
  • You are wonderful. Seriously, thank you so much. I'm the only person with any programming knowledge at my job so I've had to turn to stack overflow for help. If I could upvote you (I need more rep points to do so) I would :D – Francesca Apr 25 '17 at 21:52
  • @Francesca thanks for the kind word in the last comment, i feel good about it, and its ok you can not upvote, Thanks and wish you luck – user2860957 Apr 25 '17 at 22:52
0

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();
user2182349
  • 9,569
  • 3
  • 29
  • 41