php keyworks search do not works - php

i want to retrieve data in database by using search engine i create.
it pass the search keywords from testseach.php to searchTitle.php.
here is my code for test seach.php
>!DOCTYPE html>
<html>
<head><title></title>
</head>
<body>
<form action="searchTitle.php" method="GET" class="formright">
<input type="text" name="keywords" placeholder="Search">
<input type="submit" value="search">
</form>
</body>
</html>
here is my searchtitle.php which pass the keywords from testsearch.
<? php
require_once 'database_conn.php'
//collect search title
if(isset($_GET['keywords'])){
$searchq = $_GET['keywords'];
$searchq = preg_replace("#[^a-z]#i" , "", $searchq);
$query = mysql_query("SELECT eventTitle FROM te_events where eventTitle LIKE '%searchq%'") or die("could not search!");
$count = mysqli_num_rows($query);
if($count==0){
echo "<p>There was no search result!</p>\n";
}
else{
while ($row = mysql_fetch_assoc($query)){
$title = $row['eventTitle'];
$id = $row['eventID'];
echo "<p>$title</p>\n";
}
}
}
?>
however, it shows this error
There was no search result! \n"; } else{ while ($row =
mysql_fetch_assoc($query)){ $title = $row['eventTitle']; $id =
$row['eventID']; echo " $title
\n"; } } } ?>
i pretty sure that my database connection is working and i don't see any typo in my code.
can anyone tell me what's is my problem?

There are some mistake
1)$query = mysql_query("SELECT * FROM countries",$connection) or die("could not search!");
In mysql_query you add connection variable
please refer syntax as per php documentation
2) You use $count = mysqli_num_rows($query); for get number of raw but you use mysql_num_rows instead of mysqli_num_rows
OR
Please check php version and that compatible with mysql or mysqli
please check it also because that may cause that type of issue also
this answer may be help you.

Related

PHP search box - Display search correctly

I'm building a search function for a website. What I don't like is that if I enter some special symbols Like < or > or % or others in the search box it prints out the whole database content even if there are no such symbols in the search entries.
What should I do so the search outputs only entries which contains the special symbol. And not the all entries which database contains.
Code:
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());;
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM users WHERE firstname LIKE '%$searchq%' OR lastname LIKE '%$searchq%'") or die("Could not search!");
$count = mysql_num_rows($query);
if ($count == 0) {
$output = 'There was no search results!';
} else {
while($row = mysql_fetch_array($query)) {
$fname = $row['firstname'];
$lname = $row['lastname'];
$id = $row['id'];
$output .= '<div>'.$fname.' '.$lname.'</div>';
}
}
}
?>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="top">
<form action="search3.php" method="post">
<input type="text" name="search" placeholder="Search here" />
<input type="submit" value=">>" />
</form>
</div>
<div id="top2">
<?php print("$output"); ?>
</div>
</body>
</html>
Edited. I tried to sanitize, it still don't work as planed.
function sanitize($data) {
return htmlentities(strip_tags(mysql_real_escape_string($data)));
}
$searchq = sanitize($_POST['search']);
That you are vulnerable to sql injection. You should use mysqli_ or pdo. For instance you can use mysql_real_escape_string() to avoid this [Though it is not recommended].
$searchq = mysql_real_escape_string($_POST['search']);
Edited: If you sanitize your input and it returns empty string (""), than your query will be :
SELECT * FROM users WHERE firstname LIKE '%%' OR lastname LIKE '%%'
Which will always prints out the whole database content. So check your input variable $searchq after sanitize. If it contains anything than you can perform your query like that:
if(strlen($searchq) > 0)
{
//run query
}
else{
//error message
}

HTML search box to pick up values in a table

Okay this is abit hard to explain but I currently have a website where I'm using PHP and MySQL to pull tables into the web pages and display them. I've been able to make a search function to look for specific values in the table. I'll show you my code.
<!DOCTYPE php>
<html>
<head>
<link rel="stylesheet" href="style.php" media="screen">
</head>
<body>
<a id="TableButton" href="/Test.php">Items Table</a>
<a id="Clear" href="index.php">Clear Search</a>
<center>
<form method="GET" id="SearchPerson">
<select name="Drop" id="Select">
<option value="FirstName">First Name</option>
<option value="Surname">Surname</option>
<option value="MobileNumber">Mobile Number</option>
<option value="Code">Code</option>
<option value="TeamGroup">Team Group</option>
<option value="Home">Home</option>
</select>
<input type="text" name="Box">
<input type="submit" value="Search">
</form>
</center>
<?php
$host = "localhost";
$user = "root";
$pass = "password";
$db = "Database";
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
if($_REQUEST['Drop']=='MobileNumber') {
$MobileNumber = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE MobileNumber = $MobileNumber";
}
elseif($_REQUEST['Drop']=='Code') {
$Code = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE Code = '$Code'";
}
elseif($_REQUEST['Drop']=='TeamGroup') {
$TeamGroup = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE TeamGroup = '$TeamGroup'";
}
elseif($_GET['Drop']=='FirstName') {
$FirstName = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE FirstName = '$FirstName'";
}
elseif($_GET['Drop']=='Surname') {
$Surname = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE Surname = '$Surname'";
}
elseif($_REQUEST['Drop']=='Home') {
$Home = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE Home = '$Home'";
}
else{
$query = "SELECT * FROM Person";
}
print "<center id=Title>Person Table</center>";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
print '<center><table><tr>';
foreach($row as $name => $value) {
print "<th>$name</th>";
}
print '</tr>';
while($row) {
print '<tr>';
foreach($row as $key=>$value) {
if($key=='MobileNumber'){print "<td><a href='/Test.php?MobileNumber=$value'>$value</a></td>";}
elseif($key=='TeamGroup'){print "<td><a href='/Test.php?TeamGroup=$value'>$value</a></td>";}
elseif($key=='Group'){print "<td><a href='/Test.php?Home=$value'>$value</a></td>";}
else{print "<td>$value</td>";}
}
print '</tr>';
$row = mysql_fetch_assoc($result);
}
print '</table></center>';
}
else {
echo "No People found!";
}
mysql_free_result($result);
mysql_close($connection);
?>
</body>
</html>
Problem is even though I've got the search working it only works if I have the full values whereas i want it so say that i put part of someone mobile number in then itll display the mobile numbers that have those parts of the value in it. For example say that a few people had a mobile number starting with 0783 and I type that into the search box I want it to show up all people with 0783 in their mobile number.
What you are looking for is "SELECT * FROM Person WHERE MobileNumber LIKE '%".$_POST['MobileNumber']."%'", which will look for any string that contains the string you want, but may also be longer on either side. For example, "foo" will return the rows with values "foobar", "barfoo", "barfoobar" and of course "foo", but not "fo".
The % is a wildcard here, which means that you can also do something like "SELECT * FROM Person WHERE MobileNumber LIKE '".$_POST['MobileNumber']."%'" if you specifically want to return rows with values starting with your string ("foobar", but not "barfoo" in our example above).
Please also note the " and '.
Also:
Don't use mysql_query. It's depreciated and will be removed in future versions of PHP. Use PDO or mysqli instead.
Your code is definitely not safe. At least use prepared statements to prevent injection. I would advise against using addslashes as it is very prone to resulting in double escapes if you are not paying attention, and as far as you may also want to go the magic_quotes, be aware it is not portable and may cause you trouble if you rely solely on this. Use mysql_real_escape_string instead, as it is very mysql-oriented and specific.

Why isn't this form returning results?

I have just started trying to learn PHP and MYSQL and have been following some tutorials for creating a webpage search engine, but have been experience an issue wherein when i submit the form the results aren't returned, i have no idea as to where the problem lies or where to try and troubleshoot it, so it thought it'll be worth a shot to post my problem here. Hopefully someone can help me out, thanks in advance.
PHP
<?php
mysql_connect("localhost","root","123")or die("Could not connect to Db");
mysql_select_db("members") or die("Could not find db");
if(isset($_POST['submit'])){
$searchq = $_POST['submit'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("Select * FROM memberlist WHERE Fname LIKE '%$searchq%' OR Lname LIKE '%$searchq%' ") or die(mysql_error());
$count = mysql_num_rows($query);
if($count == 0){
$output = "No results were found, sorry.";
}
else{
while($row = mysql_fetch_array($query)){
$firstname = $row['Fname'];
$lastname = $row['Lname'];
$output .= "<div>".$firstname." ".$firstname."</div>";
}
}
}
?>
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Search</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="searchfname" placeholder="Enter first name">
<input type="text" name="searchlname" placeholder="Enter last name">
<input type="submit" name="submit" value="Submit">
</form>
<?php print($output);?>
</body>
</html>
You can use $_POST['submit'] to check if the form was submitted, but it does not hold all the form values.
You can access the separate form values by their respective name.
So use $_POST['searchfname'] for the value in the first textbox and $_POST['searchlname'] for the second.
Your code should read more like this;
$searchqf = $_POST['searchfname'];
$searchql = $_POST['searchlname'];
$searchqfreplace = preg_replace("#[^0-9a-z]#i","",$searchqf);
$searchqlreplace = preg_replace("#[^0-9a-z]#i","",$searchql);
$query = mysql_query("Select * FROM memberlist WHERE Fname LIKE '%$searchqf%' OR Lname LIKE '%$searchql%' ") or die(mysql_error());
$count = mysql_num_rows($query);
Notice that this way of composing queries is very insecure and vulnerable for SQL injection.
You're also asking for a way to troubleshoot. You probably want to look into echo and print_r.
You have assigned the $searchq variable to your submit button.
Change this line
$searchq = $_POST['submit'];
to
$searchq = $_POST['searchfname'];
or
$searchq = $_POST['searchlname'];
or both:
$searchq = $_POST['searchfname'].$_POST['searchlname'];
you cannot use $searchq = $_POST['submit']; since no value is being posted whose name is submit
you must use any of the following....
$searchq = $_POST['searchfname'];
or
$searchq = $_POST['searchlname'];
In your code you are searching for 'submit' value instead of values from form.
Replace $searchq = $_POST['submit']; with:
$searchq = $_POST['searchfname'];
$searchq2 = $_POST['searchlname'];
and query:
Select * FROM memberlist WHERE Fname LIKE '%$searchq%' OR Lname LIKE '%$searchq2%'
Firstly,
either search with searchfname or with searchlname or both.
Secondly, modify like this
after $count = mysql_num_rows($query);,
if($count == 0){
$output = "No results were found, sorry.";
}
else{
$output = '';
while($row = mysql_fetch_array($query)){
$firstname = $row['Fname'];
$lastname = $row['Lname'];
$output .= "<div>".$firstname." ".$firstname."</div>";
}
Thirdly, Use print $output in the Second page(where database is fetched) and not in First page(Page with FORM).
If you want to show result in the First page, use jQuery/Ajax function

Form get's resent on refresh

Form get's resent on refresh, I had read about header("Location:my_page.php") unset($_POST), but I'm not sure where to place it.
This is our script, it works as need it, but it keeps re-sending on page refresh (Chrome browser alerts over and over), can some one fix the code and explain to my like 2 years old child.
<form action='thi_very_same_page.php' method='post'>
Search for Christian Movies <input type='text' name='query' id='text' />
<input type='submit' name='submit' id='search' value='Search' />
</form>
<?php
if (isset($_POST['submit']))
{
mysql_connect("localhost", "root", "toor") or die("Error connecting to database: " . mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$query = $_POST['query'];
$min_length = 2;
if (strlen($query) >= $min_length)
{
$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
echo "";
$result = mysql_query("SELECT *, DATE_FORMAT(lasteditdate, '%m-%d-%Y') AS lasteditdate FROM movies WHERE (`moviename` LIKE '%" . $query . "%') OR (`year` LIKE '%" . $query . "%')") or die(mysql_error());
if (mysql_num_rows($result) > 0)
{
while ($results = mysql_fetch_array($result))
{
echo "";
}
}
else
{
echo "";
}
}
else
{
echo "";
}
}
If you mean that the form data gets submitted again upon refresh, check this method
http://www.andypemberton.com/engineering/the-post-redirect-get-pattern/
You set your header to header('HTTP/1.1 303 See Other');
Data wont be cached, so when page refreshes the form data wont get submitted again!
The problem is you are using the post method to submit the form values so when ever you tries to refresh the browser asks you whether to send the form information or not it is the default behavior of the browser to tackle the posted information, the alternate solution for your problem is you can use the get method like in form attribute method='get' what it does it will append all the information of form in the URL which we call the query string and in PHP code you are accessing the form values in $_POST but when using get method the form values will now appear in the $_GET method these methods are called request method and are PHP's global variables, Now when you try to refresh it will not ask you to resend information because the information now resides in the URL
<form action='thi_very_same_page.php' method='get'>
Search for Christian Movies <input type='text' name='query' id='text' />
<input type='submit' name='submit' id='search' value='Search' />
</form>
<?php
if (isset($_GET['submit']))
{
mysql_connect("localhost", "root", "toor") or die("Error connecting to database: " . mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$query = $_GET['query'];
$min_length = 2;
if (strlen($query) >= $min_length)
{
$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
echo "";
$result = mysql_query("SELECT *, DATE_FORMAT(lasteditdate, '%m-%d-%Y') AS lasteditdate FROM movies WHERE (`moviename` LIKE '%" . $query . "%') OR (`year` LIKE '%" . $query . "%')") or die(mysql_error());
if (mysql_num_rows($result) > 0)
{
while ($results = mysql_fetch_array($result))
{
echo "";
}
}
else
{
echo "";
}
}
else
{
echo "";
}
} ?>
Hope this is enough to explain you about the form submission one thing I will suggest you to deeply look at below
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

PHP Foreach statement issue. Multiple rows are returned

I'm a PHP beginner and lately I've been having a problem with my source code.
Here it is:
<html>
<head>
<title>
Bot
</title>
<link type="text/css" rel="stylesheet" href="main.css" />
</head>
<body>
<form action="bot.php "method="post">
<lable>You:<input type="text" name="intrebare"></lable>
<input type="submit" name="introdu" value="Send">
</form>
</body>
</html>
<?php
//error_reporting(E_ALL & ~E_NOTICE);
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("robo") or die(mysql_error());
$intrebare=$_POST['intrebare'];
$query = "SELECT * FROM dialog where intrebare like '%$intrebare%'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
?>
<div id="history">
<?php
foreach($row as $rows){
echo "<b>The robot says: </b><br />";
echo $row['raspuns'];
}
?>
</div>
It returns the result 6x times.
This problem appeared when I've made that foreach because I wanted the results to stuck on the page one by one after every SQL query.
Can you please tell me what seems to be the problem? Thanks!
You are doing it wrong. ;-)
First of all you have to fetch your result with mysql_fetch_array in a loop like this:
while (true == ($row = mysql_fetch_array($result))) {
echo "<b>The robot says: </b><br />";
echo $row['raspuns'];
}
Second I want to tell you that all mysql_* functions are marked as deprecated. If you want to learn PHP you should try to learn how to connect to mysql using PDO.
mysql_fetch_array fetches one row per call. You'll want to do like this:
while ($row = mysql_fetch_array($result)) {
echo "<b>The robot says:</b><br>";
echo htmlentities($row['raspuns']);
}
and get rid of that first mysql_fetch_array.
(Notice that i am HTML-escaping the variable output. Unless you know what you're doing, you should not output raw data into a page.)
By the way, mysql_query is effectively deprecated. It is not at all recommended for new code. Take a look at mysqli (the replacement) or PDO (the new hotness). With the new mysqli (objecty) interface, the PHP part would look a bit like this:
<?php
//error_reporting(E_ALL & ~E_NOTICE);
$db = new mysqli('localhost', 'root', '', 'robo');
# turn into a wildcard
$intrebare='%' . $_POST['intrebare'] . '%';
$stmt = $db->prepare('SELECT * FROM dialog WHERE intrebare LIKE ?');
$stmt->bind_param('s', $intrebare);
$result = $stmt->execute();
echo '<div id="history">';
# 5.4 lets you do it like this;
# older versions, try `while ($row = $result->fetch_assoc())`
foreach ($result as $row) {
echo "<b>The robot says: </b><br />";
echo htmlentities($row['raspuns']);
}
?>
You're only getting one result (only one call to mysql_fetch_array()). There are six columns, I bet, in dialog.
...
$result = mysql_query($query) or die(mysql_error());
?>
<div id="history">
<?php
while($row = mysql_fetch_array($result))
{
echo "<b>The robot says: </b><br />";
echo htmlentities($row['raspuns']);
}
?>
</div>
Also, mysql_* functions are being deprecated. Switch to mysqli_* or PDO.
Use while to fetch all the data and check variable names
while($row = mysql_fetch_array($result)){
echo "<b>The robot says: </b><br />";
echo $row['raspuns']; // Here
}
You are trying it reversed way:
<?php
while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
echo '<strong>The robot says: </strong><br />', $row['raspuns'];
}
?>
Try now :)

Categories