How to select multiple rows from the same table only using one query?

203
November 29, 2017, at 04:44 AM

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 ?

Answer 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.

Rent Charter Buses Company
READ ALSO
Date to Age Diff() errors in PHP

Date to Age Diff() errors in PHP

I'm falling between two errors while converting a date from datetimepicker to user's age

347
Positon pegman Google Maps FULLSCREEN wrongly positioned with Bootstrap

Positon pegman Google Maps FULLSCREEN wrongly positioned with Bootstrap

I'm having a problem with the Google Street View's pegman, it works normally in normal mode, but when I click on full screen and I'm going to try to put the pegman it's way above my mouse

202
php socket server closing port after 24h

php socket server closing port after 24h

i have a php socket server but i'm facing problems

145