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')");
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 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
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.
I have a dropdown lists which the default value is selected. If there is a value there the if statements allow an update to the data. If no value then instead a whole row will be inserted. It works if I hard code the third value as 1. However when I set this to $category_of_taxom1 the insert doesn't work. The Update works fine, so If I manually create the record within the DB, I can update it via the update SQL shown below. But if I try INSERT no luck? (I Have hard coded the first 3 items to be inserted, the third should be the variable mentioned above.
I have this select list
<select name="categorySelect1fromDB" >
<option value ="">EMPTY</option>';
<option value="1" <?php echo ($category_of_taxom1 == 1)?"selected":""; ?>>A</option>
<option value="2" <?php echo ($category_of_taxom1 == 2)?"selected":""; ?>>B</option>
<option value="3" <?php echo ($category_of_taxom1 == 3)?"selected":""; ?>>C</option>
<option value="4" <?php echo ($category_of_taxom1 == 4)?"selected":""; ?>>D</option>
</select>
And this set of statements.
if(isset($_POST['save']))
{
$category_of_taxom1 = $_POST['categorySelect1fromDB'];
$number_of_taxom1 = $_POST['number_of_taxom1'];
if (!empty($category_of_taxom1)){ //This is the value fromDB if not empy then do below else do last
pg_query("UPDATE record_tbl SET category_of_taxom ='$category_of_taxom1', number_of_taxom ='$number_of_taxom1' WHERE sheet_id = '$sheet_id' AND line = 1");
echo "Updated!";
} else
{
pg_query("INSERT INTO record_tbl (line, taxom_id, category_of_taxom, number_of_taxom, sheet_id) VALUES (1,1,'$category_of_taxom1','$number_of_taxom1','$sheet_id')");
echo "New Record ?Saved!";
}
}
This is an example of a working pgsql line I use else where in my site:
$sql8 = "INSERT INTO record_tbl (line, taxom_id, category_of_taxom, number_of_taxom, sheet_id) VALUES (8,8,'$_POST[gammarus_numbers]','$_POST[countgammarus]','$sheetid')";
$result = pg_query($sql8);
The datatype for the field 'category_of_taxom' is most likely set to varchar, meaning it should have quotes around the value when using INSERT. So you can either:
1) Change the datatype of category_of_taxom to integer in your database
2) Include quotes around the value in your INSERT statement:
('1','1','1','$number_of_taxom1',$sheet_id)
Related documentation:
mysql - quote numbers or not?
I should probably delete this question: The quotes were correct, I needed them on each variable. However because the code was so long, i couldnt post it all on here. I had accidentally called that variable twice. So at one point of time it does have something in, but within the same code it may also not. So i ended up having to rename my variable. Not really a good answer, but going to delete it anyway. As this will be too narrow for anyone else.