0

i'm using this simple query right now:

SELECT * FROM ships ORDER BY shipid ASC

Now i have an array of shipids which should be searched...

$shipid = array("1","9","19","73");

Is there a way to easily do ONE query without loops nor building a query string?

I'm looking for something like this:

SELECT * FROM ships WHERE shipid=(IS IN ARRAY shipids) ORDER BY shipid ASC

Thanks!

1
  • Do note that, assuming the array comes from user input, you've got yourself an SQL injection vulnerability if you just merge the array into the SQL string. You'd better sanitize, or rather parameterize, the array. Commented Jun 25, 2017 at 11:51

2 Answers 2

2

Try php implode() function to convert the array into string like:

$ships = implode(",", ships);

and use it like:

"SELECT * FROM ships WHERE shipid IN (".$ships.") ORDER BY shipid ASC"
Sign up to request clarification or add additional context in comments.

Comments

2

You have to use IN clause

SELECT * FROM ships WHERE shipid IN (1,9,19,73) ORDER BY shipid ASC

You can create query string like below

<?php
$ships = array("1","9","19","73");
$query = "SELECT * FROM ships WHERE shipid IN (".implode(',',$ships).") ORDER BY shipid ASC";
?>

Here is how it generates query string

Script

akshay@db-3325:/tmp$ cat test.php 
<?php
$ships = array("1","9","19","73");
$query = "SELECT * FROM ships WHERE shipid IN (".implode(',',$ships).") ORDER BY shipid ASC";
print $query.PHP_EOL;
?>

Output

akshay@db-3325:/tmp$ php test.php 
SELECT * FROM ships WHERE shipid IN (1,9,19,73) ORDER BY shipid ASC

1 Comment

Does this work in this way? SELECT * FROM ships WHERE shipid IN (shipids) ORDER BY shipid ASC

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.