I have a drop down menu that I use to you choose from and this results in a value given to the next page. I would like to use this value to determine where to select from. So the possible values are car and toys. So I would like to let the user use the drop down menu to choose car which results in the database selecting from car to find the item.. If the user chooses toys I would have them select from toys in order to find the item. When I attempt to use this code I just get an error. If I delete '%item%' the error is gone. Any help would be loved. Thanks.
Submitting
<form action="search.php" method="post">
<select>
<option value>Choose A Item</option>
<option value="car" name="item">Car</option>
<option value="toys" name="item">Toys</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
Searching
$term = $_POST['term'];
$item = $_POST['item'];
$query = mysql_query("select * from '%$item%' where Items like '%$term%'");
if(mysql_num_rows($query) <= 0)
{
echo "<center>No results. Please try another item.</center>";
} else {
while ($row = mysql_fetch_array($query)) {
echo "<p2>";
echo $row['Items'], ' - Location ' .$row['Loc'];
echo '<br/><br/>';
echo "</p2>";
}
}
?>
1.) - don't use mysql_query - its an outdated library and your query as written above is subject to SQL injection - the most common compromise on the internet.
2.) don't use like '%...%' as this can't be indexed and will be horribly slow on any medium size table or greater. try to at least remove the first % to allow indexing.
http://php.net/manual/en/book.pdo.php
I think your query should be changed into: $query = mysql_query("select * from '$item' where Items like '%$term%'");
Related
Okay, I'm reframing this whole question because the earlier version was a bit convoluted.
Here's the scenario:
I have a MySQL table called "churches."
I have a form with four selects. The options are drawn dynamically from the table, so that users can search on four table columns to find churches that fit the criteria (country, state/province, city, presbytery)
I also have working code to get all the table data to display.
What I haven't figured out is how to use the selected option from the form to filter the results.
My current code is below:
<form action="display0506b.php" method="post">
<select name="country">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT country FROM churches");
$query_display = mysqli_query($link,"SELECT * FROM churches");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['country'] . "</option>";
}
?>
</select>
<select name="state">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT state FROM churches WHERE state != ''");
$query_display = mysqli_query($link,"SELECT * FROM churches WHERE state != ''");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['state'] . "</option>";
}
?>
</select>
<input type="submit" value="Go!">
</form>
<?php
if(isset($_POST['country']))
{
$name = $_POST['country'];
$fetch = "SELECT * FROM churches WHERE id = '".$name."'";
$result = mysqli_query($link,$fetch);
echo '<div class="churchdisplay">
<h4>' .$row['churchname'].'</h4>
<p class="detail">' .$row['detail'].'</p>
<p><b>' .$row['city'].'</b>, ' .$row['state'].' ' .$row['country'].'</p>
<p>' .$row['phone'].'</p>
// etc etc
</div>';
}
else{
echo "<p>Please enter a search query</p>";
}
?>
Note that in the form above, I only have two selects for illustration, but ultimately I will have four, as mentioned; and I am only attempting the country selection at this point to keep things simple. Ultimately, I will need the ability to select any (and preferably all) of the four categories.
As you can see, this code does attempt to "grab" the selected value from the form, but it's not working. I've pondered numerous tutorials and examples, but none of them do exactly what I'm after, and as an extreme PHP novice, I'm stumped.
So the question: how do I tweak this so that I can "grab" the form selection and display the relevant results from my table?
Edit: I am using mysqli syntax, and want to just use PHP and MYSQL (no Ajax etc) if possible.
Well, it looks like I've finally found what I needed here:
display result from dropdown menu only when value from it is selected
Or, I should say, I've got it to work with one select option. Still need to see if I can figure out how to get four working together.
Learning PHP and having an issue that I can't figure out. I have read that PHP only has scope for functions, so I'm not sure why my switch statement isn't changing the value of variables.
Goal: to change the mysql SELECT statement based on user selection of drop-down.
Form:
<form action="contacts_show.php" method="POST">
<select name="grade" id="grade">
<option value="all">All Levels</option>
<option value="elementary">Elementary</option>
<option value="middle">Middle</option>
<option value="senior">Senior</option>
<input type="submit" name="browse" id="browse" value="Browse" />
</form>
PHP (edited to shorten code):
$levelSelected = $_POST['grade'];
if ($levelSelected == "all") {
$querySelect = "SELECT * FROM teachers ORDER BY school ASC";
} else {
$querySelect = "SELECT * FROM teachers WHERE school LIKE %$levelSelected% ORDER BY school ASC";
}
$query = $querySelect;
$result = mysqli_query($connection, $query);
confirm_query($result);
the confirm_query function, if needed:
function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed.");
}
}
When "All Levels" from drop-down is selected, code runs as expected. When any other option is selected, my confirm_query function states that the query fails.
I'm not sure why the variable's values are not switching.
To elaborate on my comment:
Change LIKE %elementary% to => LIKE '%elementary%' and do the same for the others.
You need to wrap the pattern match in quotes, and as per the manual:
http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#operator_like
mysql> SELECT 'David!' LIKE '%D%v%';
mysql> SELECT 10 LIKE '1%';
You're also not checking for DB errors.
Add or die(mysqli_error($connection)) to mysqli_query()
If that still doesn't work, then it's also a scope issue.
Pass the connection to your function, do not make it global.
I have searched quite a bit on here about this topic. But I could not find a solution for my problem. I'd appreciate it a lot if you could help me, this is for a school project I am working on.
I have a database with a table ("Main_table") and columns including "sector" and "sub_sector". I want to have two select boxes, first one will load all the records from database in "sector" column and the second one will load all the records from database in "sub_sector" column depending on the selection value of the first select box. (For example: If I select "plastics" on the first select box, then second select box should be updated with sub_sector values where sector value is equal to "plastics").
I have managed to load the options values from database for the first select box but when I click on any selection, it does not load any option to the second select box. You can find the codes below. I did not put "sector_options.php" below, as it seems to work just fine.
index.html shown below:
<script>
$(document).ready(function() {
$('#filter_sector')
.load('/php/sector_options.php'); //This part works fine - uploads options to the first select box
$('#filter_sector').change(function() {
$('#filter_subsector').load('/php/subsector_options.php?filter_sector=' + $("#filter_sector").val()
} //This part does not work - no options on the second select box
);
});
</script>
<body>
<div id="sectors"><p>Sector:</p>
<select id="filter_sector" name="select_sector" multiple="multiple" size="5"> </select>
</div>
<div id="subsectors"><p>Sub Sector:</p>
<select id="filter_subsector" name="select_subsector" multiple="multiple" size="5"> <option value="" data-filter-type="" selected="selected">
-- Make a choice --</option>
</select>
</div>
</body>
</html>
sector_options.php shown below:
<?php
$link = mysqli_connect("*******", "*******","******","********") or die (mysql_error());
$query = "SELECT sector FROM Main_table ";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_assoc($result)) {
$options .= "<option value=\"".$row['sector']."\">".$row['sector']."</option>\n ";
}
echo $options;
?>
subsector_options.php shown below:
<?php
$link = mysqli_connect("********", "*****,"*******", "********") or die (mysql_error());
$Sectors = $_REQUEST['filter_sector'];
$query = "SELECT sub_sector FROM Main_table WHERE sector='$Sectors'";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_assoc($result)) {$options .= "<option value=\"".$row['sub_sector']."\">".$row['sub_sector']."</option>\n ";
}
echo $options;
?>
For completeness, the solutions were:
Check how AJAX operations are doing using a browser network monitor
Load AJAX fetcher scripts in a browser tag - in many cases they will render quite happily there, allowing them to be more easily debugged
AJAX scripts that return HTML for injection should only return that HTML, and not a full HTML document.
Sorry if this has been asked and answered but I have looked and can't see it anywhere. Yes I am a nooby.
I have a DB with 3 tables: flour, filler and others.
What I would like to do is have a dropdown List. So, if user chooses flour from the Drop Down box it will display flour table. If the user chooses filler then filler table be displayed.
Hope this is clear. I hope you can help. Thanks in advance.
<Form id="form1" name="form1" method="get" >
Supplies of
<select name=filler action="flour.php">
<option value="1" selected>flour</option>
<option value="2">filler</option>
<option value="3">others</option>
</select>
<input type="submit" value="Submit" />
</form>
<?php
header("Content-Type: text/html; charset=windows-1251");
#mysql_connect('localhost','root','');
#mysql_select_db('krendel');
#mysql_query('SET NAMES cp1251');
$res = mysql_query("SELECT * FROM `flour` ") or die(mysql_error());
$res2 = mysql_query("SELECT * FROM `filler` ") or die(mysql_error());
$res3 = mysql_query("SELECT * FROM `addit` ") or die(mysql_error());
Add the action to the form, not select element. So you'd have
<form method="get" action="flour.php">
and
In your form processing script (flour.php), you could so something like this:
switch($_GET['filler'])
{
case '1':
$table = 'flour';
break;
case '2':
$table = 'filler';
break;
case '3':
default:
$table = 'addit';
}
$res = mysql_query("SELECT * FROM {$table}");
If all tables have the same structure, consider combining the tables, and adding a type column (varchar containing either flour, filler, or addit for simplicity).
you could then write the query like this (still using the $table variable name to work with the code above.
$res = mysql_query("SELECT * FROM table WHERE type='{$table}'");
Using mysql_query, and concatenating variables into the SQL is not good practice now - have a look at PDO and parameterised queries as you learn more.
Some quick and dirty display code:
<?php
$results = array();
while($row = mysql_fetch_array($res, MYSQL_ASSOC)) { ?>
$results[] = $row;
}
?>
<table>
<?php foreach($results as $result) { ?>
<td><?php echo $result['column_name'] ?></td>
<?php } ?>
</table>
This should get you started - as I said above, it's quick and dirty. You'll be able to improve upon this as you get more knowledge (properly separating out the HTML from PHP, for example - it's really worthwhile reading up on MVC amongst other patterns).
Just don't use this code on a production system!
Hope this helps.
The page that is going to display the table needs to check the $_GET['filler'] and see what the value is. Since you are using $_GET and a drop box, you should have a white list something like: $filler_white_list = array('flower', 'filler', 'other');
Check to see if the value of $_GET['filler'] is in the $filler_white_list array. If the $_GET['filler'] value is valid, then make your query:
$res = mysqli_query('SELECT * FROM '.$_GET['filler'].';') or die(mysqli_error());
Then loop through the result set to print out to the page:
while($row = mysqli_fetch_array($res)){
//get the columns by using $row['column_name']
//decide how you want to format
}
Things to note: I used mysqli instead of mysql, because the mysql is deprecated (no longer supported), The SELECT statement uses an *, but it is better to list out the names of the column since it is faster. It is not a good idea to use the the values of the drop box as the name of you tables in the database. The less information you reveal about your database, the better. Of course, if this is not for a production DB, then it doesn't matter. But, I think it is always best to think about security even when you're just practicing. Also, I put the $_GET['filler'] in the middle of the SELECT statement because the table's names are the same as the drop box.
I really would like some help on this as I'm pulling hair out!!!
I have two fields, one being an input box & the other being a drop down list which search the database and display the results, however I cannot seem to figure it out...here is what I have so far...
This is the actual search form:
<form id="myform" name="myform" action="<?php echo $_SERVER['PHP_SELF']?>" method="get"><br />
<div class="T1"><br /><p></div> <input name="term" type="text" value="<? php echo $_GET['searched']; ?>" size="10" maxlength="4" placeholder="e.g. BS1"/>
<select>
<option value="">I feel like...</option>
<option value="">Anything</option>
<option value="Indian">Indian</option>
<option value="Chinese">Chinese</option>
<option value="Thai">Thai</option>
</select>
<input type="submit" name="submit" value="Go"/>
</form>
And this is the PHP code:
<?php
if (isset($_GET['submit'])){
mysql_connect ("host", "user","password") or die (mysql_error());
mysql_select_db ("database");
$term = $_GET['term'];
$term = $_GET['option value'];
}
else
$sql = mysql_query("select pagetitle from Restaurant where extra like '%$term%' and showing like '1'");
$sql = mysql_query("select cuisine from Restaurant where cuisine like 'option value' and showing like '1'");
echo Restaurants in $term and Cuisine $option value:";
}
while ($row = #mysql_fetch_array($sql)){
echo ''.$row['pagetitle'];
echo '<br/>';
}
}
?>
The database has a table called Restaurant with two coloumns, one called 'Extra' which contains the postcode & the other called 'Cuisine' which containts the cuisine.
I would like it to return a list of restaurants that match both 'Extra' and 'Cuisine'
Any help will be greatly appretiated.
Echoing $_SERVER['PHP_SELF'] or $_GET['searched'] anywhere in your script (even in the form action) will open your site up to XSS attacks. Do not do this unless you sanitize them first.
For all new projects, it is recommended to use prepared statements for mysql queries. You can do this with either mysqli or PDO. Your code is just asking for SQL injection by the looks of what you are trying to do.
You are missing a bracket in your code and you have some extra ones at the end. Also after echo you're missing a quotation mark. I'm not sure what's going on there. Try to get those fixed.
What is with the # before mysql_fetch_array() ? There are really very few cases where # should ever be used in PHP. It is usually an indicator that there is some sort of error somewhere in your code that should be fixed instead of suppressed.
Your needs a name attribute if you want to be able to use it in PHP.
In your SQL query, you should not be using LIKE when you should be using equals. Also, you should not quote integers.
Why are you echoing an empty string like echo ''.$somevar; ? Just echo the variable.
I'm not sure what "showing" is for but I assume is a record that can be displayed. The first thing to do is update your query:
$sql = mysql_query("select pagetitle, cuisine from Restaurant where (extra like '%$term%') and (showing like '1') and (cuisine like 'option value')");
You also need to check if the user did not enter an option or selected 'anything' in which case the query needs to be changed a little:
$sql = mysql_query("select pagetitle, cuisine from Restaurant where (extra like '%$term%') and (showing like '1') and (cuisine like 'option value' or 'option value' = '')");