PHP MySQL search & show row by html <input> - php

I have an HTML form like:
<form action = "get-row.php" method = "post" >
<input type = "text" name = "mess_username" />
<input type = "submit" name = "submit" />
</form>
And my "get-row.php" is like :
$button = $_POST ['submit'];
$search = $_POST ['mess_username'];
if (!$button) {
echo "you didn't submit a keyword";
}
else {
if (strlen($search) <= 1) {
echo "Search term too short";
}
else {
echo "You searched for <b> $search </b> <hr size='1' >";
}
}
I am now successfully getting the value I have searched for. My next approach is to search the $search from my Database. I am trying like:
mysql_connect("server", "user", "pass");
mysql_select_db("my_db");
My Final "ok" Code after currection :
$sql = " SELECT * FROM messbd WHERE mess_username= '$search' ";
$run = mysql_query($sql);
$foundnum = mysql_num_rows($run);
if ($foundnum == 0) {
echo "Sorry, there are no matching result for <b> $search </b>";
}
else {
echo "$foundnum results found !<p>";
while ($runrows = mysql_fetch_assoc($run)) {
$mess_username = $runrows ['mess_username'];
$mess_email = $runrows ['mess_email'];
$android_app = $runrows ['android_app'];
echo " $mess_username <br> $mess_email <br> $android_app ";
}
}
The problem is, I am getting the message that, "There are no matching results!" So what will be the correction there?
The problem is solved now & The code is updated above. Thanks.

You missed to quote your search term
$sql = 'SELECT * FROM messbd WHERE mess_username="' . mysql_real_escape_string($search) . '"';
But the mysql extension is deprecated and should be replaced by either PDO or mysqli. Here is an example with PDO and prepared statement:
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$dbh = new PDO('mysql:host=server;dbname=my_db', 'user', 'pass', $options);
$sql = 'SELECT * FROM messbd WHERE mess_username=?';
$sth = $pdo->prepare($sql);
$sth->execute(array($search));
// there is no sure working rowCount, so fetch all and count
$rows = $sth->fetchAll(PDO::FETCH_ASSOC)
if (!$rows) {
echo "Sorry, there are no matching result for <b> $search </b>";
} else {
echo count($rows) . " results found !<p>";
foreach ($rows as $row) {
$mess_username = $row['mess_username'];
$mess_email = $row['mess_email'];
$android_app = $row['android_app'];
echo "$mess_username<br>$mess_email<br>$android_app";
}
}

Since your $search results will be a string, then you need to quote that variable in your query. I'm pretty sure that you're looking for a string in your database, seeing echo "you didn't submit a keyword"; and mess_username being a user's "name".
WHERE mess_username='$search' ";
assuming an exact match. If you're looking for something that resembles your search, say you're looking for "foot" and want to find "football", then use LIKE.
http://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html
Also add or die(mysql_error()) to mysql_query() just in case there may be errors, and it seems that there would be, when not quoting a string in a query's variable.
Footnotes:
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
Plus, it's best to use a conditional empty() against your input.
I.e.:
if(!empty($_POST[ 'mess_username' ])){
...
}
should someone just click without entering anything, which could throw you an error.

With this query mysql will search for $search input insted for the relarive value of the var. Try to use single quotes.

Related

How to disable % from outputting everything

Hey I have an search field where I am searching something from my database, now I saw the problem after testing that if I put "%" in the search field it will output everything that I have ready for searching. Is there a way to disable this?
<h3>Search Share Details</h3>
<p>You may search either by company name or issue date</p>
<form name = "search" method = "get">
<input type = "text" name = "share" size = "40" maxlength="50">
<input type = "submit" value = "Search">
</form>
Getting contents connecting to DB, fetching results and printing
function get_contents() {
if(isset($_GET['share']))
{
$conn = db_connect();
$shares = get_shareSearch($conn);
db_disconnect($conn);
$contents = array('shares' => $shares);
return $contents;
}
else
{
$conn = db_connect();
$shares = get_share($conn);
db_disconnect($conn);
$contents = array('shares' => $shares);
return $contents;
}
}
function print_contents($contents)
{
if(count($contents['shares']) == 0)
{
echo "<script type = 'text/javascript'>alert('Sorry but share is not found! Q_Q');</script>";
}
else
{
?>
<table>
<tr>
<th>Company Name</th>
<th>Rate</th>
<th>Issue Date</th>
</tr>
<?php
foreach ($contents['shares'] as $share)
{
print "<tr>";
$identifier = urlencode($share['SHAREID']);
print "<td><a href='share-details.php?id={$identifier}'>{$share['COMPANY']}</a></td>";
print "<td>{$share['RATE']}</td>";
$issue_date = $share['ISSUE_DATE'];
$issue_date = $issue_date === NULL ? "< not available >" : $issue_date;
print "<td>{$issue_date}</td>";
print "</tr>";
}
?>
</table>
<?php
}
}
//require("shares.php");
require("search.php");
?>
Query itself
function get_shareSearch($conn) {
$id = "";
if(isset($_GET['share'])){$id = $_GET['share'];}
$statement = db_create_statement($conn, "SELECT DISTINCT * FROM shares WHERE(company LIKE '{$id}' OR issue_date LIKE '{$id}')");
$resultset = db_fetch_resultset($statement);
return $resultset;
}
Escape it
This refers to putting a character in front of it to denote it's meant to be taken literally:
Original Statement
SELECT * FROM ikeaTable WHERE chair LIKE '5% off';
Escaped Version
SELECT * FROM ikeaTable WHERE chair LIKE '5\% off' ESCAPE '\';
YOURS
SELECT DISTINCT * FROM shares WHERE(company LIKE '\%{$id}' OR issue_date LIKE '\%{$id}') ESCAPE '\'
I don't know which Database library you are using, but you certainly need to escape the parameters that you include into the query. If not escaped, MySQL will understand % as a special character that basically means 'match anything'.
I would suggest you read the database library documentation (or the code) to see how to include query parameters into your statement or how to escape them directly.

Search a keyword in Mysql table with or without a space

I search for a keyword that fits the search query. And The info gets echoed out. It is like a search engine.
But I can't seem to get it to work for keywords in the database with spaces.
I have searched around a bit but can't seem to get it working.
<?php
// -- Database Connection --
if (isset($_POST['search_query'])) {
$search_query = mysql_real_escape_string(htmlentities($_POST['search_query']));
echo "<div class=\"searchText\">Search</div><hr />";
//explode the search term
$search_query_x = explode(" ",$search_query);
foreach($search_query_x as $search_each) {
$x++;
if($x==1)
$construct .="keywords = '$search_each'";
}
$construct ="SELECT * FROM search WHERE $construct";
$run = mysql_query($construct);
$foundnum = mysql_num_rows($run);
if ($foundnum==0) {
echo "Sorry, there are no matching result for <b>$search_query</b>.</br></br>1.
Try more general words.</br>2. Try different words with similar
meaning</br>3. Please check your spelling";
} else
{
echo "$foundnum results found !<p>";
while($runrows = mysql_fetch_assoc($run))
{
$title = $runrows ['title'];
$desc = $runrows ['description'];
$url = $runrows ['url'];
echo "
<div class='width: 400px;'>
<div class='title'><a href='$url'><b>$title</b></a></div>
<div class='url'>$url</div>
<div class='desc'>$desc</div>
</div>
<br />
";
}
}
}
else
{
echo "An ERROR HAS OCCURED ...";
}
?>
In $search_query_x = explode(" ",$search_query); your blankspaces get removed due to the splitting by blankspaces.
You have to chose a new delimiter for the data to seperate - like a comma instead of a blankspace.
$search_query = mysql_real_escape_string(htmlentities($_POST['search_query']));
causes your script to change spaces into URL compatible %20. Get rid of htmlentities function (which doesn't really improve security at this point) and it should be working just fine.
Htmlentities function should be used when presenting information coming from insecure sources.
Be sure to call (preferred) htmlspecialchars or htmlentities when showing the info back to the user to prevent Cross Site Scripting (XSS).
Also it has been noted in the comments that you are using obsolete functions.

MySQL retrieval from database not retrieving multiple rows

I'm trying to retrieve all data with the LIKE query from the users input and match it to the database, it works but only returns one record but I have many records in the table.
It returns the closest record it can find,
so say for example I have 2 records who's ItemDesc field contains the characters 'The', when I search for 'The' in my input box and click submit it returns the closest (earliest created) record when it is supposed to return both.
<?php
$username = "a3355896_guy";
$password = "++++++";
$hostname = "mysql5.000webhost.com";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db("a3355896_book") or die("Unable to connect to database");
$ItemDesc = $_POST['ItemDesc'];
$query = "select * from StockItems where ItemDesc LIKE '%$ItemDesc%'";
$result=mysql_query($query);
$num=mysql_num_rows($result);
mysql_close();
?>
Sorry was supposed to included the retrieval:
<?php
if ($num>0)
{
echo "<center><table border=1><tr><th>Item Code</th><th>Item Desc</th>";
echo "<th>Item Stock Qty</th>";
echo "<th>Item Unit Price</th><th>Item Category</th></tr>";
$ItemCode = mysql_result($result,$i,"ItemCode");
$ItemDesc = mysql_result($result,$i,"ItemDesc");
$ItemStockQty = mysql_result($result,$i,"ItemStockQty");
$ItemUnitPrice = mysql_result($result,$i,"ItemUnitPrice");
$ItemCategory = mysql_result($result,$i,"ItemCategory");
echo "<tr><td>$ItemCode</td><td>$ItemDesc</td><td align=right>";
echo "$ItemStockQty</td>";
echo "<td align=right>$ItemUnitPrice</td>";
echo "<td>$ItemCategory</td></tr>";
echo "</table></center>";
}
else
{
echo "<form name='DeleteStock2'>";
echo "<p> Sorry, $ItemDesc does not exist!<p>";
echo "<input type='button' value='Leave' onclick='history.go(-1)'>";
}
?>
You aren't actually accessing your data here- you need to iterate over the result set.
$setLength = mysql_num_rows($result);
for($i = 0; $i < $setLength; $i++){
//Here, mysql_fetch_assoc automatically grabs the next result row on each iteration
$row = mysql_fetch_assoc($result);
//do stuff with "row"
}
Unless you ARE doing that and you just chose to not include it in your snippit. Let us know :)
--Edit--
First off, I apologize- out of old habit I suggested that you use mysql_fetch_assoc instead of the mysqli set of functions.
Try using the fetch_assoc or fetch_array functions, it could solve your issue. I've never used the method you used, I think it has been deprecated for a while.
Check it out here:
http://php.net/manual/en/mysqli-result.fetch-assoc.php

Simple logon script

I'm trying to do a simple logon script. That is, accept form content through a POST action. Check the database for a matching record. Pull other information from that row such as Full Name.
The code I have is;
if ( !isset($_POST['loginsubmit']) ) {
//Show login form
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<p>
Account ID:
<input name="AccountID" type="text" />
</p>
<p>
Username:
<input name="userEmail" type="text" />
</p>
<p>Password:
<input name="userPassword" type="password" />
<p>
<input name="loginsubmit" type="submit" value="Submit" />
</p>
</form>
<?php
}
else {
//Form has been submitted, check for logon details
$sql = "SELECT * FROM users WHERE 'accountID'=". $_POST['AccountID']. " AND 'userEmail'=". $_POST['userEmail'] . " AND 'userPassword'=". $_POST['userPassword']. " LIMIT 1";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if ($count == 1){
echo"Correct Username/Password";
}
else {
echo "Wrong Username or Password";
}
}
I have two issues. Firstly with the above code, I keep getting the following error.
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in ...
Second, how do I get the other details fields out of the databse. I presume
$result=mysql_query($sql);
contains an array for the MySQL row, so could I do something like;
echo $result['fullName'];
First sanitize the fields to prevent SQL injection.
$sanitize_fields = array('AccountID','userEmail','userPassword');
foreach( $sanitize_fields as $k => $v )
{
if( isset( $_POST[ $v ] ) )
$_POST[ $v ] = mysql_real_escape_string( $_POST[ $v ] );
}
Then quote the string fields in your query. Initially there was an error in your query. That's why you were getting a boolean value of false.
$sql = "SELECT * FROM users WHERE accountID='". $_POST['AccountID']. "' AND userEmail='". $_POST['userEmail'] . "' AND userPassword='". $_POST['userPassword']. "' LIMIT 1";
I suggest you do the following after running the query to see the error generated by MySQL, if there is one.
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
The MySQL extension is being phased out and there are newer better extensions such as MySQLi and PDO, have a look at those.
In your SQL statement:
$sql = "SELECT * FROM users WHERE 'accountID'=". $_POST['AccountID']. " AND 'userEmail'=". $_POST['userEmail'] . " AND 'userPassword'=". $_POST['userPassword']. " LIMIT 1";
if in the table, the userEmail and userPassword are strings, please add single qoutes:
$sql = "SELECT * FROM users WHERE accountID=". $_POST['AccountID']. " AND userEmail='". $_POST['userEmail'] . "' AND userPassword='". $_POST['userPassword']. "' LIMIT 1";
To get the results:
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
if(mysql_num_rows($result) > 0)
echo $row['COLUMN_NAME'];
}
}
Your codes are very insecure:
Please use MySQLi or PDO to interact with the database
Escape all input data before sending to the database
Try this:
else {
//Form has been submitted, check for logon details
$conn = mysql_connect("db-host-here","db-user-here","db-pass-here");
$sql = "SELECT * FROM users WHERE accountID=". mysql_real_escape_string($_POST['AccountID']). " AND userEmail='". $_POST['userEmail']=mysql_real_escape_string($_POST['userEmail']); . "' AND userPassword='". $_POST['userPassword']=mysql_real_escape_string($_POST['userPassword']);. "' LIMIT 1";
$result = mysql_query($sql,$conn);
$count = mysql_num_rows($result);
if($count == 1){
echo"Correct Username/Password";
}
else {
echo "Wrong Username or Password";
}
}
// Get other information:
$dbInfo = mysql_fetch_assoc(); //If more than one row can be selected, use a while loop.
//Now play with $dbInfo:
echo $dbInfo['some_other_column'];
You have single quotes in your query where you don't need them, and you're missing them where you do. Try the code above.
Replace db-host-here,db-user-here and db-password-here with the correct database information.
I have done some escaping in your code, to prevent injection attacks. But you should really look into using prepared statements.
The problem here is that Your query fails to select any row therefore a boolean FALSE is returned from mysql_query call.
You should repair Your query and always check if the $result = mysql_query($query); returns false or not, like so:
// ...
$result = mysql_query($query);
if($result !== false) {
$count = mysql_num_rows($result);
// ...
}
But I recommend using PDO or at least mysqli http://php.net/mysqli.

Searching MySQL with PHP

I am doing a project where I want a person to enter the name of any artist/band into a text box where it will seach my mysql database for the event information and display the results/content on another page. The code below is within my index.php where it should get the information from search.php (below also). I've looked all over and I'm not sure why it's not working and I can't figure out what to do. Help would be great! (I really need to pass this class!) :)
(index.php)
<form name="search" action="search.php" method="get">
<div align="center"><input type="text" name="q" />
<p><input type="submit" name="Submit" value="Search" /></p>
</form>
(search.php)
<?php
//Get the search variable from URL
$var=#&_GET['q'];
$trimmed=trim($var); //trim whitespace from the stored variable
//rows to return
$limit=10;
//check for an empty string and display a message.
if($trimmed=="")
{
echo"<p>Please enter a name.</p>";
exit;
}
//check for a search parameter
if(!isset($var))
{
echo"<p>We don't seem to have a search parameter!</p>";
exit;
}
//connect to database
mysql_connect("localhost","root","password");
//specify database
mysql_select_db("itour") or die("Unable to select database");
//Build SQL Query
$query = "select * from events where artist_name like \"%trimmed%\" order by date";
$numresults=mysql_query($query);
$numrows=mysql_num_rows(numresults);
//If no results, offer a google search as an alternative
if ($numrows==0)
{
echo"<h3>Results</h3>";
echo"<p>Sorry, your search: "" .$trimmed . "" returned zero results</p>";
//google
echo"<p><a href=\"http://www.google.com/search?q=".$trimmed . "\" target=\"_blank\" title=\"Look up ".$trimmed ." on Google\">
Click here</a> to try the search on google</p>";
}
//next determine if s has been passed to script, if not use 0
if(empty($s)) {
$s=0;
}
//get results
$query .=" limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
//display what was searched for
echo"<p>You searched for: "" .$var . ""</p>";
//begin to show results set
echo "Results";
$count = 1 + $s;
//able to display the results returned
while ($row=mysql_fetch_array($result)) {
$title = $row["artist_name"];
echo"$count.) $title";
$count++;
}
$currPage = (($s/$limit) + 1;
echo"<br />";
//links to other results
if ($s>=1){
//bypass PREV link if s is 0
$prevs=($s-$limit);
print" <a href=\"$PHP_SELF?s=$prevs&q=$var\"><<
Prev 10</a> ";
}
//calculate number of pages needing links
$pages = intval($numrows/$limit);
//$pages now contains int of pages needed unless there is a remainder from diviison
if($numrows%$limit){
//has remainder so add one page
$pages++;
}
//check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1){
//not last page so give NEXT link
$news = $s+$limit;
echo " Next 10 >>";
}
$a = $s +($limit);
if($a > $numrows){$a = $numrows;}
$b = $s + 1;
echo "<p>Showing results $b to $a of $numrows</p>";
?>
Your where clause is goofy...try changing it to:
WHERE artist_name like '%$trimmed%'
just putting trimmed will be interpreted literally as the string "trimmed". However, using the variable $trimmed in your double-quoted string will give the actual variable's value.
$query = "select * from events where artist_name like '%$trimmed%' order by date";
In order to use the variable $trimmed in a query, escape it first. Otherwise, your script will be vulnerable to SQL injection attacks, and attackers will be able to run almost any query against your database. This problem is exacerbated by the fact that you are connecting to MySQL as root. Never ever do this in a production environment.
Also, to expand a variable in a string, you should include the $ character before the variable name.
$trimmed = trim($var);
$escaped = mysql_real_escape_string($trimmed);
$query = "select * from events where artist_name like \"%$escaped%\" order by date";
Your code still looks all over the place. I think the main reason it wasn't working was the mixing of " and '. You need to escape variables before you use them in your queue. mysql_real_escape_string is the lowest form of escaping you should be using. I'd recommend you have a look at PDO though.
<?php
//Get the search variable from URL
$var = $_GET['q'];
$trimmed = mysql_real_escape_string(trim($var)); //trim whitespace and escape the stored variable
//rows to return
$limit = 10;
//check for an empty string and display a message.
if($trimmed == "") {
echo"<p>Please enter a name.</p>";
exit;
}
//check for a search parameter
if(!isset($var)){
echo"<p>We don't seem to have a search parameter!</p>";
exit;
}
//connect to database
mysql_connect("localhost","root","password");
//specify database
mysql_select_db("itour") or die("Unable to select database");
//Build SQL Query
$query = "SELECT * FROM events WHERE artist_name LIKE %$trimmed% ORDER BY DATE";
$numresults = mysql_query($query);
$numrows = mysql_num_rows(numresults);
//If no results, offer a google search as an alternative
if ($numrows==0){
echo"<h3>Results</h3>";
echo"<p>Sorry, your search: "" .$trimmed . "" returned zero results</p>";
//google
echo"<p><a href=\"http://www.google.com/search?q=".$trimmed . "\" target=\"_blank"\ title=\"Look up ".$trimmed ." on Google\">
Click here</a> to try the search on google</p>";
}
//next determine if s has been passed to script, if not use 0
if(empty($s)) {
$s=0;
}
//get results
$query .=" limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
//display what was searched for
echo"<p>You searched for: "" .$var . ""</p>";
//begin to show results set
echo "Results";
$count = 1 + $s;
//able to display the results returned
while ($row = mysql_fetch_array($result)) {
$title = $row['artist_name'];
echo $count.' '.$title;
$count++;
}
$currPage = (($s/$limit) + 1;
echo "<br>";
//links to other results
if ($s>=1){
//bypass PREV link if s is 0
$prevs=($s-$limit);
echo ' <a href="'.$PHP_SELF.'?s='.$prevs.'&q='.$var.'"><&lt';
echo 'Prev 10</a> ';
}
//calculate number of pages needing links
$pages = intval($numrows/$limit);
//$pages now contains int of pages needed unless there is a remainder from diviison
if($numrows%$limit){
//has remainder so add one page
$pages++;
}
//check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1){
//not last page so give NEXT link
$news=$s+$limit;
echo ' Next 10 >>';
}
$a = $s +($limit);
if($a > $numrows){$a = $numrows;}
$b = $s + 1;
echo '<p>Showing results '.$b.' to '.$a.' of '.$numrows.'</p>';
?>
You are missing a $ symbol. I think
$var=#&_GET['q'];
should probably be
$var=#$_GET['q'];
unless you really want a reference, in which case it should be this: (the error suppression is not needed at this point if you want a reference, but you should check $var is set before trying to access it)
$var=& $_GET['q'];
I would be tempted to write it a bit more like this.
if (!isset($_GET['q'])) {
echo"<p>We don't seem to have a search parameter!</p>";
exit;
}
$trimmed = trim($_GET['q']);
if($trimmed=="") {
echo"<p>Please enter a name.</p>";
exit;
}
Also as Chad mentioned, an sql injection would be simple since you arent cleaning input before performing DB actions with it.
try adding
foreach($_REQUEST as $param => $value)
{
$_REQUEST[$param]=mysql_real_escape_string($value);
}
This way you escape all the user input so the user cant tamper with the db. Read more about this method and sql injection in the docs here:
http://us2.php.net/mysql_real_escape_string

Categories