0

I have one table from MySQL and I want to select some rows from this table without having to use lots of queries to find single rows.

My code currently is something like that :

$query = "SELECT def_conteudo FROM conteudo WHERE nro_conteudo = '101' ";

$query2 = "SELECT def_conteudo FROM conteudo WHERE nro_conteudo = '102' ";

$query3= "SELECT def_conteudo FROM conteudo WHERE nro_conteudo = '103' ";

$query4 = "SELECT def_conteudo FROM conteudo WHERE nro_conteudo = '104' ";

And I don't like it, because for me it seems useless this code but I don't know a better way to find a solution to this, as I am new to PHP.

I want something like that if possible :

$query = "SELECT * FROM conteudo";

And while selecting all the table, I could choose what value I would display, without having multiple queries. How can I make that work ?

1
  • 1
    Use a function to abstract away the repetitive nature of your queries. Or, as you've already wrote, select all the records, and then iterate over them in a loop. Commented Nov 28, 2017 at 19:28

1 Answer 1

1

A couple of ways:

Using between:

SELECT def_conteudo FROM conteudo WHERE nro_conteudo BETWEEN 101 AND 104;

This fetches every row with an ID between those two number. If I remember correctly, the lower end is inclusive and the higher end is exclusive.

Alternatively, if they are not consecutive:

SELECT def_conteudo FROM conteudo WHERE nro_conteudo IN (101, 102, 103, 104); 

This will fetch the ID's in the list.

Sign up to request clarification or add additional context in comments.

1 Comment

It worked like a charm, thank you. +1 and correct answer (in 5 mins) :)

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.