I have a HTML dropdown list populated by PHP as following:
<form name="selectOccupation" method="post" action="specific_occupation.php">
<div align="centre">
<select name="occupation_dropdown" id="occupation_dropdown">
<?php
include "connection.php";
$sql = mysql_query("SELECT DISTINCT Occupation from patient_info");
while ($row = mysql_fetch_array($sql)) {
echo "<option value=".$row['Occupation'].">".$row['Occupation']."</option>";
}
?>
</select>
</div>
<br>
<br>
<input type="submit" name="submit" value="Proceed"/>
</form>
In the specific_occupation.php file, I have this code:
<?php
include "connection.php";
$selectedoccupation = $_POST['occupation_dropdown'];
echo $selectedoccupation;
$myquery = "SELECT patient_info.Name, test_info.DateOfTest FROM `patient_info`,`test_info` WHERE patient_info.PatientID = test_info.PatientID AND patient_info.Occupation = '$selectedoccupation' ";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
$tempdata = json_encode($data);
?>
This works fine if an occupation without any white space between them like "carpenter" is selected from the dropdown menu but doesn't work for "sales person". How can the $_POST be used for occupations with white spaces??
Thanks in advance !!
You're building your HTML wrong. You've got it as:
<option value=Sales Person>
^^^^^---what will get sent as the value
^^^^^^---some wonky unknown/non-standard attribute
This is incorrect. HTML now requires that ALL attributes be quoted:
<option value="Sales Person">
and even when the quotes weren't required, you still had to have the quotes to handle "spaced" data like this.
PHP post replace some characters such as - with whitespaces.
You can try urlencode($var) in your PHP script.
Related
I tried to create a simple bar chart in D3 taking data from database. The idea is to fetch year and value from the database using the selection buttons of parameters and country and display it in the form of simple bar chart. I have two selection buttons and a submit button. The code for that is like this :
<form action ="data.php" method ="post">
<tr>
<th valign="bottom">Select country:</th>
<td >
<select name="country" class="">
<option value= "NPL">Nepal</option>
<option value= "IND">India</option>
</select>
</td>
<th valign="bottom">Select parameters:</th>
<td >
<select name="indices" class="">
<option value= "foodfinal">Vulnerability on food</option>
<option value= "waterfinal">Vulnerability water </option>
</select>
</td>
<td valign="top">
<input type="submit" class="action" />
</td>
</tr>
</form>
Foodfinal and waterfinal are the names of tables in the database called 'Climate'. NPL and IND are the countrycodes. My PHP code ( data.php ) is like this :
<?php
$username = "root";
$password = "";
$host = "localhost";
$database="climate";
$country="AFG";
$country=$_POST["country"];
$indices=$_POST["indices"];
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "SELECT `year`, `values` FROM `$indices` WHERE `countrycode`= '$country'";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
include("linegraph.html");
mysql_close($server);
?>
My problem is that linegraph.html had been working well before the use of the selection forms but this time, it only displays the output of data.php which looks like this.
{"year":"1995","values":"0.525999"},{"year":"1996","values":"0.570037"},{"year":"1997","values":"0.563966"},{"year":"1998","values":"0.513896"},{"year":"1999","values":"0.5346"},{"year":"2000","values":"0.552691"},{"year":"2001","values":"0.545319"},{"year":"2004","values":"0.543972"},{"year":"2005","values":"0.543299"},{"year":"2006","values":"0.546682"},{"year":"2007","values":"0.550066"},{"year":"2008","values":"0.549449"},{"year":"2009","values":"0.548832"},{"year":"2010","values":"0.548215"},{"year":"2011","values":"0.547536"},{"year":"2012","values":"0.547536"}]
Would you please help me.
change this
include("linegraph.html");
To ( as a best practice thing if the "include" is required to display the page just use require )
require("linegraph.html");
And add at the top of the php
ini_set('display_errors', 1);
You will probably find your page missing ( at the very least your life will be easier with error reporting turned on )
oh and change this part too,
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
To this
$data = array();
while ( false !== ( $row = mysql_fetch_assoc($query))){
$data[] = $row;
}
It probably won't fix your problem ( hard to do without the other html page ) but its the preferred way to do this type of loop.
Update: Here you can't pass both html and json the way you are ( just dawned on me ) you have to pick one. Your problem is a structural one, as you cant do both things at the same time, where does the json data go, it just floats on top of the html? Sorry but it wont work like that, either you already have the html and fill it in with the returned json data, or you build the html with the data already in it and send it back.
change this
echo json_encode($data);
include("linegraph.html");
to ( now you are sending valid json / with the html but you'll have to assemble it client side )
ob_start();
include("linegraph.html");
$html = ob_get_clean();
$responce = array( 'data'=>$data, 'html'=>$html );
echo json_encode($responce);
At the very least your output will change. Hard to say how to do it ( again ) without the other page.
Ok,,,, when I asked to echo something at the bottom did you do this?
echo json_encode($data);
include("linegraph.html");
mysql_close($server);
echo "works";
?> //id remove this end tag it's not needed and can cause problems if there is space ( line returns ) after it. Because it will make you json which you may or may not need invalid.
Oyyy. this is .. uhh
if ( ! $query ) {
echo mysql_error();
die;
}
you can just do like this.
if ( ! $query ) {
die ('Query error' . mysql_error());
}
I'm trying to insert multiple values in the database using select list. What I got so far:
HTML
<form enctype="multipart/form-data" action="" method="post">
<select name="cars[]" multiple="multiple" style="width:300px">
<?php
$getcars = mysql_query("SELECT cars_id, cars_name FROM car");
while ($row = mysql_fetch_assoc($getcars)) {
$car_id = $row['cars_id'];
$car_name = $row['cars_name'];
?>
<option value="<?php echo $car_id ?>"><?php echo $car_name ?></option>
<?php } ?>
</select><br />
<input type="submit" name="submit" value="Submit"/><br/>
</form>
PHP
$cars= $_POST['cars'];
echo $cars;
for($i = 0; $i < count($cars); $i++){
echo $cars[$i];
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]]')");
}
Unfortunately it doesn't work, I tried to print $cars to check the resulted value. It prints "Array", and when I tried to print $cars[$i] it prints nothing.
Does anyone know what the problem is?
There is an extra closing bracket that should be removed. You are not checking if your query was successful or not.
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]]')");
should be:
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]')") or die(mysql_error());
Since $cars is an array, you can print its content using print_r or var_dump:
print_r($cars);
var_dump($cars);
Useful reading:
How to get useful error messages in PHP?
mysql_* functions are deprecated
You have error $cars[$i]] and need change $cars[$i]
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]]')");
fix php for you with good sql
$cars= $_POST['cars'];
echo $cars;
foreach($cars as $i => $cars_name){
echo $cars_name;
$carGroups = mysql_query("INSERT INTO car_groups SET `fieldcompany`='{$company}', `fieldcars`='{$cars_name}'");
}
I'm retaining values in form elements after a form submit. I've got it to work fine with a select box using the following:
<select name="BranchManager" class="formfield" id="BranchManager"onchange="document.forms[0].submit();SEinit();"><option value="">-- Select Manager --</option>
<?php
$area = $_POST['Area'];
if ($area); {
$BMquery = "SELECT DISTINCT Branch_Manager FROM Sales_Execs WHERE AREA = '$area' ".
"ORDER BY Branch_Manager";
$BMresult = mysql_query($BMquery);
while($row = mysql_fetch_array($BMresult))
{
echo "<option value=\"".$row['Branch_Manager']."\">".$row['Branch_Manager']."</option>\n ";
}
}
$branchmanager = $POST['BranchManager'];
?>
<script type="text/javascript">
document.getElementById('BranchManager').value = <?php echo json_encode(trim($_POST['BranchManager']));?>;
</script>
Which works fine (apologies if it isn't the cleanest/most efficient code, I'm doing my best!) The next field is a text field that needs to be populated based off the Branch Managers name above. So I've used :
<input name="BranchNum" type="text" class="formfield" id="BranchNum" size="3" maxlength="3" />
<?php
$bm = $_POST['BranchManager'];
if ($bm); {
$BNumquery = "SELECT DISTINCT BRANCH_NUM FROM Sales_Execs WHERE Branch_Manager = '$bm' ";
$BNumresult = mysql_query($BNumquery);
}
$branchnum = $POST['BranchNum'];
?>
<script type="text/javascript">
document.getElementById('BranchNum').value = <?php echo json_encode($BNumresult);?>;
</script>
Which isn't working... where am I going wrong here?
why are you having semicolons after if condition checks?
if ($bm);
if ($area);
This will always terminate the statement and whatever is in the curly braces will always get executed irrespective of the value in $bm or $area
You need mydql_fetch functions to retrive data from $result.
if($row = mysql_fetch_array($BNumresult))
$branchNum = $row[BRANCH_NUM];
why are you using json_encode when your input tag has size = 3?
You need to put value="<? echo $variableName; ?>" inside the input field
The reason is because a) you're not echoing, and b) you must echo in a different spot than in a select. You must echo in the value portion of the input.
<?php
$bm = mysql_real_escape_string($_POST['BranchManager']);
if ($bm) {
$BNumquery = "SELECT DISTINCT BRANCH_NUM FROM Sales_Execs WHERE Branch_Manager = '$bm' ";
$BNumresult = mysql_query($BNumquery);
}
$branchnum = $POST['BranchNum'];
?>
<input name="BranchNum"
type="text"
class="formfield"
id="BranchNum"
size="3"
maxlength="3"
value="<?php echo htmlspecialchars($branchnum); ?>" />
As per the comments, they are correct; you should not be using mysql_*. Instead, look at PDO; though this is outside the scope of your question.
I have a MYSQL database with a number of fields such as property, bedrooms, size etc
I have two dropdown list with data that is contained within the database
When submitting the options I want a new page to open displaying the results. I am getting the error message mysql_fetch_assoc(): supplied argument is not a valid MySQL and have no idea how to fix this! help much appreciated...I know about SQL injections and looking to rectify this after I get this section working first
HTML
<form method="get" action="submit.php">
Number: <select name="property">
<option value="Aviemore House">Aviemore House</option>
<option value="Dalfaber House">Dalfaber House</option>
</select>
<br>
Name: <select name="bedrooms">
<option value="2">2</option>
<option value="3">3</option></select>
<br>
<input type="submit" value="submit" />
</form>
PHP
<?php
require 'defaults.php';
require 'database.php';
$property = $_GET['property'] ;
$bedrooms = $_GET['bedrooms'] ;
$query = "select FROM properties where property = '$property' & bedrooms = '$bedrooms'";
while ($row = mysql_fetch_assoc($result))
{
$r[] = $row;
}
?>
You forgot to execute your query!
<?php
require 'defaults.php';
require 'database.php';
$property = $_GET['property'] ;
$bedrooms = $_GET['bedrooms'] ;
$query = "select FROM properties where property = '$property' & bedrooms = '$bedrooms'";
$result = mysql_query($query); // <-- You forgot this
while ($row = mysql_fetch_assoc($result))
{
$r[] = $row;
}
?>
Try this instead:
$query = "SELECT * FROM `properties` WHERE property = '{$property}' AND bedrooms = '{$bedrooms}'";
$row=mysql_query($query);
Your sql is malformatted and need to execute the query.
Okay so I have a table called Countries and it looks like this:
---------------------------
|Country | Code |
---------------------------
|Afganastan | AF |
|Ă…LAND ISLANDS| AX |
| etc. | etc. |
---------------------------
The thing that I want to do is create a dynamic menu in which the user chooses a country and that itself gets stored as a value that I can call after the user hits submit.
I did try something here but I'm not sure what its doing because I am still new to PHP and HTML to the point where I just type things in to see what would happen.
Anyways I am really stuck and I tried using google and the search feature in this site and nothing I found worked for me...
The code I tried is this:
<select>
<?php
$result = mysql_query('SELECT Country FROM Countries');
echo '<select name="country">';
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
echo '</select>';
?>
</select>
The result is supposed to look like a dropdown menu with the list of countries from the database in it. But this doesn't work and just shows this in the drop down:
.$row['name']
Which is nothing close to what I want because that's not even a country. when I remove that part of the code, then there is no option for the user to choose, the menu is empty.
EDIT
My code so far that still doesn't work:
<select name = 'country'>
<?php
include ("account.php");
include ("connect.php");
$result = mysql_query('SELECT Code , Country FROM Countries');
while ($row = mysql_fetch_array($result))
{?>
<option value="<?php echo $row['Code']?>"><?php echo $row['Country']?></option>
<?php}
?>
</select>
The include ("account.php"); and include ("connect.php"); lines allow me to connect to my database.
you code should be something like this
$host = "localhost";
$user = "root";
$pass = "yourpassword";
$db = "databasename";
// This part sets up the connection to the
// database (so you don't need to reopen the connection
// again on the same page).
$ms = #mysql_connect($host, $user, $pass);
if ( !$ms )
{
echo "Error connecting to database.\n";
}
// Then you need to make sure the database you want
// is selected.
#mysql_select_db($db);
<form method = "POST" action = "abc.php">
<select name = 'country'>
<?php
$result = mysql_query('SELECT id , name FROM Countries');
while ($row = mysql_fetch_array($result))
{?>
<option value="<?php echo $row['id']?>"><?php echo $row['name']?></option>
<?php}
?>
<input type = "submit" value = "Submit">
</form>
Now in php use this
echo '<pre>';
print_r($_POST);
And you will see what user selected. Check your settings there might be some problem.
Your single and double quotes are messing you up:
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
should be:
echo "<option value=\"" . $row['id'] . "\">" . $row['name'] . "</option>";
You can use a single quote around your script but when you jump out of it to do the $row['id'] and $row['name'] you are running into issues because it thinks you are jumping back into your quoted code... Either use my example above, starting/ending with double-quotes and escaping all double-quotes inside that need to display, or escape your single quotes in the $row[\'id\'] and $row[\'name\']
Thant should help you out.
Try this code
<?php
$result = mysql_query('SELECT * FROM Countries');
?>
<select name="country">
<?php
while ($row = mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
<?php
}
?>
</select>
Firstly your table doesn't have a column id. Try changing your query like
SELECT Country, Code FROM Countries
Then the code and the html should be like this
<?php
$host = "localhost";
$user = "user"; //username
$pass = "pass"; //password
$db = "db"; //database
$con = #mysql_connect($host, $user, $pass);
if ( !$con )
{
echo "Error connecting to database.\n";
}
#mysql_select_db($db);
?>
<select name="country">
<option value="0" selected="selected">Choose..</option>
<?php
//echo '<select name = \'country\'>';
$result = mysql_query('SELECT Country, Code FROM Countries');
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['Code'].'">'.$row['Country'].'</option>';
}
?>
</select>
<select>
<?php
$result = mysql_query('SELECT Country FROM Countries');
echo '<select name="country">';
$row = mysql_fetch_array($result)
for ($i=0; $i<count($row ); $i++)
{
echo '<option value="'.$row[$i]['id'].'">'.$row[$i]['name'].'</option>';
}
echo '</select>';
?>
next page use print_r($_POST);
or var_dump($_REQUEST);
If you are using mysql_fetch_array you can use either the field names or their selected index to read them from the fetched row. You can also use either the sprintf or printf functions to merge content into a string to help keep the HTML fragment clean of the quotes needed to merge in values otherwise.
$result = mysql_query('SELECT Country, Code FROM Countries');
while ($row = mysql_fetch_array($result)) {
printf('<option value="%1$s">%2$s</option>',
$row['Code'], $row['Country']);
}
Your SQL statement selected only 'Country' from the 'Countries' table; as a result, it's impossible for you to use $row['id'] and $row['name'].
Use this instead:
echo '<select name="country">';
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['Code'].'">'.$row['Country'].'</option>';
}
echo '</select>';
?>
That should solve your problem.
I figured out the problem I was having. The first being that there was an extra select tag in the page and the second that the file was saved as a html page instead of a php file. Thank you to everyone that helped me figure this out!
Try my code, I'm using this and it really works... just change the values...
<?php
include ('connect.php');
$sql = "SELECT * FROM casestatusfile";
$result = mysql_query($sql);
echo "<select name = 'txtCaseStatus'/>";
echo "<option value = ''>--- Select ---</option>";
$casestatus = $_POST['txtCaseStatus'];
$selected = 'selected = "selected" ';
while ($row = mysql_fetch_array($result)) {
echo "<option " .($row['CASESTATUSCODE'] == $casestatus? $selected:''). "value='". $row['CASESTATUSCODE'] ."'>" . $row['CASESTATUS'] ."</option>";
}
echo "</select>";
?>
I'm sure that is working because that is the one that i'm using....