I am trying to create a simple search bar that allows the user to search using a user id to return a specific user.
I need to include SQL injection protection.
currently the page loads a blank screen but when I refresh the page I get the "No results found" response.
I have been reading a lot of posts about search bars but nothing is helping me.
here is the code:
<html>
<head>
<title></title>
</head>
<body>
<form action="search.php" method="POST">
<input type="text" name="search" />
<input type="submit" value="Search" />
</form>
</body>
<?php
//search.php
include("DbConnect.php");
$search = $_POST['search'];
$safesearch = mysqli_real_escape_string($search);
$Query = "SELECT user_id
FROM users
WHERE user_id = '$safesearch'";
$Result = mysqli_query($DB,$Query);
$NumResults = mysqli_num_rows($Result);
if ($NumResults==1)
{
echo "<h1>results: ".$Result."</h1>";
}else{
echo "<h1>No Results found</h1>";
}
?>
You should have an if(isset($_POST['submit']{ } around your code so it only fires if they search and not when the page is loaded.
If you're doing any sort of insert,select or update with sql statements that will have variables within them you should use prepared statements.
Use a prepared statement it's a lot more safe than what you're doing:
<?php
//search.php
include("DbConnect.php");
$search = $_POST['search'];
$safesearch = mysql_real_escape_string($search);
$Query = "SELECT user_id
FROM users
WHERE user_id = ?";
$stmt = $connectionVariableName->prepare($query);
$stmt->bind_param("s",$safesearch);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
$num_rows = $stmt->num_rows;
$stmt->close();
if ($num_rows > 0)
{
echo "<h1>results: ".$result."</h1>";
}else{
echo "<h1>No Results found</h1>";
}
?>
http://php.net/manual/en/mysqli.prepare.php
You should also sanitize the search variable by testing it with regex to make sure it only contains the characters you allow in the userid and not / * ^ etc
You want partial phrase search, I presume.
Then your query must look like this:
$Query = "SELECT user_id
FROM users
WHERE user_id LIKE '%$safesearch%'";
Not very familiar with php, but % symbol seem not being a special character in the language (correct me if I'm wrong), if it by chance is - escape it.
To make it case insensitive -
$safesearch = strtolower($safesearch);
$Query = "SELECT user_id
FROM users
WHERE lowercase(user_id) LIKE '%$safesearch%'";
Related
Have had a look around but still struggling like no tomorrow. Just trying to get a delete button working. But its made complicated because the delete function is not completed on the one file.
Users are currently on the crud/view.php file
<?php
session_start();
if(isset($_SESSION['u_uid']))
$uid = $_SESSION['u_id'];
require_once('connect.php');
$ReadSql = "SELECT * FROM `contact` WHERE users_id=$uid ORDER BY Name";
$res = mysqli_query($connection, $ReadSql);
?>
I have a few functions but my delete button is:
<td> <input type="button" onClick="deleteme(<?php echo $r['u_uid']; ?>)" name="Delete" value="Delete"></td>
Followed by:
function deleteme(delid) {
if(confirm("Are you sure you want to Delete?")){
window.location.href='delete.php?del_id='+delid;
}
}
Leading to a crud/delete.php
<?php
session_start();
if(isset($_SESSION['u_uid'])){
require_once('connect.php');
$select = "DELETE from contact where id='".$_GET['del_id']."'";
$query = mysqli_query($connection, $select) or die($select);
}else {
print_r($_GET['del_id'])
?>
I think you can have the delete function on just the view.php and get rid of the delete.php. But I'm not sure what to do.
Many thanks!
Make sure that the variables really contain something that you expect it to have, does the u_uid was really set, try printing out your delete query to make sure that it builds a valid SQL statement.
Or you can try enclosing your table fields with back-ticks, like you did on your select statement.
It is very advisable also to use prepared statements to make your script more secured.
I am in the process of auditing security tools, and I decided a good approach would be to create my own "insecure area" (with randomly generated fake data), so I set up an area that is susceptible to sql injections. However, I can't actually seem to inject it. I do notice that when I give it a bad query, the "Here are the accounts found" does not print, but the error messages do not print, either.
Can someone tell me if I am doing something incorrect?
<?php
$resultHTML;
if (isset($_POST['email']) || isset($_GET['email'])) {
$conn = mysqli_connect($servername,$username,$password);
if ($conn) {
//this part is insecure (intentionally for testing)
if (isset($_GET['email'])) {
$query = "SELECT * from badSQL.Two WHERE email = '$_GET[email]'";
} else {
$query = "SELECT * from badSQL.Two WHERE email = '$_POST[email]'";
}
//echo $query;
$result = $conn->query($query);
if ($result) {
$resultHTML = "Here are the accounts found: ";
$hasAccount = false;
while ($row = mysqli_fetch_assoc($result)) {
$hasAccount = true;
$resultHTML .= "<br>".print_r($row);
}
if ($hasAccount === false) {
$resultHTML = "No accounts found.";
}
}
} else {
$resultHTML = "DB Connection could not be established: ".$conn->connect_error;
}
}
?>
<html>
<head>
<title>Two BadSQL Test</title>
</head>
<body>
<h1>Two Website!</h1>
<br>
<h3>Forgot Password</h3>
<p>Enter your email below, and click submit:</p>
<form id="forgotForm" method="get">
<input type="text" name="email" />
<input type="submit" value="submit" />
</form>
<br>
<div id="results"><?php echo $resultHTML; ?></div>
</body>
</html>
1' OR '1'='1 should be valid SQLi for your above script, as it would evaluate to:
"SELECT * from badSQL.Two WHERE email = '1' OR '1'='1'"
It doesn't matter that the email address will always be wrong, as it makes use of an OR clause. Considering 1 will always equal 1, the expression as a whole will always hold true. Thus, the above script will 'skip over' all of the email checks, and then attempt to find the first user to satisfy the condition of '1' = '1'. This correlates to the first user in the table (which is usually an administrator as the ID would be 1, leading to further exploitation).
To prevent against this, I'd recommend making use of stored procedures or parameterised queries, and making the first user in each table have the fewest privileges possible. I'd also recommend checking out the OWASP SQLi Prevention Cheat Sheet.
An equivalent non-vulnerable PHP parameterised query would look something like:
$stmt = $dbConnection->prepare('SELECT * FROM badSQL.TwoWHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with $row
}
Also, I'd recommend against deliberately making your own site more vulnerable, as creating a vulnerability for encapsulated fake data could serve as a vector for legitimate attacks.
Hope this helps :)
I have already setup the blocks in App Inventor to submit data, because previously I did and it worked, however when retrieving data it worked too, except when I realized I have fetched all the data in the table and passed it into TinyDB, then from TinyDB, I compare the texts string that matches the user input.
Yes that allowed me to create a login page, but i was comparing data through App Inventor and not from MySQL. So what I did was I tried sending the strings from App Inventor into the php file, then supposedly it will query which will send out user id, username and password, where the username and password will be matched with the $_GET request from App Inventor(user).
Then the final result would be, the queried data would be then sent to App Inventor either as a row of string, and then I can use TinyDB to store the user id, so that on the next page, i can call the id, then query the user data according to my apps needs.
Here's the code
//Details in asterisk to hide.
<?php
define('DB_SERVER', '******');
define('DB_USERNAME', '*******');
define('DB_PASSWORD', '*******');
define('DB_DATABASE', '*******');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
$query = "SELECT user_id, username, user_password FROM User_Login WHERE username='$username' AND user_password='$password'",
$username = mysqli_real_escape_string($db,$_GET['username']),
$password = mysqli_real_escape_string($db,$_GET['password']);
// Perform Query
$result = mysqli_query($db,$query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysqli_error($db) . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
while ($row = mysqli_fetch_assoc($result)) {
echo $row['$username'];
echo $row['username'];
echo $row['user_password'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysqli_free_result($result);
?>
here is one of my database php search files. you welcome to take any of it and use what you want. I went in and added some comments to help with some clarity. Everyone is welcome to make it better. I use it as a template when ever i need to make a search.php
<?php
mysql_connect("localhost", "root", "12450") or die("Error connecting to database: ".mysql_error());
/*
localhost - it's location of the mysql server, usually localhost
root - your username
third is your password
if connection fails it will stop loading the page and display an error
*/
mysql_select_db("myDatabase") or die(mysql_error());
/* tutorial_search is the name of database we've created */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Search Results</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div data-role="page" id="SearchResultsPage" data-theme="b" data-add-back-btn="true">
<div data-role="header">
<h1>Search Results</h1>
</div>
<?php
$query = $_GET['query'];
// gets value sent over search form
$min_length = 3;
// you can set minimum length of the query if you want
if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM emplist
WHERE (`lfname` LIKE '%".$query."%') OR (`id` LIKE '%".$query."%')") or die(mysql_error());
// * means that it selects all fields, you can also write: `id`, `title`, `text`
// articles is the name of our table
// '%$query%' is what we're looking for, % means anything, for example if $query is Hello
// it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
// or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo "<h4><p>".$results['lfname']."</h4>"." ".$results['phonenum']." <br> MCI #".$results['id']." <br> ".$results['state']." ".$results['zip']."</p>";
// posts results gotten from database
}
}
else{ // if there is no matching rows do following
echo "No results found";
}
}
else{ // if query length is less than minimum
echo "ERROR Minimum length is ".$min_length;
}
?>
</body>
<div data-role="content"></div>
<input type="button" name="bIndex" value="Back" onclick="location.href='Index.php'">
<div data-role="footer" data-theme="b">
<h4>____?____?____?___?____ © 2016</h4>
</div>
</html>
<html>
<head>
</head>
<body>
<form action="login_process.php" method="post">
SID: <input type="text" name="sid">
<br />
Password: <input type="text" name="pw">
<br />
<input type="submit" value="Login">
</form>
</body>
</html>
login_process.php FILE
<html>
<head>
</head>
<body>
<?php
include ("connection.php");
$sid = $_POST['sid'];
$pw = $_POST['pw'];
setcookie("username", "$sid". time()+86400);
$result = mysqli_query($con, "SELECT SID FROM student_table WHERE SID='$sid' and password='$pw'") or die('Query failed');
if(!$result){
echo "Failed";
} else {
echo "success". $_COOKIE['username'];
$_SESSION['username'] = $sid;
}
?>
</body>
</html>
I have data in my student_table. But no matter what input i give it says success. even if i click login button without any input it still says success. please help.
You should use quotes when you assign values in sql queries .
SELECT
SID
FROM
student_table
WHERE
SID = '$sid' and password = '$pw'
Also look forward Prepared Statements to protect yourself from sql injections.You should also add the code below to fetch selected row :
while ($row = mysqli_fetch_array($result)) {
$_SESSION['username'] = $row['SID'];
}
Start learning basic debugging:
When a query fails bad, just do this:
Instead of running it (mysql_query, or mysqli_query or whatever you have), ECHO it:
echo "SELECT SID FROM student_table WHERE SID='$sid' and password='$pw'";
After you submit the form, you will be shown the query that runs, go to phpmyadmin or whatever you use and run the query manually. See if there are errors and also see easier what's going on. Advisable when you do work like this, FIRST try the queries in phpmyadmin then apply them in the code, after you are confident they are ok.
This is not really an answer but more about how to find out what is going wrong when you code does not work as you expect.
First, always put you SQL into a variable by itself. Why, so you can 'var_dump' it and see what is happening. So, try this:
$sql = "SELECT SID FROM student_table WHERE SID=$sid and password=$pw";
var_dump($sql, 'my_query'); // you will see what PHP created.
then try the answer provided:
$sql = "SELECT
SID
FROM
student_table
WHERE
SID = '$sid' and password = '$pw'";
At least you will see what is likely to be incorrect.
var_dump($sql, 'the answer_query'); // you will see what PHP created.
$result = mysqli_query($con, $sql) or die('Query failed');
The outer quote marks must be " (double quote) not " ' " (single quote) both of which are perfectly valid PHP. the former allows variables to be replaced in strings.
The latter will treat eveything as a literal string.
I need some help getting a search function to work. I have previously coded something to work similar to this, where if I click on a hyperlink, I'm able to carry a variable forward and then assign this into an SQL script so it pulls only this one thing back from the DB. (Predefined variable, and not user input). I've tried modifying the script I've been using to allow for a form based text box to have user input which is then searched through a single database field, with a LIKE statement.
This is what I have, and it's not returning anything.
Input Form
<form class="formFormat" method="post" action="SearchResult.php">
<label class="lableInput2">Key Words</label>
<input type="text" class="textInput" name="JobDetails" />
<input type="image" src="img/blue/buttonsearch.jpg" value="search" class="buttonInput" alt="Submit Form" border="0" />
</form>
Returning Page
<?php
include('conn_mysql.inc');
include('corefuncs.php');
// create database connection
$conn = dbConnect('query');
// initialize flag
$deleted = false;
// get details of selected record
if ($_GET && !$_POST) {
// check that primary key is numeric
if (isset($_GET['JobDetails']) && is_numeric($_GET['JobDetails'])) {
$JobDetails = $_POST['JobDetails'];
}
else {
$JobDetails = NULL;
}
if ($JobDetails) {
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%JobDetails%'";
$result = mysql_query($sql) or die (mysql_error());
$row = mysql_fetch_assoc($result);
}
}
?>
<p><h1><?php echo ($row['JobTitle'].'<span class="jobid"> #'.$row['IDJobs'].'</span>');?></h1></p>
<p><strong><?php echo ($row['Location']); ?></strong></p>
<p><strong>£<?php echo ($row['JobValue']); ?>.00</strong></p>
<p><strong>www.companyurl.com - BAD IDEA?</strong></p>
<p><strong>Open for Bidding</strong></p>
<br />
<p><span class="jobid">Job Posted: <?php echo ($row['JobPostDate']); ?></span></p>
<p><?php print ($row['JobDetails']); ?></p>
<p><span class="jobid">Job Deadline: <?php echo ($row['JobDeadline']); ?></span></p>
I know that I need to loop the output, so it displays more than one, but at the moment it simply returns the following error for every field (obv the line changes depending on what's trying to extract.
"( ! ) Notice: Undefined variable: row in
C:\wamp\www\ReEmployWork\SearchResult.php on line 54"
Can anyone assist? I'm a bit lost with this, and I believe I'm either going in the wrong direction or just missing something.
You missed $ before the variable name. Instead of:
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%JobDetails%'";
write:
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%$JobDetails%'";
You left your $ before JobDetails in you query.
Also remeber to use http://php.net/manual/en/function.mysql-real-escape-string.php
A suggestion:
$escaped_value = mysql_real_escape_string($JobDetails)
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%$escaped_value%'";
For future readers. I scrapped the code I tried to modify and I took it from the beginning. There's enough information above for anyone to do this. Have a go, and you may end up with a result similar to what I coded.
$JobDetails = $_POST['JobDetails'];
$JobDetails = mysql_real_escape_string($JobDetails);
$sql = "SELECT * FROM `jobs` WHERE `JobDetails` LIKE '%{$JobDetails}%'";
$result = mysql_query($sql) or die (mysql_error());
?>
The above is what I coded and it runs like a dream. You make a lot more mistakes modifying code than you do, if you just code from scratch, so if you're learning dabble and play with code already wrote, but if you need something yourself which is unique then you're best starting from scratch.