I have a form with a select multiple like this:
<select name="states[]" size="5" multiple>
<option value="2">state 1</option>
<option value="3">state 2</option>
<option value="4">state 3</option>
<option value="5">state 4</option>
<option value="6">state 5</option>
</select>
I want to have the possibility to choose more than one state, and then make the query to my database and show the description of each state chosen.
So this is what I have to make the query using PHP and MySQL:
$state = $_POST['states'];
$data = mysql_query("SELECT * from states WHERE id_state = '$state'",$db);
while($row = mysql_fetch_array($data)){
$result=$row['description'];
}
echo $result;
I have that code and it doesn't show anything.
How can I fix this problem?
Try this
$state = $_POST['states']; // return Array
$count_states = count( $state );
if( $count_states > 0) {
$states = implode( ',', $state);
$data = mysql_query("SELECT * from states WHERE id_state IN ($states)",$db);
while($row = mysql_fetch_array($data)){
echo $row['description'];
}
}
This would require a simple foreach to go through the array and get results based on each value as such,
foreach($_POST['states'] as $state) {
$data = mysql_query("SELECT * from states WHERE id_state = '$state'",$db);
$row = mysql_fetch_array($data);
echo $row['description'];
}
Also since you're not protecting your query in some sort and are using mySQL which has been deprecated as of PHP 5.5.0, I suggest you looking into PDO or mySQLi Prepared statements
$_POST['states'] holds an Array with all the ID's of the selected states.
Off course you can query your database for every posted state_id, but way nicer (and faster) would it be to make a query which looks like this and uses only one query:
SELECT description FROM states WHERE id_state=1 OR id_state=2 etc etc
This also might be a good point to start using a database abstraction layer like PDO.
As the number of posted states is variable, we need to make the statement also variable:
// The [connection setup][2] by PDO is done in $conn, with some proper exception handlers
// e.g. $conn = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// Fill an array with count() number of elements with value 'id_state=?'
$place_holders = array_fill(0, count($_POST['state']), 'id_state= ?');
//implode the array
$place_holders = implode(' OR ', $place_holders);
// prepare the query
$st = $conn->prepare("SELECT description FROM state WHERE $place_holders");
// execute to above prepared query with the $_POSTED states
$st->execute($_POST['state']);
// traverse the result
foreach($st->fetchAll() AS $r){
// do some magic
}
You could build the string by iterating through the array:
$state = "";
foreach($_POST['states'] AS $s)
{
// Sanitize $s here
$state .= "`id_state` = " . $s . " OR";
}
if($state)
{
$state = substr($state, 0, -3);
$data = mysql_query("SELECT * from states WHERE $state",$db);
while($row = mysql_fetch_array($data)){
echo $row['description'];
}
}
Of course, you should use something like MySQLi or PDO to handle database interaction. They will have ways to sanitize input easily so you can avoid obvious SQL injection.
Tamil has a pretty good IN select method as well. This is just one option.
Example (pages for edit):
//On select_multiple.php (Form):
<?php
//Conn
include('incl_config.php');
//Multiple data to bring
$sql = " select COD_DXS,VALOR_DXS from hc_dxsindromico where ESTADO_DXS='1' ";
$result=#mysql_query($sql);
?>
//In the form select:
<select multiple="multiple" size="7" name="dxsindromico[]"> //look yes or yes brackets []
<option value="" selected="selected">Choose one or more options</option>
<?php
while($row=mysql_fetch_array($result)){
?>
<option value="<?php echo $row['COD_DXS']; ?>" style="color:#F00;"><?php echo $row['VALOR_DXS'];?></option>
<?php } ?>
</select>
//////////// On grabar_mtr.php ///////////////
<?php
include('incl_config.php');
/*Multiple selection form in HTML5, PHP and Bootstraps
Created by: www.nycsoluciones.com
Version: 1.1*/
//we use a foreach to traverse the array (values of our select and save them in the table dxsindromico_data)
if(isset($_POST['dxsindromico'])){
foreach( $_POST['dxsindromico'] as $insertar ) {
//echo $insertar;
$sqli="insert into dxsindromico_data(DXSINDROMICO_HC) values('$insertar')";
//echo $sqli;
//exit;
$resulti=mysql_query($sqli);
}
} else{
foreach( $_POST['dxsindromico'] as $insertar ) {
//echo $insertar;
$sqli="insert into dxsindromico_data(DXSINDROMICO_HC) values('$insertar')";
$resulti=mysql_query($sqli);
}
}
?>
Related
I'm getting a weird result when i try to implement the PHP inside a HTML
The config is literally my DB connection, other scripts work well but only for this matter i couldn't figure out.
Maybe I missed out some elements.
<select name="country">
<option value="" disabled selected style="display: none;">All Japan Cities</option>
<?php
include 'scripts/config.php';
$query = "SELECT state FROM product";
$result = mysql_query($query);
$count = count($result);
if (!empty($count)) {
while($row = mysql_fetch_array($result))
{
$state = $row['state'];
echo "<option value='$state'> $state </option>";
}
} else {
echo '<option>No data</option>';
}
?>
</select>
I keep on getting no data for my select statement where I have 3 results in my db.
I don't think you can do a count() on a mysql result set like that.
Try using mysql_num_rows instead, like this:
....
$count = mysql_num_rows($result);
if (!empty($count)) {
....
Also, as others have said, these old mysql_ functions are deprecated, so you should probably switch to mysqli or PDO if that is practical as well.
I have a page where I am wanting to allow a user to select fields from a select that exist in a table, then display the contents of those fields on screen. I have set-up the select like so
<select name="queryfields" size="12" multiple="multiple" tabindex="1">
<option value="firstname">firstname</option>
<option value="lastname">lastname</option>
<option value="address">address</option>
<option value="phone">phone</option>
And I know to discover what options were selected I can use this:
<?php
header("Content-Type: text/plain");
foreach ($_GET['queryfields'] as $selectedOption)
echo $selectedOption."\n";
?>
And that gives me an array of the fields selected. However, how do I then parse the array to generate my full query? For example, let's say that firstname, lastname were selected. I would then want to build my query like this:
Select firstname, lastname from employeedata
Unknown to me, is how to get the data from the array into a select statent like my above code snippet.
Try This:
$sql = '';
$selected_fields = array();
foreach ($_GET['queryfields'] as $selectedOption){
//echo $selectedOption."\n";
$selected_fields[] = $selectedOption;
}
if(!empty($selected_fields)){
$fields = implode(',', $selected_fields);
$sql = 'SELECT '.$fields.' from employeedata';
}
//print query if it is not empty
if(!empty($sql)){
echo $sql;
}
You can use PHP implode() function.
<?php
header("Content-Type: text/plain");
$q = "SELECT ".implode(', ', $_GET['queryfields'])." FROM employeedata";
?>
But there are some possibilities for SQL injection. You should read the about that before proceeding. How can I prevent SQL injection in PHP?
You can create a design like the below
<?php
header("Content-Type: text/plain");
$filter = array_filter($_GET['queryfields'], function($val) {
$allowedFields = array(
'firstname',
'lastname',
'address',
'phone',
);
return in_array($val, $allowedFields);
}
$q = "SELECT ".implode(', ', $filter)." FROM employeedata";
?>
I get confused for post variable to sql query,
here is sample of my report.php code
<form action="report.php">
<select id="status" name="status">
<option value="MARRIED">married</option>
<option value="SINGLE">Single</option>
<option value="ALL">ALL</option>
</select>
<input type="submit" value="Seach">
</form>
<?php
$status= $_GET['status'];
// Create DB connection
$sql = "SELECT * FROM member WHERE status ='$status'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<B>id: </B>" . $row["user_id"]. " -- <b>Date Record:</b> " . $row["created"]. " -- <b>Last Seen</b> " . $row["last_seen"]. " -- <b>Status: </b> "
}
} else {
echo "0 results";
}
$conn->close();
?>
How do i Query If "ALL" condition is Selected?
I dont know the PHP so this is not the exact code but concept should be like this
if( $status == 'ALL' )
$sql = "SELECT * FROM member";
else
$sql = "SELECT * FROM member WHERE status ='$status'";
It would be very wise in this case to store the $status variable in POST instead, since the SQL query depends on what value is stored in the URL, and is thus exposed to the user.
Another thing, since you are dealing with legacy code here is to make extra sure that you filter the user input and SQL query as much as possible. The thing with using older and obsolete functionality is that you will still be vulnerable to XSS and SQL injection attacks regardless of the precautions you take so it is highly recommended you go with either the MySQLi or PDO (PHP Data Objects) extension instead as these offer more stable and advanced functionality.
$status = htmlspecialchars($_GET['status'], ENT_QUOTES);
$where = '';
if ($status != 'ALL') {
$where = 'WHERE status = "$status"';
}
$sql = mysql_real_escape_string('SELECT * FROM member ' . $where);
$results = mysql_query($sql);
In PHP file
<?php
$status= $_GET['status'];
if($status == 'ALL'){
$where = '';
}else{
$where = 'status = '".$status."' ';
}
// Create DB connection
$sql = "SELECT * FROM member WHERE ".$where." ";
?>
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.
I am writing a reservation system. On the main page I would give a choice of category, viewed the equipment available for booking.
For example I have code like this:
<select>
<option value = "a">A</option>
<option value = "b">B</option>
<option value = "c">C</option>
<option value = "d">D</option>
<option value = "e">E</option>
</select>
I wish that each choice was associated with a separate query to the database, and that was the result of a query dynamically displayed on the screen.
It would be great if you could show me some sample code.
Regards
$query = mysql_query("SELECT * FROM choices");
while($row=mysql_fetch_assoc($query)) {
echo '<option value="'.$row['value'].'">'.$row['value'].'</option>';
}
If you need separate query for each choice the code doesns't change much:
$query = mysql_query("(SELECT * FROM choices) UNION (SELECT * FROM choices1) [etc]");
while($row=mysql_fetch_assoc($query)) {
echo '<option value="'.$row['value'].'">'.$row['value'].'</option>';
}
There are two parts to your question; 1 - Detecting which query to run and 2 - Displaying the results dynamically.
Part 1: Detecting which query to run:
Given hard-coded choices and no parameters for the query, using your above code, you can determine which query to run using the following:
For the HTML part, as part of a form, create the select as you did above (but with a name)
<select name="querySelect">
<option value="a">A</option>
<option value="b">B</option>
</select>
And in the PHP:
$querySelect = $_GET['querySelect'];
switch($querySelect)
{
case 'a':
$sql = "SELECT * FROM TableA";
break;
case 'b':
$sql = "SELECT * FROM TableB";
break;
}
$results = mysql_query($sql);
Part 2: Displaying the results dynamically
With the $results, what you do with the data very much depends on what you want to achieve. At a very basic level, you can do the following to dynamically display a table of the results:
if(mysql_num_rows($results) > 0)
{
$header = false;
print "<table>"
while($row = mysql_fetch_assoc($results))
{
if(!$header)
{
$headings = array_keys($row);
print "<tr>";
for($i=0;$i<count($headings);$i++)
{
print "<th>".htmlspecialchars($headings[$i])."</th>";
}
print "</tr>";
$header = true;
}
print "<tr>";
foreach($row as $value)
{
print "<td>".htmlspecialchars($value)."</td>";
}
print "</tr>";
}
print "</table>"
}
else print "<h1>No Results Found!</h1>";
mysql_free_result($results);
There is still alot not covered in my answer because I can't say what level of detail is required. You will also need to cover things like your connection to MySQL, error handling, formatting of the table...
Update
Hmmm, very interested to know why this has been downvoted. If someone can please explain in comments where I have misinterpreted the question or misguided the user, I would appreciate it.
If you use jQuery the code might look like
<select id="select_id">
<option value = "a">A</option>
<option value = "b">B</option>
<option value = "c">C</option>
<option value = "d">D</option>
<option value = "e">E</option>
</select>
<script type="text/javascript">
$('#select_id').change(function(e) {
// this code send selected value to the server
$.post('url', {selected_value: this.value}, function(response) {
// handle the server's response
});
});
</script>
On server side take the value from $_POST and make a query. And remember - do not trust to data from client-side. You never know who is over there. Always check incoming data and DO NOT use such constructions
$sql = "SELECT * FROM table_name WHERE name = '{$_POST['selected_value']}'";
because there might be any string including those can drop all databases, clear data and so forth.