Match key words in PHP - php

i have a search function on my website where users can search for products. it works perfectly fine except for the fact that when a user searches for 'ipod' it comes up with no result as the name of the product is 'apple ipod'. how do i code it so that when part of the name of the product is searched, the correct product comes up?
my code is as follows:
<div id="search" align="right">
<form action="" method="get">
<span id="sprytextfield1">
<input name="search" id="search2" type="text" width="250px"/>
<span class="textfieldRequiredMsg"></span></span>
<input name="" type="submit" value="Search"/>
</form></div>
<br /><br />
<h2>Your Search Results For "<?php echo $_GET['search'] ?>":</h2><hr />
<table border="0" cellpadding="2px" width="600px">
<?
$search = $_GET['search'];
$result=mysql_query("select * from products WHERE name = '$search'")
or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo ' '.'Could Not Be Found';
}
else {
while($row=mysql_fetch_array($result)){
?>
<tr>
<td><?php echo'<img src="getImage.php?id=' . $row['serial'] .'"/>'
?> </td>
<td> <b><?=$row['name']?></b><br />
Price:<big style="color:green">
£<?=$row['price']?></big><br /><br />
<input type="button" value="Add to Cart" onclick="addtocart(<?=$row['serial']?>)" />
</td>
</tr>
<tr><td colspan="2"><hr size="1" /></td>
<?
}
}?>
</table>
thanks for any advice given! :)

Ignoring the fact that your code should never be used for production (it's unsafe), you should use a LIKE in your query.
mysql_query("select * from products WHERE name LIKE '%$search%'")
Now, optimized against SQL injections and other things you don't want, this would become:
mysql_query("select * from products WHERE name LIKE '%".mysql_real_escape_string($search)."%'")

You can use a LIKE statement, like so
select * from products WHERE name LIKE '%$search%'
The above will match both 'apple ipod', 'ipod' and 'apple ipod'

Searching keyword in a table (eg: your product list) LIKE can be very useful but doesn't perform well on long text fields (eg: description), so consider also full text index and the MATCH () AGAINST operator.
Here mysql manual page
To avoid to return the page No results found, sorry, (after a none results query) you can use the SOUNDEX operator
mysql_query("select * from products WHERE SOUNDEX(name) > 0 ORDER BY SOUNDEX(name) DESC" ):
Here mysql soundex manual page

Related

Add and Remove Friend Button

I am with some difficulties on create an Add Friend and Remove Friend button.
For example if the 'accepted' row in mysql of table friends_request is equals to 1 then it should appears the 'Remove Friend' button, otherwise it should appears the 'Add Friend' button.
Here is the code of the buttons I did, which is wrong.
<?php
$selfriendsBtn = "SELECT fr.username
FROM (select from_username AS username
FROM friends_request
WHERE to_username = '".$_GET['u']."' AND accepted = 1
UNION ALL
SELECT to_username AS username
FROM friends_request
WHERE from_username = '".$_GET['u']."' AND accepted = 1) AS fr
JOIN users AS u ON u.username = fr.username LIMIT 5";
$resultfriend_add_rmv = $sql->query($selfriendsBtn);
$rowAdd_RmvFriend = mysqli_fetch_assoc($resultfriend_add_rmv);
$accepted = $rowAdd_RmvFriend['accepted'];
if($user != $_GET['u']) {
if($accepted == 1) {
?>
<table>
<tr>
<td>
<form action="profile.php?u=<?php echo $_GET['u']; ?>&deleted=<?php echo $user; ?>" method="POST">
<input type="submit" name="rmvfriend" value="Remove Friend" />
</form>
</td>
<td>
<form action="profile.php?u=<?php echo $_GET['u']; ?>&a=compose" method="POST">
<input type="submit" name="msg" value="Message" />
</form>
</td>
</tr>
</table>
<?php
} else {
?>
<table>
<tr>
<td>
<form action="profile.php?u=<?php echo $_GET['u']; ?>&requested=<?php echo $user; ?>" method="POST">
<input type="submit" name="addfriend" value="Add Friend" />
</form>
</td>
<td>
<form action="profile.php?u=<?php echo $_GET['u']; ?>&a=compose" method="POST">
<input type="submit" name="msg" value="Message" />
</form>
</td>
</tr>
</table>
<?php
}
}
?>
The SELECT tables I pick up from the friends.php page and implemented it on here.
I don't know why it's not working. Should I use loop or not? Well, in my opinion I think a loop it would work very well on this.
You're looking for a value that isn't present in the result set:
$accepted = $rowAdd_RmvFriend['accepted'];
The only value you select from the database is the username:
SELECT fr.username
FROM ...
So $accepted will never be equal to 1. Thus, this will always be false:
if ($accepted == 1)
So the else block (the "Add Friend" button) will always be shown.
You should also select the accepted value from your query so you can use it in your logic. This is mostly a guess based on your query so far, but it looks like you'd need to add it in three places:
SELECT fr.username, fr.accepted -- here
FROM (select from_username AS username, accepted -- here
FROM friends_request
WHERE to_username = ? AND accepted = 1
UNION ALL
SELECT to_username AS username, accepted -- here
FROM friends_request
...
Keep in mind that nobody here really knows your data, so you may need to tinker with the query a little bit in your database management tools to get it just right.

How to make search form where user has three columns to search.Using PHP AND SQL AND HTML

I was wondering how to make a search form where user has 3 options to search with
Search By age (dropdown 18-25 & 26-40)
Search By gender (male or female)
Search By name
In my code, when I click "Submit" with blank fields, it's throwing all data which i don't it to:
<?php
$output = NULL;
if (isset ( $_POST ['submit'] )) {
// Connect to database
$mysqli = new Mysqli ( "localhost", "root", "2222", "matrimonialPortal" );
$search = $mysqli->real_escape_string ( $_POST ['search'] );
// Query the databse
$resultSet = $mysqli->query ( "SELECT * FROM mp_user WHERE name LIKE '%$search%' OR email LIKE '%$search%' OR salutation LIKE '%$search%' OR id LIKE '%$search%'" );
if ($resultSet->num_rows > 0) {
while ( $rows = $resultSet->fetch_assoc () ) {
$name = $rows ['name'];
$email = $rows ['email'];
$output .= "::<strong>The Details of your search</strong> ::<br /> Name: $name<br /> Email:$email<br /><br /> ";
}
} else {
$output = "Oops No results Found!!";
}
}
?>
<!-- The HTML PART -->
<form method="POST">
<div>
<p>
Search By name: <input type="TEXT" name="search" /> <input
type="SUBMIT" name="submit" value="Search >>" />
</p>
</div>
<div>Search By Age :
<select name="age">
<option></option>
<option value="18-20">18-20</option>
<option value="20-25">20-25</option>
</select><input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br />
<div>
Search By Gender:
<select name="salutation">
<option></option>
<option value="0">--- Male ---</option>
<option value="1">--- Female ---</option>
</select> <input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br> <br>
</form>
<?php echo $output; ?>
It seems like you are new to PHP. Here is a solution for you.
First HTML PART. Here use "action" which means that the page will locate the file and process data. For example action="search_process.php". But if you are processing the data from the same page use $_SERVER['PHP_SELF'];
<!-- The HTML PART -->
<form method="POST" action="$_SERVER['PHP_SELF']"> // here it will load the self page
<div>
<p>
Search By name: <input type="text" name="search_name" />
Search By age: <input type="text" name="search_age" />
Search By gender: <input type="TEXT" name="search_gender" />
<input type="submit" name="submit_name" value="Search >>" />
</p>
</div>
Now the PHP part:
<?php
if(isset($_POST['submit_name'])
{
//What happens after you submit? We will now take all the values you submit in variables
$name = (!empty($_POST['search_name']))?mysql_real_escape_string($_POST['search_name']):null; //NOTE: DO NOT JUST USE $name = $_POST['search_name'] as it will give undefined index error (though your data will be processed) and will also be open to SQL injections. To avoid SQL injections user mysql_real_escape_string.
$age = (!empty($_POST['search_age']))?mysql_real_escape_string($_POST['search_age']):null;
$gender = (!empty($_POST['search_gender']))?mysql_real_escape_string($_POST['search_gender']):null;
//Now we will match these values with the data in the database
$abc = "SELECT * FROM table_name WHERE field_name LIKE '".$name."' or field_gender LIKE '".$gender."' or field_age LIKE '".$age."'"; // USE "or" IF YOU WANT TO GET SEARCH RESULT IF ANY OF THE THREE FIELD MATCHES. IF YOU WANT TO GET SEARCH RESULT ONLY WHEN ALL THE FIELD MATCHES THEN REPLACE "or" with "and"
$def = mysql_query($abc) or die(mysql_error())// always use "or die(mysql_error())". This will return any error that your script may encounter
//NOW THAT WE HAVE GOT THE VALUES AND SEARCHED THEM WE WILL NOW SHOW THE RESULT IN A TABLE
?>
<table cellspacing="0" cellpadding="0" border"0">
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
<?php while($row = mysql_fetch_array($def)) { // I HAD MISSED OUT A WHILE LOOP HERE. SO I AM EDITING IT HERE. YOU NEED TO USE A WHILE LOOP TO DISPLAY THE DATA THAT YOU GOT AFTER SEARCHING.
<tr>
<td><?php echo $row[field_name]; ?></td>
<td><?php echo $row[field_age]; ?></td>
<td><?php echo $row[field_gender]; ?></td>
</tr>
<?php } ?>
</table>
<?php } ?>
A perfect solution for your query. All the best.
Well i cant give you the whole code, but here are the few solutions..
Use 3 different forms with 3 different submit buttons.
Use radio buttons on html form, and make a check on PHP side and perform operations depending upon what or which radio is selected.
Use a button instead of submit, radio buttons, hidden fields, and pass data to different php page on form submit (this can be lengthy).
Well you have options.
You can replace your code
if ($resultSet->num_rows > 0) {
with this
if ($resultSet->num_rows > 0 and trim($search) != "") {
so it will not show all results if your input box is empty
hope this will help you
Edit
here is an example you can get idea
$qry = "SELECT * FROM test WHERE 1=1";
if($purpose!="")
$qry .= " AND purpose='$purpose'";
if($location!="")
$qry .= " AND location='$location'";
if($type!="")
$qry .= " AND type='$type'";
and for age
if ($age!='') {
$qry .= " AND age between ".str_replace('-',' and ',$age);
}
When you POST a blank variable and Query with %$search% and 'OR' other criteria, sql matches all records with space in column Name ! So you will have to use some variation of;
If(empty($POST['search']){ ['Query witbout Name parameter']} else{['Query with Name parameter']}
As for converting DOB to match age range. You will have to use
SELECT TIMESTAMPDIFF
answered here
calculate age based on date of birth

making a search under this coding process

this codes below came from my friend. i want to make a search under this codes . from this codes , it will display all the users to delete. what i want is i want to put search box and search button . so when i insert user id and press search only then it display which user that i want . where should i put this search text , button and php ? i want to put it under this else if codes . help me. im new :(
else if($_SESSION['jawatan'] == 'ADMIN') { ?>
<li> VIEW PROFILE </li>
<li> VIEW REQUEST </li>
<li>LOG OUT</li>
<li><img src="msc.jpg" width = "240" height ="80"></li>
<form method="get">
<input type="text" name="userid" placeholder="search" />
<inpu type="submit" value="Search" />
</form>
<h3>View User</h3>
<table border='1'>
<tr>
<td><b>#</b></td>
<td><b>Nama</b></td>
<td><b>Email</b></td>
<td><b>Division</b></td>
<td><b>Department</b></td>
<td><b>Delete</b></td>
</tr>
<?php
$i = 1;
$whr="";
if(isset($_GET['userid'])){
$whr.= " and mem_id='".$_GET['userid']."'"; // which field you want. If you want to do search name use LIKE instead =(equal to)
}
$result = mysql_query("SELECT * FROM members WHERE mem_role='USER' ".$whr);
if(mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
?>
<tr>
<td>
<?php echo $i; ?>
</td>
<td>
<?php echo $row['mem_name']; ?>
</td>
<td>
<?php echo $row['mem_email']; ?>
</td>
<td>
<?php echo $row['mem_division']; ?>
</td>
<td>
<?php echo $row['mem_department']; ?>
</td>
<td>Delete</td>
</tr>
<?php
$i++;
}
} else {
echo '<tr><td>No results found</td></tr>';
}
?>
</table>
<?php
}
HTML
<form method="get">
<input type="text" name="userid" placeholder="search" />
<inpu type="submit" value="Search" />
</form>
PHP
$whr="";
if(isset($_GET['userid'])){
$whr.= " and mem_id='".$_GET['userid']."'"; // which field you want. If you want to do search name use LIKE instead =(equal to)
}
MYSQL
$result = $result=mysql_query("SELECT * FROM members WHERE mem_role='USER' ".$whr);// add whr variable here
I can tell you the steps:
Create search text field and search button ( wrap in form if you want to do with php only)
on click of button ( that would be submit ), fetch that value from search text box and run query based on that
when results appear , fill the table data with that results using foreach.
hope it helps. Ask me for any issue.

PHP While loop only works for first two of three results?

I know I am a beginner, but I have an issue I can't figure out. I've searched everywhere. Please don't be mean:) I'm trying to learn!:)
SO I have a while loop that is making an HTML table for me, and two of the three row[] echoes work every time, but the third echoes only the ID of the last entry in the table.
My code:
<?php
$searchsql = "SELECT * FROM `students` WHERE `fname` LIKE '%" . $searchvalue1 . "%' LIMIT 0, 10 ";
$search1result = mysql_query($searchsql);
while($search1row=mysql_fetch_array($search1result)){?>
<h3>
<table align="center">
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Select</td>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $search1row['fname'];?></td>
<td><?php echo $search1row['lname'];?></td>
<td>
<form method="post" action="4.php">
<input type="hidden" id="voteid" name="voteid" class="inputbutton" value="<?php echo $search1row['studentid'];?>">
<input type="submit" class="inputbutton" value="SELECT">
</td>
</tr>
</tbody>
</table>
</h3>
<?php }?>
So if the table returned is (see picture)
The select button from within that form always posts the studentid from the LAST row... Every select button posts Jane's ID number. So John, Jason, Jane, and their last names are echoed correctly, but their corresponding ID numbers are not... if that makes any sense.
I have to keep it a form because of the way my site works (not a link with get variables).
Any ideas on how to get the ID to echo inside of that form?
You're not closing the form at the end of each loop. So each time the voteid input is getting overwritten which is why it always posts the id for the last row.
Add a closing form tag:
...
<form method="post" action="4.php">
<input type="hidden" id="voteid" name="voteid" class="inputbutton" value="<?php echo $search1row['studentid'];?>">
<input type="submit" class="inputbutton" value="SELECT">
</form>
...

Issue using 2 fields in PHP form to retrieve information from a MySQL Database

I have a MySQL database with 3 columns:
id | articletitle | articleorganization
And a simple PHP form with 2 fields and a submit button: search.php
<div class="content">
<form id="form1" name="form1" method="post" action="searchdb.php">
<table width="100%" border="0" cellpadding="6">
<tr>
<td width="29%" align="right">Article Title:</td>
<td width="71%" align="left"><input name="title" type="text" id="articletitle" size="50" /></td>
</tr>
<tr>
<td align="right">Author or Organization:</td>
<td align="left"><input name="organization" type="text" id="articleorganization" size="50" /></td>
</tr>
</table>
<table width="100%" border="0" cellpadding="6">
<tr>
<td><input type="submit" name="submit" value="Submit" /></td>
</tr>
</table>
</form>
</div>
The form connects to searchdb.php:
<?php
include('settings.php');
$title = mysql_real_escape_string($_POST['title']);
$organization = mysql_real_escape_string($_POST['organization']);
$sql = "SELECT * FROM articles WHERE 1 "
. (isset($title) ? "AND articletitle LIKE '$title%' " : "")
. (isset($organization) ? "AND articleorganization LIKE '$organization%'" : "");
while ($row = mysql_query($sql)){
echo '<br/> Article Title: '.$row['articletitle'];
echo '<br/> Article Organization: '.$row['articleorganization'];
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo '<td>View Full Entry</td>';
echo '<br/><br/>';
}
?>
After some revision with the help of commenters the problem has changed.
Now, upon submitting a search, the results page begins scrolling the table that is created via searchdb.php over and over again, though without any results in the table.
If you echo your query, it will print something like this:
select * from articles where articletitle like '%%'
That's why your code returning all rows from the table. To make it work the way you want, change the name of your <input> to match with your columns.
<input type="text" name="title" />
<input type="text" name="organization" />
Given these tags, you'll have $_POST contains array like this:
Array
(
[title] => 'some value',
[organization] => 'another value',
)
And you have to perform some logic in your query. If only title is supplied,
SELECT * FROM articles WHERE articletitle LIKE '%$title%'
If only organization is supplied,
SELECT * FROM articles WHERE articleorganization LIKE '%$organization%'
If both are supplied,
SELECT * FROM articles
WHERE articletitle LIKE '%$title%' AND
articleorganization LIKE '%$organization%'
Here's the PHP to make SQL like above:
// Don't forget to properly escape your input
$title = mysql_real_escape_string($_POST['title']);
$organization = mysql_real_escape_string($_POST['organization']);
// Build the SQL
// Echo this string to make sure the SQL is correct
$sql = "SELECT * FROM articles WHERE 1 "
. (strlen($title) ? "AND articletitle LIKE '%$title%' " : "")
. (strlen($organization) ? "AND articleorganization LIKE '%$organization%'" : "");
$qry = mysql_query($sql);
Basically, when you have several items with the same name referencing some kind of array what you get is an actual array afterwards.
That is to say that if the input boxes are filled with "a" and "b" the variable $_POST['term'] will be equal to array("a", "b").
With regards to indenting, it is part of your code style, do it whatever way you feel comfortable with as long as you are consistent across your whole code base.
Edit: I do agree with others that you should be a lot more careful with user input and how you add that data to your queries
$_POST[term] becomes an array with key's like 0,1. Loosing the field reference for your SQL query.
Use these names in your input fields:
<input name="articletitle" type="text" id="articletitle" size="50" />
<input name="articleorganization" type="text" id="articleorganization" size="50" />
You can build your query like this:
$sql = mysql_query("select * from articles WHERE articletitle LIKE '%".mysql_real_escape_string($_POST['articletitle'])."%' OR articleorganization LIKE '%".mysql_real_escape_string($_POST['articleorganization'])."%'");
Note: Never ever use $_POST (user input) vars in a query without escaping first to prevent mysql injection.
PS My personal taste on indenting is: Always indent every block of matching HTML elements. So yes, I would indent the table one tab further.

Categories