I am trying to make an advanced search engine, one in which you can search by first name, last name, zip, city, state, phone, cell phone and email.
I have managed to get it to search by first name, but you have to type the first name correctly as with anything else, I took out everything else but the first name search to find my problem yet, I have yet to find it, Here is a MySQL version of my search code that I am trying to convert to PDO.
MySQL:
<?php
//This is only displayed if they have submitted the form
if ($searching =="yes") {
echo "<h2>Results</h2><p>";
//If they did not enter a search term we give them an error
if ($find == "")
if ($f == "")
if ($info == "")
if ($zip == "")
if ($state == "")
if ($email == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to our Database
mysql_connect("xxx", "xxxx", "xxx") or die(mysql_error());
mysql_select_db("xxxx") or die(mysql_error());
// We preform a bit of filtering
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM users WHERE fname
LIKE '%" . mysql_real_escape_string($find) . "%' AND lname
LIKE '%" . mysql_real_escape_string($f) . "%' AND info
LIKE '%" . mysql_real_escape_string($info) . "%' AND zip
LIKE '%" . mysql_real_escape_string($zip) . "%' AND state
LIKE '%" . mysql_real_escape_string($state) . "%' AND email
LIKE '%" . mysql_real_escape_string($city) . "%' AND city
LIKE '%" . mysql_real_escape_string($email) . "%'");
?>
<?php
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo "<hr><br>First Name: ";
echo $result['fname'];
echo "<br>Last Name: ";
echo $result['lname'];
echo "<br>Home Phone: ";
echo $result['info'];
echo "<br>Cell Phone: ";
echo $result['cp'];
echo "<br>City: ";
echo $result['city'];
echo "<br>State: ";
echo $result['state'];
echo "<br>Zip: ";
echo $result['zip'];
echo "<br>Email: ";
echo $result['email'];
echo "<br><hr>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
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;
}
?>
Now here is my PDO version:
<?
$dsn = 'mysql:host=xxx;dbname=xxx;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,'xxx','xxx', $opt);
$stmt = $pdo->prepare("SELECT * FROM users WHERE fname= ?");
if ($stmt->execute(array($fname)));
while ($row = $stmt->fetch()) {
print $row['fname'] . "<br>";
print $row['lname'] . "\t<br>";
print $row['info'] . "\n<br>";
print $row['cp'] . "\n<br>";
print $row['state'] . "\n<br>";
print $row['city'] . "\n<br>";
print $row['zip'] . "\n<br>";
print $row['email'] . "\n<br>";
}
?>
Tips, advice, and comments are welcome and appreciated.
I guess you would build a sql-string and use parameters.
You would not include into your sql fields that the user left empty.
// **EDIT** check if there's any user-input...
if (!isset($_POST['fname']) && !isset($_POST['lname'])) { // add all your input-fields
echo "<p>please enter a search term!</p>";
echo 'try again";
exit();
}
$sql = '';
$bind = array();
if (strlen($_POST[‘firstname‘]) > 0) { // assuming your form-method is "post"
$sql .= 'AND fname LIKE :fname ';
$bind['fname'] = '%'.$_POST['firstname'].'%';
}
if (strlen($_POST['lastname']) > 0)
$sql .= 'AND lname LIKE :lname ';
$bind['lname'] = '%'.$_POST['lastname'].'%';
}
// ...
// do this will all of your input-fields...
$sql = 'SELECT * FROM users WHERE ' . trim($sql, 'AND') . ' ORDER BY lname';
$stmt = $pdo->prepare($sql);
$stmt->execute(array($bind));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// go ahead and display your results with foreach...
Your biggest problem is you’re using AND instead of OR in your WHERE clause. Change it to this:
SELECT *
FROM `table`
WHERE `name` LIKE '%string%'
OR `zip` LIKE '%string%'
// AND SO ON
Related
While selecting rows the data should be shown as:
but on the running code it is as:
My Codes:
<?php
$link = mysqli_connect("localhost", "root", "", "trial");
if(!$link){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$term = 'd';//mysqli_real_escape_string($link, $_REQUEST['term']);
if(isset($term)){
$sql = "SELECT * FROM rolls WHERE Place LIKE '%" . $term . "%'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
if(mysqli_num_rows($result) > 1000){
echo "<p>There are many results please be more specific</p>";
}
else{
while($row = mysqli_fetch_array($result)){
echo "<p><a href='#". $row['Place'] ."'>" . $row['Place'] . "</a></p>";
}
mysqli_free_result($result);
}
} else{
echo "<p>No matches found</p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
mysqli_close($link);
?>
On trying
$sql = "SELECT * FROM rolls WHERE Place LIKE '%" . $term . "%' LIMIT 1";
it only displays MANDYA, rest all are skipped
If you just want to display the place, use DISTINCT for showing unique values. Check out this query.
$sql = "SELECT DISTINCT(Place) FROM rolls WHERE Place LIKE '%" . $term . "%'";
I'm a designer and not developer, so I don't even know HOW to ask this question.
I have a select box in my script and it shows only one user type. But I need it to show more user types, for example, user_type 2, but Ive tried adding AND / OR and it doesnt work.
Heres the script code.
$result = mysql_query ('SELECT id,email,username FROM ' . $dbacct . '
WHERE user_type="3" ORDER BY username ASC', $link) or die(mysql_error());
Heres the full line
<select class=\'widtha\' name=\'contact_user\'>
';
$result = mysql_query ('SELECT id,email,username FROM ' . $dbacct . ' WHERE user_type IN ("2","3") ORDER BY username ASC', $link) or die(mysql_error());
while ($row = mysql_fetch_array ($result))
{
$row = safe_data ($row, 'display');
echo '<option value=\'' . $row['email'] . '\'';
if ($row[id] == $_POST[contact_user])
{
echo ' selected=\'selected\'';
}
echo '> ' . $row['username'] . '</option>';
}
echo '</select>
Please can someone help me.
Anton
$result = mysql_query ('SELECT id,email,username FROM ' . $dbacct . '
WHERE user_type IN ("1","2","3",....) ORDER BY username ASC', $link) or die(mysql_error());
Hello I am trying to echo out a variable $address into a google map url as such:
<iframe width="640" height="480" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.it/maps?q=<?php echo $address; ?>&output=embed"></iframe>
I can't get the variable to echo out in the <?php echo $address; ?>
Here is my pagination script, (depricated) I know.
This is the same script that I want the address to be echoed out into the url, so everytime someone searches if an address is brought up then it automatically generates a Static Map.
<?php
// Connects to your Database
mysql_connect("xxx", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
error_reporting(0);
//This checks to see if there is a page number. If not, it will set it to page 1
if (!(isset($pagenum)))
{
$pagenum = 1;
}
//Here we count the number of results
//Edit $data to be your query
$data = mysql_query("SELECT * FROM bus WHERE fname
LIKE '%" . mysql_real_escape_string($name) . "%' AND Address
LIKE '%" . mysql_real_escape_string($address) . "%' City
LIKE '%" . mysql_real_escape_string($city) . "%' AND state
LIKE '%" . mysql_real_escape_string($state) . "%' AND zip
LIKE '%" . mysql_real_escape_string($zip) . "%' AND phone
LIKE '%" . mysql_real_escape_string($phone) . "%' AND hours
LIKE '%" . mysql_real_escape_string($hours) . "%'") or die(mysql_error());
$rows = mysql_num_rows($data);
//This is the number of results displayed per page
$page_rows = 10;
//This tells us the page number of our last page
$last = ceil($rows/$page_rows);
//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum > $last) {
$pagenum = $last;
}
if ($pagenum < 1) {
$pagenum = 1;
}
//This sets the range to display in our query
$max = 'limit ' .((($pagenum == 0) ? 1 : $pagenum) - 1) * $page_rows .',' .$page_rows;
//This is your query again, the same one... the only difference is we add $max into it
$data_p = mysql_query("SELECT * FROM bus WHERE fname
LIKE '%" . mysql_real_escape_string($name) . "%' AND Address
LIKE '%" . mysql_real_escape_string($address) . "%' City
LIKE '%" . mysql_real_escape_string($city) . "%' AND state
LIKE '%" . mysql_real_escape_string($state) . "%' AND zip
LIKE '%" . mysql_real_escape_string($zip) . "%' AND phone
LIKE '%" . mysql_real_escape_string($phone) . "%' AND hours
LIKE '%" . mysql_real_escape_string($hours) . "%' $max") or die(mysql_error());
//This is where you display your query results
while($info = mysql_fetch_array( $data_p ))
{
echo "<hr width=500><table width=500><td id=table1><br>Business Name: ";
echo $info['fname'];
echo "<br>Address: ";
echo $info['Address'];
echo "<br>City: ";
echo $info['City'];
echo "<br>State: ";
echo $info['state'];
echo "<br>Zip Code: ";
echo $info['zip'];
echo "<br>Phone: ";
echo $info['phone'];
echo "<br>Hours: ";
echo $info['hours'];
echo "<br></td></table><hr width=500>";
}
// This shows the user what page they are on, and the total number of pages
echo " --Page $pagenum of $last-- <p>";
// First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we do nothing. If we aren't then we generate links to the first page, and to the previous page.
if ($pagenum == 1)
{
}
else
{
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> ";
echo " ";
$previous = $pagenum-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> ";
}
//just a spacer
echo " ---- ";
//This does the same as above, only checking if we are on the last page, and then generating the Next and Last links
if ($pagenum == $last)
{
}
else {
$next = $pagenum+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last -></a> ";
}
?>
<?php
?>
<?php
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data_p);
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> " .$fname;
?>
From php 4.0 you need to divine fields from a post with $_POST['field_name']. So you need to change it to $_POST['address'].
As the address for Google Maps can be anything from full address(zip,house number, street,area,town,region,state,country etc) to any combination of these your approach is wrong.
You should decide what elements you want and have a separate input for each of them. You can then build up the search address from these
$query = "SELECT * FROM `status_info_private` WHERE `id`=$id ORDER BY `Status_Date` DESC LIMIT 100";
if ($query_run = mysql_query($query)) {
while ($rows = mysql_fetch_array($query_run)) {
echo '<font color="#009900" > ' . $rows['Name'] . ' ' . ' Says :' . '</font><br/>';
echo '<p align="justify> ' . $rows['Private_status'] . '<br/>';
echo '<p align="right">' . $rows['Status_Date'] . '<br/>';
$like = $rows['Like'];
$unlike = $rows['Unlike'];
}
}
I think everything is correct in the piece of code. But still I am unable to get the output under the column titled as "Private_status". The above code is producing everything correctly except the message under cols "Private_status". I have already checked the spelling of the col name & there is no error in that part.
So, Please tell me what exactly is missing ?
first close your <p> tags and then do a print_r to check what is in $rows
..
Also, start using PDO or mysqli
$query = "SELECT * FROM `status_info_private` WHERE `id`=$id ORDER BY `Status_Date` DESC LIMIT 100";
if ($query_run = mysql_query($query)) {
while ($rows = mysql_fetch_array($query_run)) {
echo '<a href="view_profile.php?id=' . $id . '" color="#009900" > ' . $rows['Name'] . ' ' . ' Says :' . '</a><br/>';
echo '<p align="justify"> ' . $rows['Private_status'] . '</p>';
echo '<p align="right">' . $rows['Status_Date'] . '</p>';
$like = $rows['Like'];
$unlike = $rows['Unlike'];
}
}
<form method="post" action="oabtest.php?go" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
<p>A | B | C |D |E |F |G |H |I |J |K |L |M |N |O |P |Q |R |S |T |U |V |W |X |Y |Z </p>
<p>You may also search by Patrol.</p>
<form method="post" action="oabtest.php?go" id="searchform">
<input type="text" name="patrol">
<input type="submit" name="submit" value="Search">
</form>
<?php
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect("localhost", "*****", "*****");
if (!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db("troop97_***");
if (!$db) {
die("Unable to select database");
}
if (isset($_POST['submit'])) {
if (isset($_GET['go'])) {
if (preg_match("/[A-Z | a-z]+/", $_POST['name'])) {
$name = $_POST['name'];
//-query the database table
$sql = "SELECT ID, First_Name, Last_Name FROM contact WHERE First_Name LIKE '" . mysql_real_escape_string($name) . "%' OR Last_Name LIKE '" . mysql_real_escape_string($name) . "%'";
//-run the query against the mysql query function
$result = mysql_query($sql);
//-count results
$numrows = mysql_num_rows($result);
echo "<p>" . $numrows . " results found for " . stripslashes($name) . "</p>";
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$First_Name = $row['First_Name'];
$Last_Name = $row['Last_Name'];
$ID = $row['ID'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "" . $First_Name . " " . $Last_Name . "</li>\n";
echo "</ul>";
}
} else {
echo "<p>Please enter a search query</p>";
}
}
}
if (isset($_GET['by'])) {
$letter = $_GET['by'];
//-query the database table
$letter = mysql_real_escape_string($letter);
$sql = "SELECT ID, First_Name, Last_Name FROM contact WHERE First_Name LIKE '" . $letter . "%'
OR Last_Name LIKE '" . $letter . "%'";
//-run the query against the mysql query function
$result = mysql_query($sql);
//-count results
$numrows = mysql_num_rows($result);
echo "<p>" . $numrows . " results found for " . $letter . "</p>";
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$First_Name = $row['First_Name'];
$Last_Name = $row['Last_Name'];
$ID = $row['ID'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "" . $First_Name . " " . $Last_Name . "</li>\n";
echo "</ul>";
}
}
if (isset($_POST['submit'])) {
if (isset($_GET['go'])) {
if (preg_match("/[A-Z | a-z]+/", $_POST['patrol'])) {
$patrol = $_POST['patrol'];
//-query the database table
$patrol = mysql_real_escape_string($patrol);
$sql = "SELECT ID, First_Name, Last_Name FROM contact WHERE Patrol LIKE '" . mysql_real_escape_string($patrol) . "%'";
//-run the query against the mysql query function
$result = mysql_query($sql);
//-count results
$numrows = mysql_num_rows($result);
echo "<p>" . $numrows . " results found for " . $patrol . "</p>";
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$First_Name = $row['First_Name'];
$Last_Name = $row['Last_Name'];
$ID = $row['ID'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "" . $First_Name . " " . $Last_Name . "</li>\n";
echo "</ul>";
}
}
if (isset($_GET['id'])) {
$contactid = $_GET['id'];
//-query the database table
$sql = "SELECT * FROM contact WHERE ID=" . $contactid;
//-run the query against the mysql query function
$result = mysql_query($sql);
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$First_Name = $row['First_Name'];
$Last_Name = $row['Last_Name'];
$Home_Phone = $row['Home_Phone'];
$Cell_Phone = $row['Cell_Phone'];
$Work_Phone = $row['Work_Phone'];
$Email = $row['Email'];
$Home_Street = $row['Home_Street'];
$Home_City = $row['Home_City'];
$Home_State = $row['Home_State'];
$Home_Zip = $row['Home_Zip'];
$Troop_Role = $row['Troop_Role'];
$Patrol = $row['Patrol'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . $First_Name . " " . $Last_Name . "</li>\n";
echo (empty($Home_Phone)) ? '' : "<li>" . $Home_Phone . " Home</li>\n";
echo (empty($Cell_Phone)) ? '' : "<li>" . $Cell_Phone . " Cell</li>\n";
echo (empty($Work_Phone)) ? '' : "<li>" . $Work_Phone . " Work</li>\n";
echo "<li>" . "" . $Email . "</li>\n";
echo "<li>" . $Home_Street . "</li>\n";
echo "<li>" . $Home_City . ", " . $Home_State . " " . $Home_Zip . "</li>\n";
echo "<li>" . $Troop_Role . "</li>\n";
echo "<li>" . $Patrol . "</li>\n";
echo "</ul>";
}
}
}
}
SQL Injection Risk
If you ever use a value from a submitted form when interacting with a database, you should escape the content before doing so. In MySQL, the best function to do this is mysql_real_escape_string() PHP Manual
$sql="SELECT ID, First_Name, Last_Name FROM contact WHERE First_Name LIKE '" . mysql_real_escape_string( $name ) . "%' OR Last_Name LIKE '" . mysql_real_escape_string( $name ) ."%'";
Adding Fields to Search
If you are wanting to add an additional field, like "Department" to the search query, you simply have a field on the search form corresponding to it, and then adapt your SQL Search to have it included in the WHERE clause:
$sql="SELECT ID, First_Name, Last_Name
FROM contact
WHERE ( First_Name LIKE '" . mysql_real_escape_string( $name ) . "%'
OR Last_Name LIKE '" . mysql_real_escape_string( $name ) ."%' )
AND Department='" . mysql_real_escape_string( $department ) ."'";
Using One Field for Two Searches
If you wanted to use a single text field to perform the above search, you will need to decide on some kind of prefix for users to prefix the value for the second field with.
For instance, if we specify "in:" as a prefix to designate the Department, so a search for "John in:Radiology" would look for any person with a first, or last, name starting with "John" but only those in the "Radiology" department.
list( $name , $department ) = explode( ' in:' , $_POST['name'] , 2 );
instead of
$name = $_POST['name'];
LIKE Search Limitation
At the moment, your code will only search for First Names and/or Last Names which start with the entered value. You can make the search return either fields which simply contain (not just start with) the entered value by putting another "%" at the start of the search string:
$sql="SELECT ID, First_Name, Last_Name FROM contact WHERE First_Name LIKE '%" . $name . "%' OR Last_Name LIKE '%" . $name ."%'";
Full-Text Search
You may want to look at this tutorial - Using MySQL Full-text Searching. It covers the concepts of Full-Text Searching, will allows you to find one, or more, words submitted through a single field across multiple database fields.
Limit Returned Rows
Always a good idea to limit the number of rows you return for a search, whether you paginate or simply show X rows. Failing to do this would allow a malicious user to essentially scrape your whole database by simple searching for each letter of the alphabet.
Add your hypothetical field say search_field and then search for it with "SELECT * FROM contact WHERE search_field='search value' order by First_Name", don't forget to index on search_field if it is going to be a unique field like email. I hope the code you pasted above will not go into production. Do not trust user inputs and filter them properly before you used them in SQL queries, needless to say store db credentials and connection string in a separate file and include it.