how to select exact json value in mysql query condition - php

I am trying to select exact json value in mysql query condition, currently i am using LIKE and it work but like returns false positive.
my code is::
$id='1';
json data example:: ["1","12","38"]
$sql="SELECT * FROM `posts` WHERE `json_column` LIKE '%".$id."%' ";
with this query, it returns both 1 and 12. how can i get just 1?

Note the extra quotes:
$sql="SELECT * FROM posts WHERE json_column LIKE '%\"$id\"%'";
However, this is wide open to SQL inject if $id comes from user input. Be careful.
The more secure method would be to use parameterised queries with PHPs prepared statements as follows:
$stmt = $dbh->prepare("SELECT * FROM posts WHERE json_column LIKE '%\"?\"%'");
$stmt->bindParam(1, $id);

Related

Understanding PDO Prepared Statements and Binding Parameters

From experience and also having been told constantly the benefits of using prepared statements and binding my parameters, I have constantly used those two techniques in my code, however I would like to understand exactly the purpose of each of those two techiques:
From my understanding of prepared statements:
$sql = "SELECT * FROM myTable WHERE id = ".$id;
$stmt = $conn->prepare($sql);
$stmt->execute();
The previous code should create a sort of a buffer in the database with the query I proposed. Now FROM MY UNDERSTANDING (and I could be very wrong), the previous code is insecure, because the string $sql could be anything depending on what $id actually is, and if $id = 1; DROP TABLE myTable;--, I would be inserting a malicious query even though I have a prepared statement.
FROM MY UNDERSTANDING this is where binding my parameters com in. If I do the following instead:
$sql = "SELECT * FROM myTable WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->execute();
The database should know exactly all the parts of the sql statement before hand:
SELECT these columns: * FROM myTable and WHERE id = "a variable that was input by the user", and if "a variable that was input by the user" != a variable, the query fails.
I have been told by some my understanding is correct, and by others that it is false, could someone please let me know if I am wrong, correct, or missing something? And elaborate as much as you want, all feedback is greatly appreciated!
You're correct that the first case is insecure. It's important to understand though, that preparing a statement only has value if you are using variable data, and/or executing the same query repeatedly. If you are executing plain statements with no variables, you could simply do this:
$sql = "SELECT * from myTable WHERE this_column IS NOT NULL";
$result = $conn->query($sql);
And end up with a PDOStatement object to work with, just like when you use PDO::exec().
For your second case, again, you're largely correct. What's happening is the variable passed to the database is escaped and quoted (unless you specify otherwise with the third argument to PDOStatement::bindParam(), it's sent as a string which is fine for most cases.) So, the query won't "fail" if bad data is sent. It behaves exactly as if you had passed a valid number that didn't exist as an ID in the database. There are, of course, some edge cases where you are still vulnerable even with a correctly prepared statement.
Also, to make life easier, you can use prepared statements like this, to do implicit binding:
$sql = "SELECT * FROM myTable WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->execute([":id"=>$id]);
Or even like this, with un-named parameters:
$sql = "SELECT * FROM myTable WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->execute([$id]);
Naturally, most of this has been explained in the comments while I was typing up the answer!

PHP select query returning false

I am having this piece of code:
$result = mysqli_query($con , 'SELECT * FROM messages WHERE group = "'.$_POST['group'].'" ORDER BY date '.$_POST['order'].'');
I don't understand why it is always returning me false. The variables $_POST['group'] and $_POST['order'] aren't empty .
$_POST['group']='PHP'
$_POST['order']='DESC'
The conecction to the database is corect too.
GROUP is a mysql reserved word and needs to be quoted using backticks;
SELECT * FROM messages WHERE `group` = ...
You're also wide open to SQL injection, you should never add un-validated/un-escaped POST data in string format to your SQL. The safest way to do queries with user data is using prepared statements, or - as a less secure alternative - escape the data using mysqli_real_escape_string.
$result = mysqli_query($con , "SELECT * FROM messages WHERE group = '".mysqli_real_escape_string($_POST['group'])."' ORDER BY date '".mysqli_real_escape_string($_POST['order'])."'";
Try formatting the query like this and see if it helps your result. I also added mysqli_real_escape_string() to escape your input, as your query was wide open to SQL injection.
http://php.net/manual/en/mysqli.real-escape-string.php

Mysqli query Injection , how to inject the SQL query string?

Let's consider i have this line of code
$result = $mysqli->query("SELECT * from myTable where field='".$_GET['var']."');
IMHO this is vulnerable to SQL injections.
So I'd like to prove it trying by sending via Get / URL a "var" param that will inject the query, with potential malicious code.
I actually tryed this:
var = "1'; TRUNCATE myTable; ";
I tryed to print out the SQL string query before executing it and it's actually 2 SQL valid statements.
SELECT * from myTable where field='1'; TRUNCATE myTable;
1st problem
But actually itseems that mysqli->query will not execute 2 statements at once. Isn't it?
2nd problem
I see that a common technique to Inject queries is to per form injection then add comment chars to get rid of the tail of the SQL.
Example:
"SELECT * from myTable where field='".$_GET['var']."' AND field2 IS NOT NULL"
Can be injected with :
var = "1'; TRUNCATE myTable; # ";
But this problem arise and I'm missing the trick to get rid of it
if the SQL string in the code have new lines e.g. :
"SELECT * from myTable where field='".$_GET['var']."'
AND field2 IS NOT NULL"
If i use the above "var" the final result is
SELECT * from myTable where field='1'; TRUNCATE myTable; #
AND field2 IS NOT NULL
Second line won't be commented
How to test injection on this?
Many thanks.
1st problem But actually it seems that mysqli->query will not execute 2
statements at once. Isn't it?
That's right, if you want to execute multiple statements you need to use mysqli->multi_query. You can find a good explanation about multiple statements here: http://www.php.net/manual/en/mysqli.quickstart.multiple-statement.php
But this problem arise and I'm missing the trick to get rid of it
The problem arises because you are using multiple statements, and mysqli->query does not support them.
About your queries:
$result = $mysqli->query("SELECT * from myTable where field='".$_GET['var']."');
You can inject this using for example 1' OR 1=1; that would return all entries of myTable on the query result.
"SELECT * from myTable where field='".$_GET['var']."' AND field2 IS NOT NULL"
Here you could use 1' OR 1=1 UNION ALL SELECT * FROM myTable WHERE '1'='1
Nowadays there are tools that can automatically check SQL injection for you, take a look at SQL Inject Me (Firefox Addon) for example.

PDO misbehaving with bind parameters

I have simple SQL query that could benefit from bind variables so I have written like this:
$stmt = $this->db->prepare("SELECT * FROM activities WHERE user_id=':user_id' AND date(start_time)=date(':on_specific_day')");
$stmt->bindParam(':user_id',$where['user_id']);
$stmt->bindParam(':on_specific_day',$where['on_specific_day']);
As you can see there is an associative array called where which is used to store my where conditions. When I execute this statement it doesn't return any errors but the row count is zero. If I instead discard my dream of using bind variables and do this:
$stmt = $this->db->prepare("SELECT * FROM activities WHERE user_id='{$where['user_id']}' AND date(start_time)=date('{$where['on_specific_day']}')");
The query runs just fine and returns 2 results in my test case. Can someone help me from slipping into madness. :^)
You don't need to enclose your PDO parameters with quote marks:
$stmt = $this->db->prepare("SELECT * FROM activities WHERE user_id=:user_id AND date(start_time)=date(:on_specific_day)

PDO queryString with binded data

If I have a prepared statement like SELECT * FROM users WHERE userid = :userid, i can read this SQL statement via PDOStatement::$queryString. For logging i want to have the string, which is executed, e.g. ... WHERE userid = 42. How do i get this string?
PDOStatement->debugDumpParams is what you want. You may need to use output buffering though as the results are echoed out.

Categories