0

I'd like to select some data from my database using variables.

Here is a short version of my code:

// $a is either null or something like [1, 2]
if ($a) {
    $debug = implode(',', $a);
} else {
    $debug = [0-9];
}

$sql = "SELECT id FROM user WHERE id IN ($debug)"

How can I achieve that I get only user 1 and 2 (= value in $a) if $a is set and all user if $a is not set?

2

2 Answers 2

1

First:
be aware when you directly inject string inside queries, because you can be target of a SQL Injection

Second:
change directly the query might be the easiest solution

// $a is either null or something like [1, 2]
$sql = "SELECT id FROM user";
if ($a) {
    $debug = implode(',', $a);
    $sql = "SELECT id FROM user WHERE id IN ($debug)";
}
Sign up to request clarification or add additional context in comments.

11 Comments

` target of a SQL Injection` does this not need input from a user? If $debug is only set with known values (not from $_POST, or so) then this should not be a problem.
Does something like SELECT id FROM user WHERE id IN (any number) exist?
@Luuk infact in my code i've injected directly the string since idk where that array comes from, but i'm warning him of that possibility
@Luuk the values are from $_GET but I check if the array just contains numbers :).
@user13977445 i'm unable to find any way to achieve what you are asking using numbers, or if you really really need this kind of things, you can use something like where ... id IN (select id from user) and so injecting select id from user as string, but i mean, it's not that great as a suggestion ahah
|
0

you can set flag on $a to check if its null $debug must contain a comma separated string with ids i.e '2,32,12,54,56,76'

$sql = "SELECT id FROM user ";
if(!empty($a)){
$debug = implode(',', $a); //here you must get string like '1,2,3,4,5'
$sql .= " WHERE id IN ($debug)";
}

//here if $a is empty you have all rows and if $a have values you get selected rows

//final query will be
// if a is empty 'SELECT id FROM user '
// else 'SELECT id FROM user WHERE id IN (1,2,3)' // where 1,2,3 got from $debug

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.