I have two List Boxes and I click on both of them to create the SELECT query.I placed the $POST variable into another variable and then placed these into the select query.This seems to work fine,but the problem arises when I only want to select from one of the boxes for example just all of Ken Davis's books or all books from the adventure genre.It seems I have to chhose both boxes before I get a result.Can anyone suggest a way round this
<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">
<?php
$_POST['author'];
$bird = $_POST['author'];
$_POST['genre'];
$cat = $_POST['genre'];
$con = mysql_connect("localhost","root","");
If (!$con){
die("Can not Connect with database" . mysql_error());
}
Mysql_select_db("authors",$con);
$sql = "SELECT * FROM books WHERE author = '$bird' AND genre = '$cat' ";
$myData = mysql_query($sql,$con);
echo"<table border=1>
<tr>id</th>
<tr>author</th>
<tr>title</th>
<tr>publisher</th>
<tr>year</th>
<tr>genre</th>
<tr>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>
If you want to filter by only author or only genre, change the logic leading up to your SQL.
if (isset($bird) && isset($cat))
$sql = "SELECT * FROM books WHERE author = '$bird' AND genre = '$cat' ";
elseif (isset($bird))
$sql = "SELECT * FROM books WHERE author = '$bird' ";
elseif (isset($cat))
$sql = "SELECT * FROM books WHERE genre = '$cat' ";
Also I'm legally required to let you know that putting variables in SQL will lead to SQL injection. You should prepare and execute. I'll write some example code below (one sec).
First you need to get the values from the form like you are doing, but you need to add in some code that allows them to be non-mandatory:
$bird = ( ! empty($_POST['author'])) ? $_POST['author'] : null;
$cat = ( ! empty($_POST['genre'])) ? $_POST['genre'] : null;
This will either give you the value that was submitted with the form, or null which can be used later to decide how to query your db. I would also suggest you check the values given match what you expect. So either compare the data to known authors, or known genres and weed out tampered data, e.g:
$genres = array('adventure', 'biography', 'crime', 'romance', 'thriller');
if ( ! in_array($cat, $genres)) {
// invalid data supplied (you could show an error)
unset($cat); // destroys the invalid variable
}
Then when you come to your db query you can do something like this:
if (isset($bird) && isset($cat)) {
// SELECT by both
}
else if (isset($bird)) {
// SELECT by author
}
else if (isset($cat)) {
// SELECT by cat
}
else {
// SELECT all
}
There are many ways to shorten the above, but this is a good starting point for you.
In such a case, you will have to write separate queries in your PHP code for separate cases.
//When both the list boxes are selected
if(isset($_POST['author'])&&isset($_POST['genre']))
{
$sql = "SELECT * FROM books WHERE author = '$bird' AND genre = '$cat' ";
unset($_POST['genre']);
unset($_POST['author']);
}
//When searching genre-wise (author variable not set)
elseif(!isset($_POST['author']))
{
$sql = "SELECT * FROM books WHERE genre = '$cat' ";
unset($_POST['genre']);
}
//When searching authorwise (genre variable not set)
elseif(!isset($_POST['genre']))
{
$sql = "SELECT * FROM books WHERE author = '$bird'";
unset($_POST['author']);
}
Related
I have a table that displays tuples of books and data about them. There is also a radio button for each row. The idea is that the user selects the button to indicate that they want to order that book.
function displayAllBooks(){
$dbhost = 'localhost:3306';
$dbuser = 'root';
$conn = mysqli_connect($dbhost, $dbuser);
//sql statement to use the database
$sql = 'use BookStore';
mysqli_query($conn, $sql);
$sql = 'SELECT * FROM Author, Books, Written_By, Book_Categories, Assigned_To '
. 'WHERE Author.Author_ID = Written_By.Author_ID'
. ' AND Books.ISBN = Written_By.ISBN'
. ' AND Books.ISBN = Assigned_To.ISBN'
. ' AND Assigned_To.Cat_Code = Book_Categories.Cat_Code'
. ' ORDER BY ALname ASC';
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
echo '<form action = "customerDashboard.php" method = "post">';
echo 'First name:
<input type= "text" name ="CFname"<br>
Last name:
<input type= "text" name ="CLname"<br>';
echo '<p style="text-align:center"><b> All Books </b></p>';
echo '<table class="center">'
. '<tr>'
. '<th>Order</th>'
. '<th>Title</th>'
. '<th>Price</th>'
. '<th>Author</th>'
. '<th>Publication Date</th>'
. '<th>User Review</th>'
. '<th>Category</th>'
. '</tr>';
if (mysqli_num_rows($result) > 0) {
$bookCt = 0;
//mysqli_fetch_assoc associates an array with the results
while ($row) {
$retTitle = $row["Title"];
$retPrice = $row["Price"];
$retALname = $row["ALname"];
$retPubDate = $row["Publication_Date"];
$retReview = $row["User_Reviews"];
$retCat = $row["Cat_Desc"];
//fetch ISBN for each book, for use with the radio buttons to
//place orders
$sql = 'SELECT ISBN from Books WHERE Title="'.$retTitle .'"';
$resultISBN = mysqli_query($conn, $sql);
$rowISBN = mysqli_fetch_assoc($resultISBN);
$currISBN = $rowISBN["ISBN"];
echo"<tr>";
echo '<td><input type="radio" name="'.$currISBN.'"></td>';
echo "<td> $retTitle </td>";
echo "<td> $retPrice </td>";
echo "<td> $retALname </td>";
echo "<td> $retPubDate </td>";
echo "<td> $retReview </td>";
echo "<td> $retCat </td>";
echo "</tr>";
$row = mysqli_fetch_assoc($result);
}
}
else {
echo "0 results";
}
echo "</table>";
echo '<input type="submit" name="placeOrder" value="Order Selected Book">';
echo '</form>';
I've been trying something like onselect="load the button name into a session variable" but I have been unable to implement it.
Each radio button has a name value that is the ISBN (primary key) for the current book thats being put into the table. I want to be able to select a radio button, have that ISBN be stored in a session or global variable, and use that specific ISBN for another method, placeOrder(). After a radio button is checked, the user inputs their first and last name and presses "order selected book", which reloads the page and triggers the placeOrder() function via:
else if(isset($_POST["placeOrder"])){
//for placing orders on a single book
placeOrder();
}
which is present at the beginning of the PHP portion, alongside other function calls.
I'm pretty new to PHP and HTML, so forgive me if the answer is obvious. I could do this if the radio button name was explicit, but since it is changing with each row, I cannot figure it out.
Main idea: How can i capture info that a selected radio button corresponds with so I can use said info in another function?
The answer doesn't have to involve session or global variables, any help is appreciated.
You could an array to represent the radio buttons with the isbn as the index
echo '<td><input type="radio" name="books['.$currISBN.']"></td>';
and then loop through it on the server side
foreach ($_POST['books'] as $isbn => $on){
// do something with $isbn
}
I am facing difficulties while selecting values from drop down list based on the selected value from another drop down list that too retrieve from sql database
My PHP code is embedded with html, here is the code i am trying to do with select:
Country Name: <select name="status" style="width: 150px;">
<option value="select_country" selected>select</option>
<?php
$c_id="";
include 'dbconfig.php';
$sql = "select * from Country";
$result = sqlsrv_query($conn,$sql);
while($row = sqlsrv_fetch_array($result))
{
echo("<option value = '" . $row['Country'] . "'>" . $row['Country'] . " </option>");
$c_id=$row['CountryId'];
}
?>
</select> Create New Country
<br /><br />
State Name: <select name="status" style="width: 150px;" >
<option value="select_State" selected>select</option>
<?php
$s_id="";
$sql = "select * from State where CountryId = $c_id";
$result = sqlsrv_query($conn,$sql);
while($row = sqlsrv_fetch_array($result))
{
echo("<option value = '" . $row['State'] . "'>" . $row['State'] . " </option>");
$c_id=$row['State'];
}
?>
</select> Create New State
Please suggest me how to overcome this and thanks in advance..
You should use AJAX if you want the second select shown options based on the first option list picked value.
You have to use JAAX upon selection of first drop down list and replace the options of second drop down list.
I want to send some information from one php file to another.
I've read about the use of $_SESSION and $_POST, but they're giving me some problems.
My code looks something like this:
<form action="booking.php" method="post">
<select name="bookingflight">
<?php
$query = "SELECT Flight, Name
FROM Airport";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo "<option value=\"". $row['Flight'] . ',' . $row['name'] . "\">" . $row['Flight'] . ' ' . $row['name'] . "</option>";
}
?>
</select></p>
<input type="submit" value="book flight"/>
</form>
This gives me a dropbox list of all the flights, along with the name of the flights.
If I select an element it's stored in $_POST["bookingflight"] which I can access in booking.php, which is fine.
However, it's given as a string, while I should be able to handle flight and name separately.
Ideally, I'd have two variables, one for flight and one for name, which I can access in booking.php.
How should I do this? With $_SESSION I don't even know how to assign a selected item from the list to a variable.
Alternate Solution: If Flight is unique data
while($row = mysql_fetch_array($result)) {
$flight=$row['Flight'];
$name=$row['Name'];
echo "<option value='$flight'>$flight $name</option>";
}
PHP : booking.php
<?php
$flight=$_POST['bookingflight'];
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT Flight,Name FROM Airport WHERE Flight='$flight'");
$row = mysqli_fetch_array($result);
$name= $row['Name'] ; // Here you get Name of selected Flight
mysqli_close($con);
?>
Or
If your Airport table contains any unique data/id , you can pass that data as option value too
You started this the wrong way...
Give your Airport table a unique primary key (named id, INT, auto-increment) and pass that as a value in generated options:
echo "<option value=\"". $row['id'] ."\">" . $row['Flight'] . ' ' . $row['name'] . "</option>";
Now when you POST your form you get that ID value in booking.php.
Because every flight has a unique ID you can just issue another query and you get your result as an array there:
$query = "SELECT Flight, Name FROM Airport WHERE id = $id";
Put this in your booking.php...
if($_POST)
{
$values = $_POST['bookingflight'];
$val= explode(',',$values);
$_SESSION['flightnumber'] = $val[0];
$_SESSION['flightname'] = $val[1];
}
I have a database that I want to get data out onto a website. It contains states listed by name and id. Counties listed by id, namne , and state that contains thems ID and then clubs that exist , with a reference to the county id's that they exist in and columns for their actual data.
What I've got :
A drop down menu that populates itself with state id and name.
What I'd like to accomplish:
On selection of state , let's say ny , take it's id and use this in gathering another mysql array for the county drop down. I'd like it to dynamically occur on selection of state , maybe even giving a count of results next to the drop down.
$resstate = mysql_query("SELECT * FROM state ORDER by longstate;") or die("Note: " . mysql_error());
State:
<select name="State" size=1>
<?
while( $rs = mysql_fetch_array( $resstate ) ) {
echo "<option value=" .$rs['id'] . ">" . $rs['longstate'] . "</option>";
}
echo "</select>";
?>
I know I could use a JavaScript onChange="this.form.submit()" on the first drop down, but it's my understanding that I'd then be making a new page at that point and don't know if I could keep the functionality of the state drop down, say if you accidentally chose new Hampshire when you wanted New York.
here's an example of the current array filling the drop down :
http://snowmobileamerica.com/countytest.php
----EDIT---
Using Dagons Advice , I looked into Ajax.
I made a php file that's supposed to query the database based on a reference to getcounty.php?q=
The file is created as follows :
<?php
$q=$_GET["q"];
$cn=mysql_connect("localhost","user","password") or die("Note: " . mysql_error());
mysql_select_db("snowusa_clubs", $cn);
$sql="SELECT * FROM county WHERE state_id = '".$q."' ORDER by name";
$result = mysql_query($sql);
echo "<select name="County" size=1>";
while($rc = mysql_fetch_array($result))
{
echo "<option value=" .$rc['id'] . ">" . $rc['name'] . "</option>";
}
echo "</select>";
mysql_close($cn);
?>
If i try to run it manually http://www.snowmobileamerica.com/getcounty.php?q=33 I get a 500 internal server error...
Any ideas where I went wrong?
try adding an id to the element, then make an ajax call to a handler with jquery:
$("#State").change(function() {
$.post("path/to/request handler/" , { "State" : $(this).val() },
function(data){
if (data == "OK"){
//add some elements here
} else {
//handle an error here
}
});
});
not able to comment yet.
but for the second question try:
<?php
$q=$_GET["q"];
$cn=mysql_connect("localhost","user","password") or die("Note: " . mysql_error());
echo "Conn ok<br>";
mysql_select_db("snowusa_clubs", $cn);
echo " Database opened<br>";
$sql="SELECT * FROM county WHERE state_id = '$q' ORDER by name";
$result = mysql_query($sql);
echo " Database queried <br>";
echo "<select name='County' size=1>";
while($rc = mysql_fetch_array($result))
{
echo "<option value='" .$rc['id'] . "'>" . $rc['name'] . "</option>";//added single quotes in the value
}
echo "</select> ";
mysql_close($cn);
?>
I have a form with a select box where the user can select pre-existing fields from a database:
<form action='' method='POST' autocomplete='off' enctype="multipart/form-data">
<p><strong>Title and Description:</strong></p>
<select name='uidtitle' class='chosen-select'>
<option value="0" ></option>
<?php
$result = $mysqli->query("SELECT uid, title, description FROM tblFacilityHrs") or die($mysqli->error);
while ($row = $result->fetch_array(MYSQLI_ASSOC)){
echo "<option value=\"1\">" . $row['title'] ." - " . $row['description'] . "</option>";
$uid = $row['uid'];
$title = $row['title'];
$desc = $row['description'];
}
?>
</select>
...
How can I send all three of those values (separately) to my postback for SQL?
if (isset($_POST['submitted'])) {
//Get params for prepared statements
$startDatec= date("Y-m-d H:i:s", strtotime($_POST['startEventDate']));
$endDatec= date("Y-m-d H:i:s", strtotime($_POST['endEventDate']));
$startTimec=$_POST['startTime'];
$endTimec=$_POST['endTime'];
$recurc=$_POST['recurrence'];
$finalc= date("Y-m-d H:i:s", strtotime($_POST['finalDate']));
...
I have no idea why you would need to send all three values back. Database Keys exist for the reason of being able to identify ALL fields in a record given just a single field, in this case I'm assuming uid. Passing that field alone would allow you to select the other fields in your postback before performing the operation that you intend.
However, it is possible using hidden form fields, although I don't advocate this approach.
<select name='uidtitle' class='chosen-select'>
<option value="0" ></option>
<?php
$result = $mysqli->query("SELECT uid, title, description FROM tblFacilityHrs") or die($mysqli->error);
$cacheArray = array(); // Used to store the information to be used below
while ($row = $result->fetch_array(MYSQLI_ASSOC)){
echo "<option value=\"" . $row['uid'] . "\">" . $row['title'] ." - " . $row['description'] . "</option>";
$cacheArray[] = $row;
}
?>
</select>
<?php
foreach($cacheArray as $k => $v) {
echo '<input type = "hidden" name = "title-' . $v['uid'] . '" value = "' . $v['title'] . '">';
echo '<input type = "hidden" name = "description' . $v['uid'] . '" value = "' . $v['description'] . '">';
}
?>
The hidden form fields will be present for all records in your tblFacilityHrs table. The names are made distinct by appending the uid to the name. You can determine what fields you are interested in in your postback by:
$_POST['title-'.$_POST['uidtitle']]
$_POST['description-'.$_POST['uidtitle']]