1

I have a stored string that echoes like this

$string = 24,56,43,23,45;

I want to retrieve data from mysql, so I do this;

$getcompany = mysql_query("SELECT * FROM pages WHERE id = $string");

If the id matches any of the strings, it should show that info but nothing happens. I tried using explode to breakdown the strings but I don't know how to make the query loop through the string to display the info that matches the string.

I hope am making sense to someone :( pls help.

3 Answers 3

6

use IN:

$string = "24,56,43,23,45";
$getcompany = mysql_query("SELECT * FROM pages WHERE id IN (" . $string . ")");

Which would translate in to the query:

SELECT *
FROM   pages
WHERE  id IN (24,56,43,23,45);

As long as id is a numeric field that will work. If id is a string, you can rework it a bit:

$string = "24,56,43,23,45";
$args = "'" . implode("','", explode(",", $string)) . "'";
$getcompany = mysql_query("SELECT * FROM pages WHERE id IN (" . $args . ")");

Which would translate to:

SELECT *
FROM   pages
WHERE  id IN ('24','56','43','23','45');
Sign up to request clarification or add additional context in comments.

2 Comments

wow...this is awesome! Need to find a good mysql book to read. Any recommendations??? @Brad
@JaySmoke: just the MySQL Reference
2

In that case, you'd use IN:

$nums = "'24','56','43','23','45'";
$query = "SELECT * FROM pages WHERE id IN (". $nums .");"

1 Comment

thanx mate :) you are far too kind
2

What you have to do is to first split the string on the commas and then use an IN clause in the query:

$string = '24,56,43,23,45';
$string = explode(',', $string);

$getcompany = mysql_query("SELECT * FROM pages WHERE id IN($string)");

I assume that your id column is numeric so this shouldn't require putting quotes around the numbers.

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.