Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does whether a variable needs to be quoted or not depend on if the category in the database is marked as varchar or int?

Tags:

sql

php

mysql

For example, say my query is this:

$query = "SELECT * FROM statements WHERE user_id_created_by=$users_id";

Does whether $user_id need to be quoted or not depend on if the category in the database is marked as varchar or int?

Also, I don't quite understand whether or not spacing affects querys:

Is this the same as the one above:

$query = "SELECT * FROM statements WHERE user_id_created_by = $users_id";
like image 336
shakked Avatar asked Jan 27 '26 23:01

shakked


2 Answers

You shouldn't be using a variable in a query at all. Use prepared statements to prevent sql injection, which could allow an attacker to steal/modify/delete anything they want.

PDO prepared statement (with named parameters):

$params = [
  ':id' => $users_id
]
$query = "SELECT * FROM statements WHERE user_id_created_by=:id";
$sth = $dbh->prepare($query);
$sth->execute(array($params);

mysqli prepared statement:

$stmt = mysqli_prepare($link, "SELECT * FROM statements WHERE user_id_created_by=?")
mysqli_stmt_bind_param($stmt, "s", $users_id);
mysqli_stmt_execute($stmt);

Regarding the spaces in a query, those shouldn't affect anything.

like image 143
m59 Avatar answered Jan 30 '26 15:01

m59


First: Use PDO and prepared statements as m59 says!

The thing with the quotes is the following: Imagine a varchar with spaces like "this is an example".

The query unquoted query would than look like:

SELECT * FROM statements WHERE user_id_created_by=this is an example

(I guess) mysql will then think is an example doesnt belong to the passed varchar.

like image 25
Langusten Gustel Avatar answered Jan 30 '26 14:01

Langusten Gustel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!