The autocomplete is almost working as it should, except for a problem with words that start with an Uppercase.
for example the word 'Brussels':
I will be able to find it when I start typing in the searchbox 'russels', but 'Bru...' will not be found.
looking for words starting with a lowercase is not a problem, 'brussels' will show up once i start typing 'bru'.
Also words like New York will not show up when i start tying 'York', but will when i type 'ork'.
Search.php file
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName= "vlucht";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
mysqli_set_charset($conn, 'utf8');
$id = $_GET['q'];
$sql = "SELECT discipline FROM overzicht where discipline like '%".$id."%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["discipline"]. "\n";
}
} else {
echo "0 results";
}
$conn->close();
?>
index.php file:
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="jquery.autocomplete.js"></script>
<script>
jQuery(function(){
$("#search").autocomplete("search.php");
});
</script>
</head>
<body>
Discipline : <input type="text" name="q" id="search" placeholder="Geef je discipline in">
</body>
</html>
MySQL's LIKE is usually case insensitive, unless you are using a collation (e.g. binary) where that would not be the case. Assuming that, for whatever reason, your collation is causing LIKE to be case sensitive, here is one way you may phrase your query to behave the way you want:
$id = $_GET['q'];
$disc = "%" . strtolower($id) . "%";
$sql = "SELECT discipline FROM overzicht WHERE LOWER(discipline) LIKE ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $disc);
$stmt->execute();
Note that I am switching to using prepared statements with mysqli, which avoid things like SQL injection, to which your current script is prone.
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
I have a PHP that I am unable to get it to work. Its function is to connect to my db and delete the input email address from the database. But for some reason, the result is always "Data Not Deleted". I am sure of all the details like db connect details and columns names etc. still the code doesn't work.
Code:
<?php
// php code to Delete data from mysql database
if(isset($_POST['delete']))
{
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "newsletter";
// get id to delete
$email = $_POST['email'];
// connect to mysql
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
// mysql delete query
$query = "DELETE FROM `email_user` WHERE `email` = $email";
$result = mysqli_query($connect, $query);
if($result)
{
echo 'Data Deleted';
}else{
echo 'Data Not Deleted';
}
mysqli_close($connect);
}
?>
<!DOCTYPE html>
<html>
<head>
<title> PHP DELETE DATA </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="unsub.php" method="post">
ID TO DELETE: <input type="text" name="email" required><br><br>
<input type="submit" name="delete" value="Clear Data">
</form>
</body>
</html>
Please point out what I am doing wrong in here?
Thanks
You need to add quotes around $email in your query as it is a string.
$query = "DELETE FROM `email_user` WHERE `email` = '$email'";
Note:- Your code is wide-open for SQL INJECTION.You have to use prepared statements
Help reference:-
mysqli::prepare
PDO::prepare
Try modifying the query to following:
"DELETE FROM `email_user` WHERE `email` = '$email'"
I have read many articles on this password_hash and has applied as much as I can if not all the things I read about it
Still the password_verify still refuses to authenticate values no matter how much I tried. PHP Version 5.61.6 and SQL version 5.7.9
any form of help is appreciated, am already exhausted from trying many string combinations
<!DOCTYPE html>
<html>
<head>
<title>Administrator</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<?PHP
//.......all variables are collected from html form....
$conn = mysqli_connect("localhost", "uname", "pword", "dbname");
mysqli_set_charset($conn, 'utf8');
//.......`SN` column has the unique attribute
$sql = "SELECT * FROM Sign_Up WHERE `SN`=$sn";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$date = date('Y-m-j g:i:s');
//.......idgen is a function previously defined
$id = idgen();
//.......prints $id before hashing....
echo $id."<BR>";
$id = password_hash('$id', PASSWORD_DEFAULT);
//......string length before storing
echo strlen($id)."<BR>";
//......table columns
$f = $row["FirstName"];
$l = $row["LastName"];
$bn = $row["BusinessName"];
$ba = $row["BusinessAddress"];
$sq = "INSERT INTO Distributors (`FirstName`, `LastName`, `BusinessName`, `BusinessAddress`) VALUES ('$f', '$l', '$bn', '$ba')";
$res = mysqli_query($conn, $sq);
}
}
?>
</body>
</html>
And the code for verifying the hash is
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<?PHP
$conn = mysqli_connect($servername, $username, $password, $dbname);
mysqli_set_charset($conn, 'utf8');
//.....phone number has a unique attribute
$sql = "SELECT `ID` FROM Distributors WHERE `PhoneNumber`='number'";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$result1= mysqli_num_rows($result);
$look = mysqli_fetch_array($result)['ID'];
print $look."<BR>";
$look = trim($look);
print $look."<BR>";
print strlen($look)."<BR>";
//......all print statements yields expected results and hashed password is stored
//......in VARCHAR (255)...I also tried CHAR
$ver = password_verify('user input data', '$look');
if ($ver) {
print "ok";
}
else {
print "no";
}
?>
</body>
</html>
Use php variables without any quote or inside double quotes, "":
$id = password_hash($id, PASSWORD_DEFAULT); // no quotes around $id
$ver = password_verify('user input data', "$look"); // double quotes around $look
Single quote strings are not parsed i.e. treated as literal strings while double quoted strings are parsed and therefore variables names are expanded with their values.
When hashing use:
$id = "school";
Password_hash($id);
When verifying use:
Password_verify($id, $data_from_database);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Cant figure out what's going wrong here, no errors are appearing but nothing is being returned. The search bar should return the names of other users from my database.
Here is Test.php:
<?php
session_start();
?>
<!DOCTYPE html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function search(partialSearch){
$.ajax({
url:"PHP.php",
type:"POST",
data {partialSearch:partialSearch},
success:function(result){
$("#results").html(result);
}
});
};
</script>
</head>
<body>
<div class="container">
<h3>Find Other users</h3>
<input type="text" name="partialSearch"onkeyup="search(this.value)"/>
<div id="results"></div>
</div>
</body>
</html>
Here is PHP.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "coursework_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$partialSearch = $_POST['partialSearch'];
$stmt = $conn->prepare("SELECT username FROM members WHERE username LIKE ? ");
$stmt->bind_param('s',$partialSearch);
$stmt->execute();
$stmt->bind_result($username);
while ($row = $stmt->fetch()) {
$searchResults[] = $username;
echo "<div>".$searchResults."</div>";
}
?>
Here is the SQL table:
CREATE TABLE members (
memberID int(5) NOT NULL AUTO_INCREMENT,
username VARCHAR(65) NOT NULL UNIQUE,
password VARCHAR(65) NOT NULL,
PRIMARY KEY (memberID)
);
Thank you in advance for any help!
Besides the missing colon in
data {partialSearch:partialSearch},
^
which should read as:
data: {partialSearch:partialSearch},
Your PHP/MySQL syntax is off.
You're declaring $row in
while ($row = $stmt->fetch())
but not using it anywhere.
However, that's kind of a bad for a good as you don't need that much code to start with.
Plus, since you're using LIKE, you're not using the right syntax for it.
See the manual on this: http://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html
What your code should look like is this:
$partialSearch = "%". $_POST['partialSearch'] ."%";
$stmt = $conn->prepare("SELECT username FROM members WHERE username LIKE ? ");
$stmt->bind_param('s',$partialSearch);
$stmt->execute();
$stmt->bind_result($username);
while ($stmt->fetch()) {
echo $username;
echo "<div>".$searchResults."</div>";
}
Having checked your console and for errors, you'd of seen what was going on or not.
The JS console would have thrown you:
SyntaxError: missing : after property id
If that still doesn't work for you, then you most likely have errors in your database somewhere.
Consult:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
you seem tyo be using $username twice-
first for the database access
$username = "root";
and then to reference the database results
$stmt->bind_result($username);
which would seem to cause a conflict since $username="root" - try changing the name to a different variable and see if that makes a difference; eg:
$stmt->bind_result($user_name);
also you have not declared $searchResults to be an array before pushing elements into it, add the following before the while loop:
$searchResults = array();
Concatenate $partialSearch with % wildcards.
$stmt = $conn->prepare("SELECT username FROM members WHERE username LIKE ? ");
$partialSearch = "%". $_POST['partialSearch'] ."%";
$stmt->bind_param('s',$partialSearch);
...
you are also missing a ":" in the Ajax query - should be:
data: {partialSearch:partialSearch},
I'm using a simple form to do a database query. The database is accessed via password which I've included in the code. I'm not sure why I keep hitting the error on the string escape and the undefined variable $query = htmlspecialchars($query);
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<form action="Search2.php" method="POST">
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
<?php
if (isset($_POST['query']))
$query = $_POST['query'];
if (!empty($query))
$query = $_POST['query'];
// gets value sent over search form
$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 LastName, FirstName FROM Staff
WHERE (`LastName` LIKE '%".$query."%') OR (`FirstName` LIKE '%".$query."%')") or die(mysql_error());
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 "<p><h3>".$results['LastName']."</h3>".$results['FirstName']."</p>";
// posts results gotten from database(title and text) you can also show id ($results['id'])
}
}
else{ // if there is no matching rows do following
echo "No results";
}
?>
</body>
</html>
The issue here is that you've invoked a mysqli object with your credentials, however, later you try to execute with the mysql_ procedural method. You don't have a connection there. You need to stick with the mysqli object. Furthermore, you should use prepared statements to handle your user input on SQL queries.
Remove these, we don't need to do sanitization for prepared statements:
//BYE!
$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
Now let's use the mysqli object and OOP prepared methods. However, first we need to construct our like statements as our query's variables aren't executed, you can't concatenate %?% directly into the prepared() statement.
$query = '%'.$query.'%';
$stmt = $mysqli->prepare("SELECT LastName, FirstName FROM Staff
WHERE LastName LIKE ? OR FirstName LIKE ?");
Now we can bind the parameters to our $stmt object.
$stmt->bind_param('ss', $query, $query);
Let's execute it now and get our data back.
$result = $stmt->execute();
Then we can loop:
while ($row = $result->fetch_assoc()) {
echo "<p><h3>".$result['LastName']."</h3>".$result['FirstName']."</p>";
}
Edit
You also don't need to escape your column names with a backtick because:
They don't have - in the name
They aren't reserved special words in MySQL.
make sure your PHP version is below 7.0 as stated here:
http://php.net/manual/en/function.mysql-real-escape-string.php
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_real_escape_string()
PDO::quote()
I have made a search box so that you can enter the product id that you wish to gain the information of. When i input data in the product id box, there are no results returned, anyone know what im doing wrong? I think that 'while ($row = mysql_fetch_array($result)) {' is wrong but not too sure as everything ive tried didn't work.
<div class="searchbox">
<form action="Search.php" method="get">
<fieldset>
<input name="search" id="search" placeholder="Search for a Product" type="text" />
<input id="submit" type="button" />
</fieldset>
</form>
</div>
<div id="content">
<ul>
<?php
// connect to the database
include('base.php');
$search = mysql_real_escape_string($_GET['search']);
$query = "SELECT * FROM Product WHERE ProductID LIKE '%{$search}%'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo "<li><span class='name'><b>{$row['ProductID']}</b></span></li>";
}
Don't use mysql specific syntax, It's outdated and can get you into real trouble later on, especially if you decide to use sqlite or postgresql.
Use a PDO connection, you can init one like this:
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host , $databaseName, $user, $pass); // You can make it be a global variable if you want to access it from somewhere else.
Then you should make sure that you actually have the variable:
$search = isset($_GET['search']) ? $_GET['search'] : false;
So you can actually skip the database thing if something, somehow, fails.
if(!$search)
{
//.. return some warning error.
}
else
{
// Do what follows.
}
Now you should construct a query that can be used as a prepared query, that is, it accepts prepared statements so that you prepare the query and then you execute an array of variables that are to be put executed into the query, and will avoid sql injection in the meantime:
$query = "SELECT * FROM Product WHERE ProductID LIKE :search;"; // Construct the query, making it accept a prepared variable search.
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(':search' => $search)); // Here you insert the variable, by executing it 'into' the prepared query.
$statement->setFetchMode(PDO::FETCH_ASSOC); // Set the fetch mode.
while ($row = $statement->fetch())
{
$productId = $row['ProductID'];
echo "<li class='name><strong>$productId</strong></li>";
}
Oh yes, don't use the b tag, it's outdated. Use strong instead (It's even smarter to apply font-weight: bold; to .name in a separate css file.
Feel free to ask questions if anything is unclear.
remove the {} before and after $search.
should be:
$query = "SELECT * FROM Product WHERE ProductID LIKE '%$search%'";
You can use:
$result = mysql_query($query) or die($query."<br/><br/>".mysql_error());
To confirm that the data is returning.