Can not search in the database [duplicate] - php

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
Can anyone help me?
I trying to create a very basic search function for my website, but i have an error, and i can not search from my database, the error like in the image that i attached with.
It's ok when i enter the wrong name that is not exist on the database, but when i enter the name that is exist it will show the error like in the image, can anyone help me?
This is my php code:
<?php
require_once("../../include/admin/ad_ovhead.php");
require_once("../../lib/connection.php");
$output = '';
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
$sql = "SELECT * FROM users WHERE firstname LIKE '%$searchq%' OR lastname LIKE '%$searchq%'";
$query= mysqli_query($conn, $sql) or die ("Can not search");
$count = mysqli_num_rows($query);
if($count == 0){
$output= 'There are no search results!';
}else{
while ($row = mysql_fetch_array($query)) {
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$id = $row['id'];
$output .= '<div> '.$firstname.' '.$lastname.' </div>';
}
}
}
?>

Use mysqli_num_rows() instead of mysql_num_rows()
$count = mysqli_num_rows($query);

Related

Die if Data Not Exisits in php mysql table [duplicate]

This question already has answers here:
PHP mysql_num_rows die error
(3 answers)
Closed 5 years ago.
I'm getting an error message when the data is not available in data base table. I would like to stop the qry search without getting an error when the data is not available.
It works good if the data is available in table but not works while the data is not available. For an example, when i search this city name in my table the requested city's data's are not available in that table. During this time i'm getting an "Undefined variable" error.
<?php
$city = 'chennai';
$cityQry ="SELECT * FROM area_data WHERE city ='$city' LIMIT 1";
$cityQryResult = mysql_query($cityQry);
while($row = mysql_fetch_array($cityQryResult)) {
$citypop = $row['population'];
}
?>
Check if mysql_num_rows gives you count more than 0, If count is 0 call die()
$city = 'chennai';
$cityQry ="SELECT * FROM area_data WHERE city ='$city' LIMIT 1";
$cityQryResult = mysql_query($cityQry);
if(mysql_num_rows($cityQryResult) == 0)
{
die("No Data Exists");
} else {
while($row = mysql_fetch_array($cityQryResult)) {
$citypop = $row['population'];
}
}
Please try Below Code (Not Tested Yet) :
<?php
$city = 'chennai';
$cityQry ="SELECT * FROM area_data WHERE city ='$city'";
$result = mysqli_query($cityQry);
// Mysql_num_row is counting table row
$count = mysqli_num_rows($result);
if($count > 0)
{
$cityQryResult = mysql_query($cityQry);
while($row = mysql_fetch_array($cityQryResult)) {
$citypop = $row['population'];
}
} else {
echo "No Data Exists";
}
?>

How do I add a No Results Found Message [duplicate]

This question already has answers here:
Check if a row exists using old mysql_* API
(6 answers)
Closed 6 years ago.
Trying to display a message, when there are no results found.
<?php
mysql_connect ("localhost", "root","") or die (mysql_error());
mysql_select_db ("test");
$term = $_POST['term'];
$sql = mysql_query("select * from testable where FName like '%$term%' or LName like '%$term%' or ID like '%$term%' ");
while ($row = mysql_fetch_array($sql)) {
echo '<br/>First Name:'.$row['FName'];
echo '<br/>Last Name:'.$row['LName'];
echo '<br/>Phone:'.$row['Phone'];
echo '<br/><br/>';
}
?>
Try this :
if(mysql_num_rows($sql) == 0)
{
echo 'No results';
}
else
{
while($row = mysql_fetch_array($sql))
{
//..
}
}
You can use mysql_num_rows() function, Which return the number of returned rows.
if( mysql_num_rows($sql) == 0) exit('No records found!');
passing the above condition meaning that there are some result, So you can loop through:
while ($row = mysql_fetch_array($sql)) {
// print whatever you want.
}

Advanced Search Form PHP

I have made a very basic search form which fetches name of users from database. It has two problems whenever I hit enter on empty search box it display the whole database instead of showing a error message or just doing nothing like google search box. secondly, i want the search results to appear in dropdown first then a button for whenever a user wants more search results.
Please help in making these changes. any help will be definitely appreciated.
<h2>Users:</h2><br>
<?php
$username="";
$output = '';
if (isset($_POST['search'])){
$search_query = $_POST['search'];
$search_q = $_POST['search'];
$search_query = preg_replace("#[^0-9a-z]#i","", $search_query);
$search_q = preg_replace("#[^0-9a-z]#i","", $search_q);
$query = mysql_query("SELECT * FROM users WHERE username LIKE '%$search_query%' OR last_name LIKE '%$search_query%'") or die ("Could not search");
$count = mysql_num_rows($query);
if($count == 0 ||) {
$output = 'No Results Found.';
}
else{
while($row = mysql_fetch_array($query)){
$fname = $row['first_name'];
$lname = $row['last_name'];
$id = $row['id'];
$output .= "<div><a href='profile.php?u=$row[username]'>$fname $lname</a></div>";
}
}
}
?>
<?php echo("$output");?>
<form method="post" action="search.php" id="search">
<input type="text" name="search" placeholder="Search..">
You should be aware of the fact that mysql_query(), mysql_num_rows(), and mysql_fetch_array() are all deprecated in PHP 5.5.0 and removed in PHP 7.0.0. And $_POST['search'] is not filtering out potential SQL injections and other malicious code.
Anyway, you should check to see if the search string is empty before checking the database:
if (empty($POST['search'])) {
// do nothing or give error response
}
If you want to limit to 10 results:
"SELECT * FROM users WHERE username LIKE '%$search_query%' OR last_name LIKE '%$search_query%' LIMIT 10"

PHP MYSQL search always brings back 0 results

Hello Im trying to write a search function in php, but I always get 0 results found.
<?php
$mysqli = new mysqli('localhost', 'root', 'testing123', 'test')
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//collect
$output = '';
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($mysqli, "SELECT * FROM Users WHERE UsernameLIKE '%$searchq%'");
$count = mysqli_num_rows($query);
// if the $result contains at least one row
if ($query->num_rows > 0) {
// output data of each row from $result
while($row = $query->fetch_assoc()) {
}
}
else {
echo '0 results';
}
}
?>
Any ideas how to fix?
EDIT 1. This still does not allow it to be worked out with even this commented out.
if(!empty($_POST['search'])){
$searchq = $_POST['search'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($mysqli, "SELECT * FROM Users WHERE Username LIKE '$searchq%'");
$count = mysqli_num_rows($query);
// if the $result contains at least one row
if ($query->num_rows > 0) {
// output data of each row from $result
while($row = $query->fetch_assoc()) {
}
}
else {
echo '0 results';
}
}
In order to match School, School Name, or School Name 1
Your query needs to read as and removing the starting % and just keeping the trailing %
WHERE SchoolName LIKE '$searchq%'"
Now, the reason why it's not finding School Name and School Name 1 is because it contains spaces and your regex is replacing those spaces by nothing.
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
Either comment that line out or modify the regex.
By commenting it out, you can revert back to using:
WHERE SchoolName LIKE '%$searchq%'"

Checking If MySQL Rows Returned>10 and if so running some code, if not running a different piece of code

I have the code below which is supposed to check the database for entries with a certain username which is working but when I try to add some code to check if the rows returned is greater than 10 and then run some code to limit the number of rows to 10 and then if not run another piece of code which will display all the rows.
Code:
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$checkres = mysql_query("SELECT COUNT link, notes, titles, color FROM links WHERE username='" . $username . "';");
if ($checkres>10)
{
$resultsmall = mysql_query("SELECT link, notes, titles, color FROM links WHERE username='" . $username . "' LIMIT 10;");
while ($rowsmall = mysql_fetch_array($resultsmall)) { //loop
extract($rowsmall);
$htmlsmall .= "
//code goes here to format results
";
echo $htmlsmall; //display results...
}
}
else {
$result = mysql_query("SELECT link, notes, titles, color FROM links WHERE username='" . $username . "';");
while ($row = mysql_fetch_array($result)) { //loop
extract($row);
$html .= "
//code goes here to format results
";
echo $html; //display results...
}
}
mysql_close($con); //close db..
But it just displays two times the number of rows in the database instead of either limiting it or displaying them all. How would I fix this? The //code goes here for formatting isn't important it just formats the code so that it looks nice and displays it in a box...
Thanks!
EDIT:
I now have this code but it now doesn't display anything at all? Can someone help:
Code:
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$sql = "SELECT SQL_CALC_FOUND_ROWS link, notes, titles, color FROM links WHERE username='" . $username . "' LIMIT 10";
$result = mysql_query($sql) or die("MySQL error: " . mysql_error());
$subsql = "SELECT found_rows() AS foundrows;";
$subresult = mysql_query($subsql) or die("MySQL error: " . mysql_error());
$found_rows = $subresult['foundrows'];
if($found_rows > 10)
{
while($row = mysql_fetch_array($result))
{
extract ($row);
$html .= "
//getting values from columns and then formatting them goes here
";
echo "Only 10 is allowed.";
}
}
else
{
while($row = mysql_fetch_array($result))
{
extract($row);
$html .= "
//getting values from columns and then formatting them goes here
";
}
}
mysql_close($con); //close db..
Thanks!
EDIT 2 (12 April 14:03 2011 GMT):
I now have this code which has been kindly helped by Col. Shrapnel but it doesn't display anything for me and I don't know why, please could some help.
Code:
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$sql = "SELECT link, notes, titles, color FROM links WHERE username='$username' LIMIT 10";
$res = mysql_query($sql);
if (mysql_num_rows() == 10) {
while ($row = mysql_fetch_array($res)) {
extract($row);
$htmlsmall .= "
=
";
$htmlfree .= "Only 10 is allowed.";
echo $htmlsmall;
echo $htmlfree;
}
}
else {
while ($row = mysql_fetch_array($res)) {
extract($rowsmall);
$htmlsmall .= "
";
echo $htmlsmall;
}
}
Now if I view the page source I can see these 2 errors:
<b>Warning</b>: Wrong parameter count for mysql_num_rows() in <b>//url was here</b> on line <b>109</b><br />
<b>Warning</b>: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in <b>//url to file goes here</b> on line <b>125</b><br />
Line 109 is this: if (mysql_num_rows() == 10) {
Line 125 is this: while ($row = mysql_fetch_array($res)) {
(Those lines are in the code above)
Please could someone help me with this?
Thanks!
mysql_query() returns either a result statement handle, or boolean FALSE if the query failed. Your outer query is invalid:
SELECT COUNT ...
does not work, so the query fails, returns false, which jumps to the lower "unlimited" query.
However, you're going about the process of limiting things in a roundabout fashion that forces the query to run at least twice.
What you want is
$sql = "SELECT SQL_CALC_FOUND_ROWS link, notes, etc.... LIMIT 10";
$result = mysql_query($sql) or die("MySQL error: " . mysql_error());
$subsql = "SELECT found_rows() AS foundrows;";
$subresult = mysql_query($subsql) or die("MySQL error: " . mysql_error());
$found_rows = $subresult['foundrows'];
if ($found_rows > 10) {
... there's more than 10 rows available, though we're fetching only 10 because of the LIMIT
} else {
... 10 rows or less
}
The SQL_CALC_FOUND_ROWS is a MySQL extension that forces MySQL to calculate how many rows would have been fetched, if the LIMIT clause had not been present. You can get the results of this calculation with the found_rows() query function.
This way, you only run the main query once, do the very very quick found_rows() query, and off you go.
Given that you don't seem to be formatting your output any differently between the "more than 10" and "10 or less" version, except for the "only 10 allowed" line, how about this:
$sql = "...";
$result = mysql_query($sql) or die(mysql_error());
$rowcount = 0;
while ($row = mysql_fetch_assoc($result)) {
$rowcount++;
... output a row ...
if ($rowcount > 10) {
echo "Only 10 allowed";
break;
}
}
There's no need for duplicated code, excess logic, etc... when something simple will do.
I try to add some code to check if the rows returned is greater than 10 and then run some code to limit the number of rows to 10
It makes no sense.
Just run your query with LIMIT 10 and you will get your data.
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$sql = "SELECT * FROM links WHERE username='$username' LIMIT 10";
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
while ($row = mysql_fetch_array($res)) {
extract($rowsmall);
$htmlsmall .= ""; //code goes here to format results
}
echo $htmlsmall;
That's all.
If you still want to echo "Only 10 is allowed." (dunno why though) you can add these 3 lines below
if (mysql_num_rows($res) == 10) {
echo "Only 10 is allowed.";
}
However I see not much point in it.
Also note that your program design is probably wrong, as you're apparently copying this file for the every user in your system
To get number of rows returned in result you must use mysql_num_rows.
if (mysql_num_rows($checkres)>10)

Categories