I created a form that includes a dropdown field
<select name="locationselect" id="locationselect" tabindex="7">
<option value="Location1">Location 1</option>
<option value="Location2">Location 2</option>
<option value="Location3">Location 3</option>
<option value="Location4">Location 4</option>
</select>
Upon submission I want to pull the location they selected from the dropdown and print a specific row from my MySQL database that would show them an address. So if they select Location 1 it would show:
Company Name
1234 ABC Street
New York, NY 12345
But if they select Location 2 it would show:
Other Company
5678 XYZ Street
San Francisco, CA 12345
And so on for 99 different locations.
Here's what I started with but I'm missing a variable defining the array $fulladdress - I am new to MySQL so I'm not even sure what to put after Select? Is there a row number or can I put the contents of the first column or what type of ID?
switch($_GET['locationselect']){
case 'Location1':
mysql_query("SELECT ____ FROM locations");
break;
case 'Location2':
mysql_query("SELECT ____ FROM locations");
break;
}
while($row = mysql_fetch_array($fulladdress))
{
echo ($row['PlaceName']." Office Building<br>".$row['Address']."<br>".$row['City'].", CA
".$row['Zip']."<br><br>");
}
Any help for how to solve this problem would be greatly appreciated. I know my code is messy but I'm hoping you can get the idea of what I'm trying to do.
Thank you!!
I'm not too sure about using the case statement, what you can do is a parameterised query. So it would be:
mysql_query("Select fulladdress from Location where location ='" . $location . "'");
Using the dropdown value, you can pass that into the $location variable.
But if you're displaying so many values in a search box. You might want to look into something like jQuery Autocomplete. Of course after you've escaped the input.
Edit:
The above method isn't very secure, you should really use mysqli. And use something like prepared statements:
$stmt = $dbConnection->prepare('SELECT * FROM locations WHERE name = ?');
$stmt->bind_param('s', $name);
For more information check this post on SQL Injection
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 need PHP to take information from a form and compare it with a database information in this way:
The user selects option X out of N options. Each option has a specific column in the database with a value stored in it. The value stored in the database assigned to the option chosen by the user is assigned to a variable.
Here is what I´ve done:
This is my form option:
Cuál es tu color favorito?
<select name="colour">
<option name="redcolour">Rojo</option>
<option name="bluecolour">Azul</option>
</select>
I´ve created a variable for the option selected by the user:
$colour=$_POST['colour'];
So doing echo $colour; prints red or blue according the what the user has selected.
I have a mysql database with a table "datos" like this:
datos (id, red, blue) it has a single row whith these values (1, 100, 200). Those values are the points assignated to each option.
I need to have a variable $whatever with a value 100 if the user selected blue or 200 if the user selected red.
If I do this:
$consulta=mysqli_query($conexion,$query)
if($_SERVER['REQUEST_METHOD']=='POST') {
if($result=mysqli_fetch_assoc($consulta)){
echo $result['red'];
echo $result[$_POST['red']];
}
I get 100 in the first echo, and get nothing in the second one.
My sql query is:
SELECT * from datos
Use the query:
SELECT * FROM datos
Fetch the result row into an associative array, e.g. using MySQLI:
$row = mysqli_fetch_assoc($result);
or PDO:
$row = $stmt->fetch(PDO::FETCH_ASSOC);
Then you can get the value you want with $row[$_POST['colour']]
I´ve solved it using a switch:
switch ($colour) {
case 'redcolour':
$colour=$result['red'];
break;
case 'bluecolour':
$colour=$result['blue'];
break;
}
Posting it here just in case anyone needs it.
FYI, I coudn´t use name="redcolour" but value="redcolour" for options. "name" works only for the select.
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.
Ok I have a dropdown list, and I'd like to store the chosen option to the database through a variable defined on the beginning of the code:
$campus_name = isset($_POST['campus']) ? asi($_POST['campus']) :"";
The code for the dropdown list is as follows:
<select name="campus" id="campus">
<option>Choose</option>
<option value="1">Belaruz</option>
<option value="2">Normdale</option>
So how do I store that to the table campus using the variable $campus_name to store it?
So if I had a table called campus and it only had one column. I would use the mysql_query command. I used arbitrary names in my example but I hope you get the picture.
$campus_name = isset($_POST['campus']) ? asi($_POST['campus']) :"";
$link=mysql_connect('localhost','ID','Password');
mysql_select_db('College', $link);
mysql_query("insert into campus(campusID)values('$campus_name')");