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%'"
Related
I am trying to make SQL in php to return all the entries that matches a keyword that is entered by the user (from search bar).
I want to return all the entries that their name "partial" matches with the keyword.
I want at least to match the keyword, if an entry name in database before has space and after maybe another letter/space.
For example I have three entries with names "Milk", "Semi skimmed Milk" and "Full Milk 2". If the keyword is "Milk" or "milk" or "MiLK", I want to get all these three entries.
The only case I am thinking it might be the problem is case sensitive.
I tried with a keyword that exists exactly in database, but my app (on android) stops .
Based on user3783243 answer.
PHP FILE
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM items WHERE name LIKE CONCAT ('%', ?, '%')";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $keyword);
$res = $stmt->get_result();
while($row = $res->fetch_assoc()) {
echo $row["name"] . ",";
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"] . ",";
}
} else {
echo "0";
}
$conn->close();
?>
Your query should be:
$sql = "SELECT * FROM items WHERE name LIKE CONCAT ('%', ?, '%')";
and then $keyword should be bound with whatever syntax the driver you are using supports.
As is your query would have been:
SELECT * FROM items WHERE name LIKE CONCAT ('%', Milk, '%')
and you wanted Milk to be a string so it needed to be quoted. As is mysql would have thought that was a column.
Alternatively you could do:
$keyword = '%' . $_POST['keyword'] . '%';
$sql = "SELECT * FROM items WHERE name LIKE CONCAT ?";
that is the same and still requires the binding though.
The binding also takes away the SQL injection. See How can I prevent SQL injection in PHP? and/or https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_1:_Prepared_Statements_.28with_Parameterized_Queries.29
Per update.. replace:
$keyword =$_POST['keyword'];
$sql = "SELECT * FROM items WHERE name LIKE '%$keyword%)";
$result = $conn->query($sql);
with:
$sql = "SELECT name FROM items WHERE name LIKE CONCAT ('%', ?, '%')";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $keyword);
$stmt->execute();
$res = $stmt->get_result();
if(empty($conn->errno) && !empty($res)) {
while($row = $res->fetch_assoc()) {
echo $row["name"] . ",";
}
} else {
echo '0';
//print_r($conn->errno);
}
$conn->close();
...
also remove
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"] . ",";
}
} else {
echo "0";
}
$conn->close();
In this case you can convert the input in search bar to either upper or lower case by default then apply query in db like
For Upper case:
$keyword =strtoupper($_POST['keyword']);
$sql = "SELECT * FROM items WHERE upper(name) LIKE '%$keyword%)";
Or for lower case:
$keyword =strtolower($_POST['keyword']);
$sql = "SELECT * FROM items WHERE lower(name) LIKE '%$keyword%)";
the following is my code to do a database search and return the results in this format:
- Institute name 1
Rating: x/5
- Institute name 2
Rating: x/5
code:
search_results.php
<?php
//mysql_
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno())
{
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")");
}
$result = "";
//collect info from database
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
//echo $searchq;
//SQL query
$query = "SELECT institute_id, name FROM institutes WHERE
category1 LIKE '%$searchq%' OR
category2 LIKE '%$searchq%' OR
category3 LIKE '%$searchq%' OR
category4 LIKE '%$searchq%'";
$result = mysqli_query($connection, $query);
// Test if there was a query failure
if(!$result){
die("Database query failed.");
}
$count = mysqli_num_rows($result);
if($count == 0)
{
$output = "There's no search result";
}
else {
while($row = mysqli_fetch_assoc($result))
{
$id = $row["institute_id"];
?>
<li>
<h3>
<a href="institute_profile_test.php?id=<?php echo $id; ?>"><?php echo $row["name"];?>
</a>
</h3>
</li>
<div class = "rating">Rating: x/5</div>
<?php
}
}
}
?>
I have a ratings and institutes table in my database whose table structures are as follows:
ratings
institutes
As you can see, the ratings database already stores some rating information.(I will share the code i wrote to register ratings if required)
What i need to do next is pull in the average rating for each institute and substitute the x with each individual average. What additional code do i write in search_results.php to achieve this goal?
I would also like to sort the institute names as per their average ratings.
Calculating/Saving the average
If I understand correctly, all you need to do is create a simple while loop that runs through all the instances of the institute_id being fetched for each successful "search" query.
while($row = mysqli_fetch_assoc($result)){
$id = $row["institute_id"];
$query2 = "SELECT rating FROM ratings WHERE institute_id ='$id'";
$result2 = mysqli_query($connection, $query2);
//average rating vars
$count = 0;
$sum = 0;
while($row2 = mysqli_fetch_assoc($result2)){
$count++;
$sum += $row2['rating'];
}
$average = $sum / $count;
//display average
.....
}
That should allow you to display the average for each institute, then if you want to display them according to DESCENDING or ASCENDING just save each average in an array. The rest is up to you, try saving the average results in a JSON array and pairing each result with its institute id counter part.
example:
$average = array('institute_x' => 'average')
*Ensure to replace 'institute_x' with id and 'average' with average...
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);
I have a database which simply records words in a table in a single column (with RID beside). All I want to do is display the words in order with a space in between (which I have a working code for below)
<?php
$mysql_host = "mysql1.000webhost.com";
$mysql_database = "db name";
$mysql_user = "user";
$mysql_password = "pass";
// Create connection
$conn = new mysqli( "mysql1.000webhost.com","databaseuser","password","databasename");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'SELECT Words FROM Poetry ';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["Words"]. " ";
}
} else {
echo "0 results";
}
?>
HOWEVER. I want to only display a set amount (say 50) of the MOST RECENT db entries (i.e) the 50 with the highest RID. Can somebody quickly tell me what code I need (in php) which will display the 50 most recent on a web page?
Thanks!
Don't do it with PHP, just add it to your query.
$sql = 'SELECT Words FROM Poetry order by RID desc limit 50';
This query will order the result set by RID descending, most recent first I'm assuming, and limit the result set to 50 records.
You can use
SELECT Words FROM Poetry order by RID desc limit 0,50
0 is the offset and 50 is limit.u can dynamically change those value if needed.
For the better security purpose You can use mysqli prepared statements.
You can see dynamically-bind_param-array-mysqli for Dynamically Bind Params
Try saving it in a variable and echoing it after your while statement.
Something like this
$all_words = '';
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$all_words = "$all_words, $row['Words']";
}
echo"$all_words";
} else {
echo "0 results";
}
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)