What is wrong with this php search page? - php

I found a tutorial that looked like it would do what I've been trying to do without success. I adapted it to my details and tried it. It doesn't work. When you enter the search and hit submit, all it does is go back to the beginning. I can't see anything wrong with the code so after a couple of hours of trying things, here it is. Can you see what is wrong?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>test</title>
</head>
<body>
<?
if ($searching =="yes")
{
echo "<h2>Search</h2><p>";
if ($find == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
mysql_connect('localhost', 'user', 'password') or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
$data = mysql_query("SELECT * FROM engravers WHERE upper($field) LIKE'%$find%'");
while($result = mysql_fetch_array( $data ))
{
echo $result['Country'];
echo "<br>";
echo $result['Year'];
echo "<br>";
echo $result['Engraver1Surname'];
echo "<br>";
echo $result['Designer1Surname'];
echo "<br>";
echo $result['Printer'];
echo "<br>";
echo "<br>";
}
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
echo "<b>Searched For:</b> " .$find;
}
?>
<h2>Search</h2>
<form name="search" method="post" action="<?=$PHP_SELF?>">
Search for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="Country">Country</option>
<Option VALUE="Year">Year</option>
<Option VALUE="Engraver1Surname">Engraver</option>
<Option VALUE="Designer1Surname ">Designer</option>
<Option VALUE="Printer">Printer</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>
</body>
</html>

As mentioned in my comment, after POSTing, you need to grab the variables from the $_POST array. Something like:
if ($_POST['searching'] == "yes") {
$find = $_POST['find'];
$field = $_POST['field'];
// etc...

This looks like very old PHP code that had register_globals on. It doesn't work like that anymore.
Use the superglobal $_POST to get to your variables, for example:
if ($_POST['searching'] =="yes") {
...
}
Also, read into SQL injection and how to avoid it.

You need to set the variables on begin:
//set default values
$find="";
$searching="";
$field="";
If(isset($_POST['searching']) && $_POST['searching']="yes"){
$find= mysql_real_escape_string($_POST['find']);
$searching=mysql_real_escape_string($_POST['searching']);
$field=mysql_real_escape_string($_POST['field']);
...

Related

How to retrieve values from SQLite 3 database on the basis of multiple check boxes selected at once in PHP?

I am new to PHP coding. I have different preferences for the user to select from my html page. I want to retrieve all the check boxes selected by the user and display the hotel names which have all those preferences in them. For example if a user selects "Roof top", "Sea side" and "Swimming pool" check boxes, then the hotels against which their is a 1 placed in the respective columns in the mytrip.db database must be retrieved all at once and get displayed. My code takes only one checkbox value and displays the hotel name against that only. I want to display the hotels that contain all the preferences.
My code is below:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>PHP: Get Values of Multiple Checked Checkboxes</title>
<link rel="stylesheet" href="css/php_checkbox.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP: Get Values of Multiple Checked Checkboxes</h2>
<select id="mySelect" name="list">
<option selected>Select a place</option>
<option value="1">Lahore</option>
<option value="2">Dubai</option>
<option value="3">New York</option>
<option value="4">Canberra</option>
<option value="5">London</option>
</select>
<form action="php_checkbox.php" method="post">
<label class="heading">Select Your Preferences:</label>
<input type="checkbox" name="check_list[]" value="Swimming pool"><label>Swimming pool</label>
<input type="checkbox" name="check_list[]" value="Roof top"><label>Roof top</label>
<input type="checkbox" name="check_list[]" value="Sea side"><label>Sea side</label>
<input type="submit" name="submit" Value="Submit"/>
</html>
<?php include 'checkbox_value.php';?>
</form>
</div>
</div>
</body>
</html>
checkbox_value.php code is below:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('mytrip.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
if(isset($_POST['submit'])){
if(!empty($_POST['check_list'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['check_list']);
echo "You have selected following ".$checked_count." option(s): <br/>";
$prefarray=array();
$i=0;
// Loop to store and display values of individual checked checkbox.
foreach($_POST['check_list'] as $selected) {
$prefarray[$i]= $selected;
echo "<p>".$prefarray[$i] ."</p>";
echo "<p>".$selected ."</p>";
$i++;
}
echo "<p>".$i ."</p>";
$sql =<<<EOF
SELECT hotel_name from Dubai WHERE $prefarray[i]==1 AND $prefarray[i-1]==1 ;
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "<p> <br /></p>\n";
echo "\n". $row['hotel_name'] . "\n";
}
$db->close();
echo "<br/><b>Note :</b> <span>Similarily, You Can Also Perform CRUD Operations using These Selected Values.</span>";
}
else{
echo "<b>Please Select Atleast One Option.</b>";
}
}
?>
The problem with this code is that it only displays one checkbox value if I use query
SELECT hotel_name FROM Dubai WHERE $selected==1
I tried to save the check box values selected by making an array "prefarray". But when I execute the query that I have posted in my checkbox_value.php code it gives me error of "Undefined offset 3 in prefarray". I want the data base query to have only those checkbox values that have been selected by the user. For example if the user has selected 2 out of three checkboxes then my query should look like
SELECT hotel_name FROM Dubai WHERE $checkbox==1 AND $checkbox2==1;
Any help to achieve two of these tasks will be appreciated!
I have fixed and refactored (couldn't stop myself) your code.
I have changed column names to proper ones. There was some redundant code which did nothing so I got rid of it. The main thing you were looking for is concatenating each chosen column in foreach loop. I'm also checking selected values against hard coded $hotelOptions for protection against sql injection.
Here is what I got:
checkbox_value.php:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('mytrip.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$hotelOptions = array('swimming_pool', 'roof_top', 'sea_side');
if (isset($_POST['submit'])) {
if (!empty($_POST['check_list']) && is_array($_POST['check_list'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['check_list']);
echo "You have selected following ".$checked_count." option(s): <br/>";
// Loop to store and display values of individual checked checkbox.
$where = '';
foreach($_POST['check_list'] as $selected) {
echo "<p>".$selected ."</p>";
if (array_search($selected, $hotelOptions) !== false) {
$where .= " AND {$selected} = 1";
}
}
$where = substr($where, 5, strlen($where));
$sql = "SELECT hotel_name FROM Dubai WHERE {$where};";
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "<p> <br /></p>\n";
echo "\n". $row['hotel_name'] . "\n";
}
$db->close();
echo "<br/><b>Note :</b> <span>Similarily, You Can Also Perform CRUD Operations using These Selected Values.</span>";
} else {
echo "<b>Please Select Atleast One Option.</b>";
}
}
html layout:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>PHP: Get Values of Multiple Checked Checkboxes</title>
<link rel="stylesheet" href="css/php_checkbox.css"/>
</head>
<body>
<div class="container">
<div class="main">
<form action="checkbox_value.php" method="post">
<h2>PHP: Get Values of Multiple Checked Checkboxes</h2>
<select id="mySelect" name="list">
<option selected>Select a place</option>
<option value="1">Lahore</option>
<option value="2">Dubai</option>
<option value="3">New York</option>
<option value="4">Canberra</option>
<option value="5">London</option>
</select>
<p class="heading">Select Your Preferences:</p>
<input type="checkbox" name="check_list[]" value="swimming_pool" id="checkbox_1">
<label for="checkbox_1">Swimming pool</label>
<input type="checkbox" name="check_list[]" value="roof_top" id="checkbox_2">
<label for="checkbox_2">Roof top</label>
<input type="checkbox" name="check_list[]" value="sea_side" id="checkbox_3">
<label for="checkbox_3">Sea side</label>
<div>
<input type="submit" name="submit" Value="Submit"/>
</div>
<?php include 'checkbox_value.php';?>
</form>
</div>
</div>
</body>
</html>

Trouble With PHP Database Search Form

I have a database created with five fields
ValueA
ValueB
ValueC
ValueD
ValueE
and I am trying to make a search form that can search by each of these individual fields, e.g if the value in ValueB was "Blue", select ValueB from the dropdown then type in "Blue" to print out all the values in the row that Blue was a part of. So far, I've created an html file called "findme.html":
<html>
<head>
<title>Search</title>
</head>
<body bgcolor=#ffffff>
<h2>Search</h2>
<form name="search" method="post" action="findme2.php">
Search for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="ValueA">Value A</option>
<Option VALUE="ValueB">Value B</option>
<Option VALUE="ValueC">Value C</option>
<Option VALUE="ValueD">Value D</option>
<Option VALUE="ValueE">Value E</option>
</Select>
<input type="submit" name="search" value="Search" />
</form>
</body>
</html>
and also created a php file called "findme2.php":
<html>
<head>
<title>Searching through Database Table mytablename</title>
</head>
<body bgcolor=#ffffff>
<?php
include "config.php";
echo "<h2>Search Results:</h2><p>";
if(isset($_POST['search']))
{
$find =$_POST['find'];
}
//If they did not enter a search term we give them an error
if ($find == "")
{
echo "<p>You forgot to enter a search term!!!";
exit;
}
// Otherwise we connect to our Database
$username="xxxxxxxx";
$password="xxxxxxxx";
$database="xxxxxx_xxxxxxx";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
// We perform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
$iname = mysql_query("SELECT * FROM mytablename WHERE upper($field) LIKE '%$find%'")
or die(mysql_error());
//And we display the results
while($result = mysql_fetch_array( $iname ))
{
echo "id :" .$result['ValueA'];
echo "<br> ";
echo "name :".$result['ValueB'];
echo "<br>";
echo "name :".$result['ValueC'];
echo "<br>";
echo "name :".$result['ValueD'];
echo "<br>";
echo "name :".$result['ValueE'];
echo "<br>";
echo "<br>";
}
$anymatches = mysql_num_rows($iname);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query...<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
?>
</body>
</html>
I believe my problem is with the query command, but I am not sure how to adjust the syntax. Can anyone help me?
You forgot to set your $field variable.
In your if statement, you should change it to
if(isset($_POST['search']))
{
$find =$_POST['find'];
$field =$_POST['field'];
}
It should work then.

Dynamic Radio Button Error

Hey guys I'm relatively new to PHP and I've come across an issue with my Syntax I cant seem to fix (I've only started 2-3 weeks ago) and this is my second time trying to generate something 'dynamic generated' from the database.
I'm using radio buttons, so what I'm trying to do is my radio buttons will be generated from my database table and the form which its using will send the information of the value so like 'staffID' to another page to process that info
This is the error I'm getting:
syntax error, unexpected T_STRING, expecting ',' or ';'
I've looked it up it's saying I have some unterminated string of some sort at line 22 which is my echo in my while loop and I'm not too sure what to make of it.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>PHP Task 10</title>
</head>
<body>
<?php
$conn = mysql_connect("xxxxxx", xxxxxx", "xxxxxxxx");
mysql_select_db("xxxxxxxx", $conn)
or die ('Database not found ' . mysql_error() );
$sql = "SELECT staffName, staffID
FROM staff";
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
?>
<form id="staff" action="task7.php" method="get">
<?php
while($row = mysql_fetch_array($rs)){
echo "<input type="radio" name="staffID" value=<?php echo '".$row["staffID"]."'?>><?php echo ".$row["staffName"]."?>";
};
?>
<p><input type="submit" value="Submit">
<input type="reset" value="Reset"></p>
</form>
</body>
</html>
You have some mistakes in your code. While you are echoing a string with PHP, you don't need to add <?php ?> tags and echo each time like,
value=<?php echo '".$row["staffID"]."'?>
Change
while($row = mysql_fetch_array($rs)){
echo "<input type="radio" name="staffID" value=<?php echo '".$row["staffID"]."'?>><?php echo ".$row["staffName"]."?>";
};
to
while($row = mysql_fetch_array($rs)){
echo "<input type='radio' name='staffID' value='".$row["staffID"]."'>".$row["staffName"];
}
You cannot echo inside echo in PHP :
echo "<input type="radio" name="staffID" value=<?php echo '".$row["staffID"]."'?>><?php echo ".$row["staffName"]."?>";
This should be like :
echo "<input type='radio' name='staffID' value='".$row["staffID"]."'>".$row["staffName"];

How to keep the value of selected item of a drop down after form submission in PHP?

I am just building a simple search page in PHP. I need to know how can i keep the selecte value of the drop down list upon form submission. Currently, the value resets to the first index.
Can I do this via PHP without using client-side script?
Here is the code:
<?php
mysql_connect('localhost','root','');
mysql_select_db('hotel');
$sql = "SELECT * FROM customers";
$result = mysql_query($sql);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form method="get">
<select name="field" id="field">
<?php
/*if($field == 'Active')
'selected="selected"';
*/
while($rows = mysql_fetch_array($result))
echo '<option>'.$rows['customer_id'].'</option><br>';
?>
</select>
<?php
if (isset($_GET['Search']) && $_GET['action']=='search')
{
$sql="SELECT * FROM customers WHERE customer_id=".$_GET['field'];
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
echo '<br>Customer Name: '.$row['customer_name'].'<br>';
echo 'Email Address: '.$row['Email_Addr'].'<br>';
echo 'Contact No: '.$row['Contact_No'].'<br>';
}
?>
<input type="hidden" name="action" value="search" />
<br><input type="submit" value="search" name="Search" onclick="" />
</form>
</body>
</html>
usually like this.
echo '<option';
if ($_GET['field'] == $rows['customer_id']) echo " selected";
echo '>'.$rows['customer_id'].'</option>';
And please don't use the mysql_* functions to write new code, especially when you are learning. The mysql_* functions are in the process of becoming deprecated, they will be removed in future versions of PHP. Use mysqli_* or PDO objects instead.
You can check if the get value is the same than the select value :
while($rows = mysql_fetch_array($result))
echo '<option value="'.$rows['customer_id'].'" '.($rows['customer_id'] == $_GET['field']?'selected="selected"':'').'>'.$rows['customer_id'].'</option><br>';
When printing the select options, you can check for the value and set any mathing option to selected, maybe like this:
while($rows = mysql_fetch_array($result)){
if(!empty($_GET['field']) && $_GET['field'] == $rows['customer_id']){
echo '<option selected="selected">'.$rows['customer_id'].'</option><br>';
}
else {
echo '<option>'.$rows['customer_id'].'</option><br>';
}
}

How to make the php strings selectable for the html query?

I'm looking to make the the suggestions given by the Dictionary API to become links that can be queried or that are inserted directly in to the text are field before they are searched. I'm looking to achieve some kind of query expansion in any case.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Search Attempt</title>
</head>
<body>
<form method="POST" action='AllinOneMonstaaa.php'>
<label for="query">Query</label><br/>
<input name="query" type="text" size="60" maxlength="60" value="" /><br /><br />
<select name ="agg">
<option value="Aggregated">Aggregated</option>
<option value="Non-Aggregated">Non-Aggregated</option>
<option value="Bing">Bing</option>
<option value="Blekko">Blekko</option>
<option value="Faroo">Faroo</option>
</select>
<input name="bt_search" type="submit" value="Search" /> </form>
<h2> Results </h2>
</body>
</html>
<?php
if ($_POST['query'])
{
$query = urlencode($_POST['query']);
$s_count = 0;
$ss_count = 0;
$query = 'http://www.dictionaryapi.com/api/v1/references/collegiate/xml/'.$query.'?
$xml = new SimpleXMLIterator(file_get_contents($query));
foreach ($xml -> suggestion as $suggestion[$s_count])
{
$s_count++;
}
if ($s_count > 1)
{
echo ('<h4>Did you mean?</h4>');
while ($ss_count <=$s_count)
{
echo ($suggestion[$ss_count].'<br>');
$ss_count++;
}
}
}
'Quick bug, there's a missing ' on the $query line.
echo '<a href="whatever">'. $suggestion[$ss_count].'<br>';
Edit: This will send them to Dictionary.com with the word to look up there. Outside that I have no idea how else you would formulate the url.
echo '<a href="http://dictionary.reference.com/browse/"' . $suggestion[$ss_count] . '" target="_new">' . $suggestion[$ss_count] . '<br>';

Categories