I am trying to find a way in PHP to combine data from several drop down boxes into one SQL statement. I can get this to partly work. Here is the SQL query:
$sql = "
SELECT *
FROM books
WHERE
author = '$bird'
AND genre = '$cat'
AND year= '$mouse'
AND publisher = '$goat'
";
$bird, $cat etc are the variables that hold the selection from each drop down box.
I am getting mixed results. All four will work together fine and all will work individually.
So If I select from authors, genre, year and publisher, then press select it works and if I select these individually they work as well.
But if try and just select two items, let's say author and year, it does not work and can produce a variety of incorrect data. Here is the complete code. Any help appreciated:
<html>
<head>
<title>My Page</title>
</head>
<body>
<br>
<form name="myform" action="authors3.php" method="POST">
<select name="author" size="2">
<option value="ken davies">ken davies</option>
<option value= "arthur smith">arthur smith</option>
<option value="gill rafferty">gill rafferty</option><br />
<option value="molly brown">molly brown</option><br />
<option value="gilbert riley">gilbert riley</option><br />
<input type = "submit" name = "submit" value = "go">
<select name="genre" size="4">
<option value="adventure">adventure</option>
<option value="biography">biography</option>
<option value="crime">crime</option><br />
<option value="romance">romance</option>
<option value="thriller">thriller</option>
<input type = "submit" name = "submit" value = "go">
<select name="year" size="4">
<option value="2002">2002</option>
<option value="2003">2003</option>
<option value="2004">2004</option>
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<input type = "submit" name = "submit" value = "go">
<select name="publisher" size="4">
<option value="blue parrot">blue parrot</option>
<option value="yonkers">yonkers</option>
<option value="zoot">zoot</option>
<input type = "submit" name = "submit" value = "go">
<?php
$bird = (!empty($_POST['author'])) ? $_POST['author'] : null;
$cat = (!empty($_POST['genre'])) ? $_POST['genre'] : null;
$mouse = (!empty($_POST['year'])) ? $_POST['year'] : null;
$goat = (!empty($_POST['publisher'])) ? $_POST['publisher'] : null;
$con = mysql_connect("localhost","root","");
If (!$con) {
die("Can not Connect with database" . mysql_error());
}
mysql_select_db("authors",$con);
if (isset($bird) && isset($cat) && isset($mouse) && isset($goat)){
$sql = "SELECT * FROM books WHERE author = '$bird'
AND genre = '$cat' AND year = '$mouse' AND
publisher = '$goat' ";
}
else if (isset($bird)) {
$sql = "SELECT * FROM books WHERE author = '$bird' ";
}
else if (isset($cat)) {
$sql = "SELECT * FROM books WHERE genre = '$cat' ";
}
else if (isset($mouse)) {
$sql = "SELECT * FROM books WHERE year = '$mouse' ";
}
else if (isset($goat)) {
$sql = "SELECT * FROM books WHERE publisher = '$goat' ";
}
$myData = mysql_query($sql,$con);
echo"<table border=1>
<tr>
<th>id</th>
<th>author</th>
<th>title</th>
<th>publisher</th>
<th>year</th>
<th>genre</th>
<th>sold</th>
</tr>";
while($record = mysql_fetch_array($myData)){
echo "<tr>";
echo "<td>" . $record['id'] . "</td>";
echo "<td>" . $record['author'] . "</td>";
echo "<td>" . $record['title'] . "</td>";
echo "<td>" . $record['publisher'] . "</td>";
echo "<td>" . $record['year'] . "</td>";
echo "<td>" . $record['genre'] . "</td>";
echo "<td>" . $record['sold'] . "</td>";
echo "<tr />";
}
echo "</table>";
mysql_close($con);
?>
note: all four are working<br />
all work individually<br />
two or three dont work together
</form>
</body>
</html>
Apart from the fact that you're using a deprecated way connecting to MySQL (read up on SQL injection and PDO), you're not covering all the use cases in your code.
A better way might be to write a base query ($q = 'SELECT * FROM books WHERE), and extend that query with the appropriate extra WHERE clauses, based on checking if the parameter is empty or not (if (!empty($goat)) // append new clause to the WHERE portion).
You're query is half fine. Your declarations are the cause of your problem! The reason is you're essentially doing this:
genre ='adventure' and year = null.
What you want to do is edit your query accordingly. So you'll want to do
if (!is_null($year)) {
$sql.= "AND Year = $year";
}
Problem is the above method allows injection!! Which if you're fessed about is a BIG PROBLEM!!!!
So I would recommend using bind_params BUT having said that calling cal_user_func_array on bind_params is a bit tricky so I'd recommend using PDO where you can edit your query and manage your parameters safely and effectively
Related
I'm not sure how to describe it, so here's a video where I explain my problem.
I tried rearranging some of the code, as I do believe nothing is faulty, attempting to make sure that the table refreshes with the new data inside it, however every time I tried to place my code in a different order (executing the queries in different orders), it either functions differently than how I want it to function or it doesn't function at all.
Both queries do function separately, I'm just unsure why they're not working together.
Searchbar has the value seen inputted in the homepage on both my Search page and this page in question. However it was left blank for this page, which gave me the result of having the full table display which is what I wanted to happen. I'm just not sure how I can edit my code so, when submitted, it will display the newly added data.
My PHP:
<?php
$find = $_POST['searchbar'];
$host = "localhost";
$username = "FFF";
$pword = "L3FhqJNey8Op2qJY";
$database = "Project";
include 'includes/db.inc.php';
$Name2 = $_POST['Name'];
$YearOfRelease2 = $_POST['YearOfRelease'];
$Studio2 = $_POST['Studio'];
$Age2 = $_POST['Age'];
$Score2 = $_POST['Score'];
?>
My HTML:
<html>
<head>
<title>Add a Film - Films! Films! FILMS!</title>
</head>
<body>
<h1>Films! Films! FILMS!</h1>
<h2>Add a Film</h2>
<p>If you wish to add a film to our database, feel free to add data relating to the film in the respective boxes below. You should then refresh the page.</p>
<p>Add Film:</p>
<form method="POST" action="AddFilm.php">
<p>Name of Film: <input type="text" name="Name"></p>
<p>Year of Release: <input type="text" name="YearOfRelease"></p>
<p>Name of Studio: <input type="text" name="Studio"></p>
<p>Age Rating: <select name="Age" size="1">
<optgroup label="Select Age Rating">
<option value="U">U</option>
<option value="PG">PG</option>
<option value="12">12</option>
<option value="15">15</option>
<option value="18">18</option>
</optgroup>
</select></p>
<p>Review Score: <input type="text" name="Score"></p>
<p><input type="submit" name="submit" value="Submit and Refresh"></p>
</form>
<?php
echo "<h2>$output</h2>";
$query_string = "SELECT * FROM movies WHERE Name LIKE '%$find%' OR YearOfRelease LIKE '%$find%' OR Studio LIKE '%$find%' OR Age LIKE '%$find%' OR Score LIKE '%$find%'";
$query_string2 = "INSERT INTO movies (Name, YearOfRelease, Studio, Age, Score) VALUES ('$Name2', '$YearOfRelease2', '$Studio2', '$Age2', '$Score2');";
if ($result = $mysqli->query($query_string2)) {
$output2 = $Name2 ." has been added to the database.";
echo "<p>$output2</p>";
} else {
echo ("Error performing query: " . $mysqli->error() );
}
$result->close();
if ($result = $mysqli->query($query_string)) {
echo "<table border='1'>";
echo "<tr><th>FilmID</th><th>Name</th><th>YearOfRelease</th><th>Studio</th><th>Age</th><th>Score</th></tr>";
while ($row = $result->fetch_object())
{
$FilmID = $row->FilmID;
$Name = $row->Name;
$YearOfRelease = $row->YearOfRelease;
$Studio = $row->Studio;
$Age = $row->Age;
$Score = $row->Score;
$output ="<tr><td> $FilmID";
$output = $output . "<td> $Name";
$output = $output . "<td> $YearOfRelease";
$output = $output . "<td> $Studio";
$output = $output . "<td> $Age";
$output = $output . "<td> $Score </tr>";
echo "<p>$output</p>";
}
echo "</table>";
echo "<hr>";
echo '<p>Back to Home Page</p>';
$result->close();
} else {
echo ("Error performing query: " . $mysqli->error() );
}
$mysqli->close();
?>
</body>
</html>
I am currently doing a project in school which involves using a form to query a database. This form has multiple drop down menus and I am unsure on how to query the database if the user does not fill out all of the drop down menus. For example if the user only wants to search for a certain job type and does not specify the industry.
INDEX.HTML
<html>
<head>
</head>
<body>
<form action="test.php" method="post">
<select name="varjobtype">
<option value="nullg" disabled selected hidden>Job Type</option>
<option value="Part Time">Part Time</option>
<option value="Full Time">Full Time</option>
<option value="Contract">Contract</option>
<option value="Temporary">Temporary</option>
</select>
<select name="varindustry">
<option value="null" disabled selected hidden>Industry</option>
<option value="Accommodation and Food Services">Accommodation and Food Services</option>
<option value="Retail">Retail</option>
</select>
</form>
</body>
</html>
TEST.PHP
<html>
<head>
</head>
<body>
<?php
$jobtype = $_POST['varjobtype'];
$industry = $_POST['varindustry'];
$sql = "SELECT `Job ID`, Name, Employer FROM JobListings WHERE `Job Type` = '$jobtype' AND `Industry` = '$industry' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<div id="<? echo $row['Job ID']; ?>" class="box">
<?
echo "Job ID: " . $row["Job ID"]. "<br>";
echo "Name: " . $row["Name"]. "<br>";
echo "Employer: " . $row["Employer"]. "<br>";
echo "</div>";
}
?>
<?
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
As of now the php outputs no results.How would you make it so even if the user selects one of the drop down menus then the SQL statement will still display the jobs. Is it possible to make it so that it displays all of the jobs if the user does not interact with any of the drop down menus?
try this:
$jobtype = isset($_POST['varjobtype']) ? $_POST['varjobtype'] : '';
$industry = isset($_POST['varindustry']) ? $_POST['varindustry'] :'';
$sql = "SELECT `Job ID`, Name, Employer FROM JobListings";
$where = array();
if ($jobtype) $where[] = "`Job Type` = '".$jobtype."'";
if ($industry ) $where[] = "`Industry` = '".$industry."'";
if (!empty($where)) {
$sql .= " where " . implode (" and ",$where);
}
$result = $conn->query($sql);
...
I have three list boxes on my HTML form,AUTHOR,GENRE and YEAR.These are linked to a sql database called Authors and a table called books.The idea is to click on one or all of the List boxes,the choice is then placed in variables then into a customised sql statement which extracts the data from the mysql DB and places the result in a table.The result only partly works.If I click one item from each box,then it reponds fine For Example EG Ken Davies(choice in author list) Adventure(choice in genre list) and 2007(choice in year list) Then this works fine.Also if I just click on an authors name,this works fine,or if I just click on genre,this works fine.However when I click on any of the years in the year list box,I dont get anything,despite the years working if I combine them into all three(authors,genre and year).Has anyone any suggestions please Many thanks.
<html>
<head>
<title>My Page</title>
</head>
<body>
<br>
<form name="myform" action="dropdown2.php" method="POST">
<select name="author" size="4">
<option value="ken davies">ken davies</option>
<option value= "arthur smith">arthur smith</option>
<option value="gill rafferty">gill rafferty</option><br />
<option value="molly brown">molly brown</option><br />
<option value="gilbert riley">gilbert riley</option><br />
<input type = "submit" name = "submit" value = "go">
<select name="genre" size="4">
<option value="adventure">adventure</option>
<option value="biography">biography</option>
<option value="crime">crime</option><br />
<option value="romance">romance</option>
<option value="2007">thriller</option>
<input type = "submit" name = "submit" value = "go">
<select name="year" size="4">
<option value="2002">2002</option>
<option value="2003">2003</option>
<option value="2004">2004</option>
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<input type = "submit" name = "submit" value = "go">
<?php
$bird = ( ! empty($_POST['author'])) ? $_POST['author'] : null;
$cat = ( ! empty($_POST['genre'])) ? $_POST['genre'] : null;
$mouse = ( ! empty($_POST['year'])) ? $_POST['year'] : null;
$con = mysql_connect("localhost","root","");
If (!$con){
die("Can not Connect with database" . mysql_error());
}
Mysql_select_db("authors",$con);
if(isset($_POST['author'])&&isset($_POST['genre'])&&isset($_POST['year']))
{
$sql = "SELECT * FROM books WHERE author = '$bird' AND genre = '$cat' AND year = '$mouse' ";
unset($_POST['cat']);
unset($_POST['bird']);
unset($_POST['mouse']);
}
elseif(!isset($_POST['author']))
{
$sql = "SELECT * FROM books WHERE genre = '$cat' ";
unset($_POST['genre']);
}
elseif(!isset($_POST['genre']))
{
$sql = "SELECT * FROM books WHERE author = '$bird'";
unset($_POST['author']);
}
elseif(!isset($_POST['year']))
{
$sql = "SELECT * FROM books WHERE year = '$mouse'";
unset($_POST['author']);
unset($_POST['genre']);
unset($_POST['year']);
$myData = mysql_query($sql,$con);
echo"<table border=1>
<tr>
<th>id</th>
<th>author</th>
<th>title</th>
<th>publisher</th>
<th>year</th>
<th>genre</th>
<th>sold</th>
</tr>";
while($record = mysql_fetch_array($myData)){
echo "<tr>";
echo "<td>" . $record['id'] . "</td>";
echo "<td>" . $record['author'] . "</td>";
echo "<td>" . $record['title'] . "</td>";
echo "<td>" . $record['publisher'] . "</td>";
echo "<td>" . $record['year'] . "</td>";
echo "<td>" . $record['genre'] . "</td>";
echo "<td>" . $record['sold'] . "</td>";
echo "<tr />";
}
echo "</table>";
mysql_close($con);
?>
</form>
</body>
</html>
add mysql_error() for each query you have used and apart review your Html code it seems to be not pretty.
considering your database table name is books and its fields are title, author, genre, year and etc.
<?php
//database connection code here
?>
<form action="aaa.php" method="POST">
<table>
<tr>
<td>Author</td>
<td>
<select name="author">
<option value="">Select</option>
<?php
//gets all the name of the author in the database
$result1 = mysql_query("SELECT distinct author from books ORDER by author");
while($row1 = mysql_fetch_assoc($result2))
{
echo "<option>".$row21['author']."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>Genre</td>
<td>
<select name="genre">
<option value="adventure">adventure</option>
<option value="biography">biography</option>
<option value="crime">crime</option><br />
<option value="romance">romance</option>
<option value="2007">thriller</option>
</select>
</td>
</tr>
<tr>
<td>Year</td>
<td>
<select name="year">
<option value="2002">2002</option>
<option value="2003">2003</option>
<option value="2004">2004</option>
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
</select>
</td>
</tr>
<tr>
<td colspan="2"><input type="text" name="submit" value="submit"/></td>
</tr>
</table>
</form>
<?
if(isset($_POST['submit']))
{
echo "<table>";
$result = mysql_query("SELECT * from books where author='".$_POST['author']."' and genre='".$_POST['genre']."' and year='".$_POST['year']."' ");
while($row = mysql_fetch_assoc($result))
{
echo "<tr>":
echo "<td>".$row['title']."</td>":
echo "<td>".$row['author']."</td>":
echo "<td>".$row['genre']."</td>":
echo "<td>".$row['year']."</td>":
echo "</tr>":
}
echo "</table>";
}
?>
I am having issues with creating radio buttons for each query result. For each line returned I want to have an extra column that consists of 2 radio buttons. the user should only be able to select 1 of these 2 buttons. Right now I have the column of radio buttons but the user can only select 1 of each radio button, not 1 for each result of the query. I hope that makes sense.
Should I be even using radio buttons? Or should I use check boxes?
<!DOCTYPE html>
<html>
<head>
<title>games</title>
</head>
<body>
<form method="POST" action="<?= $_SERVER['PHP_SELF'] ?>">
<select name="weekNo">
<option value="1">week 1</option>
<option value="2">week 2</option>
<option value="3">week 3</option>
<option value="4">week 4</option>
<option value="5">week 5</option>
<option value="6">week 6</option>
<option value="7">week 7</option>
<option value="8">week 8</option>
<option value="9">week 9</option>
<option value="10">week 10</option>
<option value="11">week 11</option>
<option value="12">week 12</option>
<option value="13">week 13</option>
<option value="14">week 14</option>
</select>
<input type="submit" name="submit" value="Get Games" />
</form>
<br>
<hr>
<?php
$conn =
or die('Could not connect: ' . pg_last_error());
if(isset($_POST['submit'])) //submit button pressed
{
$query=NULL; //prevent compile error
$weekNum = $_POST['weekNo'];
$query = "SELECT a.game_no AS game_number, a.home AS home_team,
homeTeam.wins AS home_wins, homeTeam.losses AS home_losses,
a.away AS away_team, awayTeam.wins AS away_wins,
awayTeam.losses AS away_losses, a.spread AS spread
FROM weekly_stats AS a
INNER JOIN team AS homeTeam ON a.home = homeTeam.name
INNER JOIN team AS awayTeam ON a.away = awayTeam.name
WHERE a.week_no = $weekNum";
$result = pg_query($query) or die ('Query failed: ' .pg_last_error());
$query2 = "SELECT week_no, game_no FROM weekly_stats";
$result2 = pg_query($query2) or die ('Query failed: ' . pg_last_error());
// Printing results in HTML
echo "<br>There are " . pg_num_rows($result) . " records found.\n<p></p>\n";
echo "<table border=1>\n\t<tr>\n";
for($i=0; $i<pg_num_fields($result); $i++)
{
echo "\t\t<th>" . pg_field_name($result, $i) . "</th>\n";
}
echo "\t\t<th>Picks</th>\n";
echo "\t</tr>\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC))
{
echo "\t<tr>\n";
foreach ($line as $col_value)
{
echo "\t\t<td>$col_value</td>\n";
}
echo "<td><input type=\"radio\" name=\"picks\" value=\"home\">Home
<input type=\"radio\" name=\"picks\" value=\"away\">Away</td>";
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
pg_free_result($result);
}
// Closing connection
pg_close($conn);
?>
</body>
</html>
The input name is the same on all of your radio buttons so the web browser is assuming they all answer the same question (Home or Away for ALL records) rather than a set of questions (Home or Away for EACH record). You need to differentiate the names for each pair of radio buttons for each row.
$row=0;
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC))
{
echo "\t<tr>\n";
foreach ($line as $col_value)
{
echo "\t\t<td>$col_value</td>\n";
}
echo "<td>"
."<label>Home <input type='radio' name='picks[$row]' value='home'></label>"
."<label>Away <input type='radio' name='picks[$row]' value='away'></label>"
."</td>";
echo "\t</tr>\n";
$row++;
}
On the server side it will interpret the submission as an array. The $row variable above could be a unique index or ID for each row rather than simply a counter as I demonstrated.
Radio buttons with the same names cannot be selected simultaneously. Radio buttons for each query should have unique names but names for two buttons of the same query should have the same name.
The code should be modified to:-
echo "<td><input type=\"radio\" name=\"picks[$row_number]\" value=\"home\">Home
<input type=\"radio\" name=\"picks[$row_number]\" value=\"away\">Away</td>";
I'm trying to add results into a html dropdown.
The php works if I take it outside the html form: it shows the results, but I need it inside the form
<form><form method="post" action="selldo.php">
<label><br /><br /><br /><br />What slot do you want to Sell?</label>
<select name="pokeSLOT" id="pokeSLOT" style="width:150px;padding-left:5px;">
<option value=""></option>
<?php
$result = mysql_query("SELECT * FROM user_pokemon
WHERE belongsto='$_SESSION[username]'");
while($row = mysql_fetch_array($result))
{
echo $row['id'] . " " . $row['pokemon'];
echo "<br />";
}
?>
</select><br/><br/>
<label>Price You Would Like For The Pokemon?</label>
<input type="int" name="cost" id="cost" maxlength="30"/><br/><br/>
<button name="submit" type="submit" id="Submit_But">Sell</button>
<p> </p><p> </p>
</form>
When I look in the dropdown menu there is nothing but if it makes the SQL out of the form it posts the results to the page so it works fine I just need it in side the drop down html form
p.s i have the connect ontop of the page
You will need to echo out HTML option elements:
while($row = mysql_fetch_array($result)) {
echo "<option>" . $row['id'] . " " . $row['pokemon'] . "</option>";
}
You will probably want to give the option elements a value so the selected option is passed along properly when the form is submitted.
Did you look at the source this code generates?
You will find that your options are all there but just somewhere in the void, not wrapped by any html tags. You'll see something like:
<form>
<select>
<option></option>
your first option
your second option
your third option
your n'th option
</select>
</form>
But what you really need, for the markup to be correct, is this:
<option>your first option</option>
<option>your second options</option>
And so forth... that should be enough for you to get it right! If not...
echo '<option value="' . $row['id'] . '">' . $row['pokemon'] . '</option>';
You have an SQL-injection hole and a possible XSS security hole:
Correct this by changing the php code to:
<?php
$username = mysql_real_escape_string($_SESSION['username']);
$result = mysql_query("SELECT * FROM user_pokemon
WHERE belongsto = '$username' ");
while($row = mysql_fetch_array($result))
{
$id = htmlentities($row['id']);
$pokemon = htmlentities($row['pokemon']);
echo '<option value = "$id"> $pokemon </option>';
}
?>
See: What are the best practices for avoiding xss attacks in a PHP site
And How does the SQL injection from the "Bobby Tables" XKCD comic work?
You're not creating a select! you need the <option></option> tags for that, not just echo out your results...
<select name="pokeSLOT" id="pokeSLOT" style="width:150px;padding-left:5px;">
<option value=""></option>
<?php
$username = mysql_real_escape_string($_SESSION['username']);
$result = mysql_query("SELECT * FROM user_pokemon WHERE belongsto='$username'");
while($row = mysql_fetch_array($result)) : ?>
<option value="<?php echo htmlentities($row['id']);?>"><?php echo htmlentities($row['pokemon']);?></option>
<?php endwhile;?>
</select>
This should do the trick:
<select name="pokeSLOT" id="pokeSLOT" style="width:150px;padding-left:5px;">
<?php
$result = mysql_query("SELECT * FROM user_pokemon WHERE belongsto = '$_SESSION[username]'");
while($row = mysql_fetch_array($result)) {
echo "<option value=\"\">" . $row['id'] . " " . $row['pokemon'] . "</option>
?>
</select>