How to avoid ' in the sql query? - php

I am using MYSQL 5.5. May I know how to avoid ' in the SQL query? Below is my example query:
<?php
$mySelect1 = "'Ahli Majlis'";
$bracket_mySelect1 = "($mySelect1)";
SQL = "SELECT * FROM user where 1 and nama_gelaran in ".$bracket_mySelect1."";
?>
The wrong result I have checked in the console log data is SELECT * FROM user where 1 and nama_gelaran in ('Ahli Majlis')
Actually I want the result is SELECT * FROM user where 1 and nama_gelaran in ('Ahli Majlis')
What I tried, but it doesn't work:
SQL = SELECT * FROM user where 1 and nama_gelaran in ".html_entity_decode(htmlentities($bracket_mySelect1,ENT_QUOTES),ENT_QUOTES); .";

I am unsure how you are executing the queries but it is best practice to use PDO rather then the mysql_ functions. This also improves security and protects against mysql injection.
Below is a sample of how to connect and run a PDO query. I have changed your IN to be = as it looks like you are only passing one value.
$dsn = "mysql:host=localhost;dbname=mydb";
$user = "dbUsername";
$passwd = "dbPassword";
$name = 'Ahli Majlis';
$pdo = new PDO($dsn, $user, $passwd);
$stm = $pdo->query("SELECT * FROM `user` WHERE nama_gelaran = :name");
$stm->bindParam('name', $name);
$user = $stm->fetch();
print_r($user);

' does not come from MySQL unless that is what you INSERTed. It does come from certain PHP functions such as htmlentities. It is '.

Related

select sql row using pdo with where statement

This is my first time to try PDO and still learning it. I am more familiar in using mysql or mysqli in developing php system.
After deep searching and searching I still can't seem to understand how to query using PDO
In my code I used mysqli inside a function to be called in index.php
function getUsery(){
$ip = getIPAddress();
$query = mysqli_query("select userID from tblUsers where logged='1' AND ip='$ip'");
$row = mysqli_fetch_array($query);
$emp = $row['userID'];
$logged = $row['logged'];
$userlvl = $row['userLevel'];
$_SESSION['logged'] = $logged;
$_SESSION['userLevel'] = $userlvl;
return $emp;
}
I don't really know how to select sql query using PDO with 'where' statement. Most of what I found is using array with no 'where' statement
How can I select the userID where logged is equal to '1' and ip is equal to the computer's ip address and return and display the result to the index.php
There's SQL statement with WHERE in PDO
$sql = "SELECT * FROM Users
WHERE userID = ?";
$result = $pdo->prepare($sql);
$result->execute([$id]);
Assuming that you know how to connect database using PDO, here is how to select SQL with PDO.
$stmt = $db->prepare("select userID from tblUsers where logged = '1' AND ip = :ip");
$stmt->execute(array('ip' => $ip));
$listArray = $stmt->fetchAll();
Notice the :ip at the end of SELECT. If you don't use ? as a parameters, the prefix : is mandatory and the word after that should be the same as the key in the execute function.
EDIT
In case that the above code is inside the function and $db is outside the function, declare $db as global variable inside the function.
This one is imo one of best guides on PDO and how to use it:
https://phpdelusions.net/pdo
WHERE is a part of query and queries in PDO are not much different from pure *sql queries, just there is going on a bit filtering on execution. Read the guide carefully and you will be able to execute any query you need to.

PHP SQL prepared select query not returning anything

When I run the code below, it returns nothing. When I explicitly type a string in the place of the '?', it will return the expected result but using the prepared version has not worked for me thus far. I do not believe there is any kind of versioning issue as using prepared statements for INSERT queries has worked for me in the past. What might be the problem here with the prepared statement?
$pdo = new PDO("mysql:host=localhost;dbname=database", $user, $pass);
$sql = "SELECT * FROM table WHERE column LIKE '%?%';";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($_GET['searchterm']));
$results = $stmt->fetchAll();
print_r($results);
You are preparing the value so it isn't behaving as if you just put the string inside of the query.
When preparing a string you don't need to add " or ', that is done for you. You need to add the %'s into the value that you are escaping.
$pdo = new PDO("mysql:host=localhost;dbname=database", $user, $pass);
$sql = "SELECT * FROM table WHERE column LIKE ?;";
$stmt = $pdo->prepare($sql);
$stmt->execute(array("%{$_GET['searchterm']}%"));
$results = $stmt->fetchAll();
print_r($results);

PHP check if MySQL table contains variable

So I am new to php and I am trying to check if a mysql table contains a variable which is set when a user does a search. If the table contains the variable (it's a string) then I want to be able to do different things depending on its existence.
I should also note that I am a novice with php development!
This is what I have so far;
$db = new mysqli('IP', 'username', 'password', 'database');
$result = $db->query("SELECT * FROM tablename WHERE ColumnName = $searchVar");
if(empty($result)){
//No result Found
}else{
//Found result
}
You need to place single quotes around $searchVar in the query.
$result = $db->query("SELECT * FROM tablename WHERE ColumnName = '$searchVar'");
Then, you must fetch the results of the query.
$result = $result->fetch_row();
Okay so your current query failed because your SQL string wasn't in quotes. It also could have failed once inputted into quotes if your PHP string had a single quote in it. This is how SQL injections occur, user input should never be passed directly into a SQL query. To separate these tasks there are prepared/parameterized queries.
Here's code I think should work for you but this is untested, based off manuals.
$db = new mysqli('IP', 'username', 'password', 'database');
$stmt = $db->prepare('SELECT * FROM tablename WHERE ColumnName = ?');
$stmt->bind_param('s', $searchVar);
$stmt->execute();
if($stmt->num_rows > 0) {
echo 'there are results';
} else {
echo 'there are no results';
}
Link to thread on preventing injections: How can I prevent SQL injection in PHP?

How to prevent weird user inputs from breaking things in queries?

Is there a good standard solution to deal with characters like ' and " from being used in user inputs on a web platform?
I'm using php for a webpage and if I have, for example, a search bar which have the following query behind it.
$sql = "select * from aTable where aColumn like '%".$searchedKeyword."%'";
If I search for like Greg's icecream the ' will break the script. Also, I'm guessing if I search for something like 1' or ID>0 my script will have a false effect.
What is the common solution here? Do you usually filter away undesired characters, or is there maybe some method or similiar built-in to php?
You can us PDO and prepared statements to prevent SQL injection.
http://php.net/manual/en/pdo.prepared-statements.php
$searchedKeyword = "mykeyword";
//Database details
$db = 'testdb';
$username = 'username';
$password = 'password';
//Connect to database using PDO (mysql)
try {
$dbh = new PDO('mysql:host=localhost;dbname='.$db, $username, $password);
} catch (PDOException $e) {
var_dump("error: $e");
}
//Prepared SQL with placeholder ":searchedKeyword"
$sql = "select * from aTable where aColumn like '%:searchedKeyword%'";
$sth = $dbh->prepare($sql);
//Bind parameter ":searchedKeyword" to variable $searchedKeyword
$sth->bindParam(':searchedKeyword', $searchedKeyword);
//Execute query
$sth->execute();
//Get results
$result = $sth->fetchAll(); //fetches all results where there's a match

Is mysql_real_escape_string() unsafe against hexadecimal encoded data?

We know that all user input must be escape by mysql_real_escape_string() function before executing on mysql in php script. And know that this function insert a \ before any ' or " character in user input. suppose following code:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='".mysql_real_escape_string($_POST['username']."' AND password='".mysql_real_escape_string($_POST['password']."'";
mysql_query($query);
// This means the query sent to MySQL would be:
echo $query;
this code is safe.
But I find out if user enters her inputs with hexadecimal format then mysql_real_escape_string() can not do any thing and user can execute her sql injection easily. in bellow 27204f522027273d27 is same ' OR ''=' but in hex formated and sql execute without problem :
$_POST['username'] = 'aidan';
$_POST['password'] = "27204f522027273d27";
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='".mysql_real_escape_string($_POST['username']."' AND password='".mysql_real_escape_string($_POST['password']."'";
mysql_query($query);
// This means the query sent to MySQL would be:
echo $query;
But whether this is true and if answer is yes how we can prevent sql injection in this way?
If you are using mysql_real_escape_string(), odds are you would be better served using a prepared statement.
For your specific case, try this code:
/*
Somewhere earlier in your application, you will have to set $dbh
by connecting to your database using code like:
$dbh = new PDO('mysql:host=localhost;dbname=test', $DBuser, $DBpass);
*/
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";
$user = $_POST['username'];
$password = $_POST['password'];
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user=? AND password=?";
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $user);
$stmt->bindParam(2, $password);
$stmt->execute();
This does require you to use PDO for your database interaction, but that's a good thing overall. Here's a question discussing the differences between PDO and mysqli statements.
Also see this StackOverflow question which is remarkably similar to yours and the accepted answer, from which I poached some of this answer.

Categories