Advanced Search Form PHP - 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"

Related

Php script to search a record from database by name. (filter by name)

Can someone correct the code for filter a record by its name. I know the query but perhaps I'm not implementing it properly.
Here is my code. I want to either search by city or simply put a name in textbox to search an hospital. search-by-name is for an input field where I am supposed to write the name I want to search from database. I want to make both options available. How should I implement it correctly, as this one won't work for me.
if (isset($_POST['search'])) {
if (isset($_POST['search-by-city'])) {
$city_id = $_POST['search-by-city'];
$query = "SELECT * FROM `hospitals` WHERE `City_ID` LIKE '$city_id'";
$result = mysqli_query($con,$query);
if (isset($_POST['search-by-name'])) {
$hospital_name = $_POST['search-by-name'];
$query = "SELECT * FROM `hospitals` WHERE `Name` LIKE '$hospital_name'";
$result = filterTable($query); {
if (mysqli_num_rows($result) == 0) {
echo '<div class="col-md-12"> <h2>No recod Found</h2> </div> ';
}
}
}
while($row = mysqli_fetch_array($result)){
$city_id = $row[3];
$query = "SELECT `Name` FROM `cites` WHERE `ID` LIKE '$city_id'";
$result2 = mysqli_query($con,$query);
$row2 = mysqli_fetch_row($result2);
$city_name = $row2[0];
echo '<div class="col-md-4"><h3>'.$row[1].'</h3><h4>'.$city_name.'</h4><h4>'.$row[2].'</h4><h5>'.$row[3].'</h5><h5>'.$row[4].'</h5>
';
}
}
I'm guessing your query should be:
"SELECT * FROM `hospitals` WHERE `Name` LIKE '%$hospital_name%'
Checkout the mySQL manual on string comparison.
Also please don't use $_POST variables directly in SQL queries, that is a major security issue. (Search for sql-injection.)

PHP echo list of users from a database depending on category

Depending on the input from checkboxes I'm trying to echo out users in a database based on category in a table linking the users-table with categories. But I only get one result for each category, even though I know there are several users in each category.
I have spent several dies seaching for the correct way to do this, and based upon the many tutoriels and articles out there I thought this method would work. But it does not.
This is the code that doesn't do what I want it to do:
function printusers($idcheck, $cat){
$sqlString = "SELECT userid FROM user_category WHERE categoryid ='$idcheck'";
$result = mysqli_query($dbLink, $sqlString) or die("Could not search for user id.." . mysqli_error($dbLink));
$row = mysqli_fetch_assoc($result);
// Make the first user on the list visable
mysqli_data_seek($result, 0);
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['userid'];
$sqlString = "SELECT name FROM users WHERE id='$id'";
$result = mysqli_query($dbLink, $sqlString) or die("Could not search for user.." . mysqli_error($dbLink));
$row = mysqli_fetch_assoc($result);
$name = $row['name'];
// echo users
echo "<h2 class=\"browsecategory\">Category: $cat</h2>
<p class=\"user\">Name: $name</p>\n";
}
}
if(isset($_POST['admins'])){
printusers(1, "Administrator");
}
I have also tried replacing the while loop with a foreach loop, like this:
foreach ($result as $row) {
same code as in while loop
}
This method echoed out several empty results. The HTML was there, but there was no information from the database. And the number of reults that were echoed was even higher than the number of results that the database should produce.
This is the HTML. A basic checkbox form:
<form action="results.php" method="POST">
<input type="checkbox" name="admins" id="admins">
<input type="checkbox" name="users" id="users">
<input type="checkbox" name="maillist" id="maillist">
<input type="submit" value="Browse">
</form>

Allowing users to search database for username/email and showing results

I am trying to allow users to search a database and echo results, the thing is I want to search multiple tables. I know I can do SELECT * FROM x1, x2 but the rows are named something else so I cant
echo $row['username']
when the other row is username2. Maybe if its possible something like if($row == whatever), idk. Thanks for any help.
<?php
$search = $_POST['Srch'];
$host = "whatever";
$db = "whatever";
$user = "whatever";
$pwd = "whatever";
$link = mysqli_connect($host, $user, $pwd, $db);
$query = "SELECT * FROM users WHERE email LIKE '%$search%'";
$results = mysqli_query($link, $query);
if(isset($_POST['Srch'])) {
if(mysqli_num_rows($results) >= 0) {
while($row = mysqli_fetch_array($results)) {
echo "Username: " . $row['username'];
echo "Email: " . $row['email'];
}
}
}
?>
<body>
<form action="" method="POST">
<input type="Text" name="Srch">
<input type="Submit" name="Submit">
</form>
Edit: Found a way to do this. Something like this works:
function search1() {
// Search stuff here
}
function search2() {
// Search more stuff here
}
if(isset($_POST['Srch'])) {
search1();
search2();
}
If you want to search multiple tables you're going to have to join them somehow. Since you didn't post your table structure, I can only make assumptions on what you're trying to do, but the general syntax would be:
$query = "SELECT * FROM users u LEFT JOIN something s ON s.id = u.something_id WHERE u.email LIKE '%$search%'";
Then you can echo out the different columns that return. But again, this question needs more information for a better answer.
Hope this helps anyway!

Make a search result a button; so that when clicked retrieves more information about the clicked item

The following code is a basic search engine of my database. The user enters a description and it returns a pupil id, pupil forename and surname accordingly. I know wish to make the value of '$id' (which represents a pupil id) a link/button that when clicked will retrieve from the database more specific information about the projects that individual pupil has completed.
Thank you for your time. Any help will be greatly appreciated.
{if(isset ($_POST ['search'])){
$searchq = $_POST['search'];
$searchq= preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM pupil WHERE pupil_forename LIKE '%$searchq%' OR pupil_surname LIKE '%$searchq%' OR pupil_id LIKE '%$searchq'") or die("Could not search");
$count = mysql_num_rows($query);
if ($count == 0 ) {
$output = "No Pupils fit that description. Try again or add new Pupil details <a href='pupilinput.php'>here.</a>";
} else{
while($row = mysql_fetch_array($query)){
$fname = $row['pupil_forename'];
$sname = $row['pupil_surname'];
$id = $row['pupil_id'];
$output .= '<div> <b>ID:</b> '.$id.' <b>Name:</b> '.$fname.' '.$sname.'</div><br>';
}
}
}}

this is not updating even tho there are no reported errors in this php or sql

Here is the page that is supposed to allow a logged in member to transfere an amount they choose to another user on the system i have been working on this for days and found little about it online that actually helps and only found a few snippets here and there that used prepared statements which failed when i edited it so i want to keep it all mysqli for now until i understand prepared statements better or i learn OOP Or PDO but for now i mainly wish to find out why this failes when it sais it works successfully and when i cant see any errors with this code also i have edited this many times so i have tryed various ways but i must be missing something i have also included the db_conx page as a line in this code and the other included line is just to do with checking if a user is logged in, any ideas what may be wrong with this as its not working.
<form name="username" method="post" action="index.php">
<input type="text" name="username" placeholder="Transfere To Username"/> <br />
<input type="text" name="amount" placeholder="Amount To Send" style="centered"/><br />
<input type="submit" value="continue"/>
</form>
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
session_start();
$username = $_SESSION['username'];
echo "<p><br>";
echo "Logged In As $username";
echo "<p><br>";
include_once("../../../php_includes/check_login_status.php");
require("db_conx.php");
if (isset($_POST["username"]) && !empty($_POST["amount"])) {
$username2 = preg_replace('#[^a-z0-9]#i', '', $_POST['username']);
$amount = preg_replace('#[^a-z0-9.]#i', '', $_POST['amount']);
$amount = (int)$amount;
$select_result = ("SELECT balance FROM users WHERE username = '$username' LIMIT 1") or die(mysqli_error($select_result));
$user_query = mysqli_query($db_conx, $select_result);
$numrows = mysqli_num_rows($user_query);
if ($numrows < 1) {
echo "Error Selecting Data Try Again Or Go Back";
}
while ($select = mysqli_fetch_array($select_result, MYSQLI_ASSOC)) {
$available_balance = $select["balance"];
}
if($available_balance>=$amount){
$result = ("UPDATE users SET balance = balance - '$amount' WHERE username = '$username' LIMIT 1") or die(mysqli_error($result));
$user_query2 = mysqli_query($db_conx, $result);
$numrows2 = mysqli_affected_rows();
if ($numrows2 < 1) {
echo "Error Updating Data Try Again Or Go Back";
}
$result2 = ("UPDATE users SET balance = balance + '$amount' WHERE username = '$username2' LIMIT 1") or die(mysqli_error($result2));
$user_query3 = mysqli_query($db_conx, $result2);
$numrows3 = mysqli_affected_rows();
if ($numrows3 < 1) {
echo "Error Updating Data Try Again Or Go Back";
}}
echo "Amount Of $amount Has Been Transferred To $username2";
} else {
echo "No Amount Has Been Set, Try Again Or Go Back";
}
?>
Don't put table names in single quotes. Single quotes are for string literals and date literals.
SELECT * FROM 'users' WHERE 'username' = $username -- WRONG
SELECT * FROM users WHERE username = '$username' -- BETTER, BUT INSECURE
SELECT * FROM users WHERE username = ? -- BEST
The same is true for your UPDATE statements. Don't quote table names or column names, but do quote strings.
For good examples of using prepared queries with parameters, the most popular and frequently-referenced post on StackOverflow about this is How can I prevent SQL injection in PHP?
Check the return value from mysqli_query(). It will be false if there's a problem. If it returns false, then check mysqli_error() to find out what the problem is. For example, putting a quoted string where a table name should be.
If you don't want to write code after each mysqli_query() to check the return value, you can just configure mysqli to throw an exception when an error occurs. Just do this once at the top of your PHP file, it'll remain in effect for the rest of the script.
mysqli_report(MYSQLI_REPORT_STRICT);
You should understand the difference between mysqli_num_rows() and mysqli_affected_rows(). mysqli_num_rows() counts the rows in the result set from a SELECT, and it only works after you have fetched the rows. Whereas mysqli_affected_rows() counts the rows changed by an INSERT, UPDATE, or DELETE.
Checking the result from mysqli_affected_rows(), you may find that your UPDATEs are changing zero rows. This happens either if the WHERE clause matches no rows (that is, there is no user for $username or $username2), or if the SET clause specifies values that result in no change to the column. You should make sure $amount is not 0.
Try this if you have not. Try to get meaningful errors from database results and requests.
$numrows = mysqli_num_rows($user_query) or die(mysql_error()) ;
$select = mysqli_fetch_array($select_result, MYSQLI_ASSOC) or die(mysql_error());
I rewrote this and got it working with the following, thanks for all your help (everyone who replied)
<form name="username" method="POST" action="index.php" autocomplete="off">
<input type="text" name="username" placeholder="Transfer To Username"/> <br />
<input type="text" name="amount" placeholder="Amount To Send" style="centered"/><br />
<input type="submit" value="continue"/>
</form>
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
session_start();
$username = $_SESSION['username'];
echo "<p><br>";
echo "Logged In As $username";
echo "<p><br>";
include_once("db_conx.php");
if (isset($_POST["username"]) && !empty($_POST["amount"])) {
$username2 = preg_replace('#[^a-z0-9]#i', '', $_POST['username']);
$amount = preg_replace('#[^a-z0-9.]#i', '', $_POST['amount']);
$amount = (int)$amount;
$sql = ("SELECT balance FROM users WHERE username = '$username' AND balance >= $amount");
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query) or die(mysql_error());
if ($numrows < 1) {
echo "<h3>Failed To Complete </h3>";
}
else {
echo "Amount Of $amount Has Been Transferred To $username2 You May Now Go Back";
$sql = ("UPDATE users SET balance = balance - '$amount' WHERE username = '$username' LIMIT 1");
$query = mysqli_query($db_conx, $sql);
$sql = ("UPDATE users SET balance = balance + '$amount' WHERE username = '$username2' LIMIT 1");
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query) or die(mysql_error());
if ($numrows < 1) {
echo "<h3>Failed To Complete Transfer! Try Again Or Go Back</h3>";
}
else {
echo "<h3>Failed To Complete Transfer! Try Again Or Go Back</h3> ";
}
}
}
?>
Back To Balance Page</h3>

Categories