How to Select Multiple Rows from MySQL with One Query and Use Them in PHP

How to select multiple rows from mysql with one query and use them in php

Use repeated calls to mysql_fetch_assoc. It's documented right in the PHP manual.

http://php.net/manual/function.mysql-fetch-assoc.php

// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}

If you need to, you can use this to build up a multidimensional array for consumption in other parts of your script.

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

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.

MYSQL - Select multiple rows in one query

You can retrieve the highest id of the claimid using group by.

$query =    "SELECT max(Id) as Id,claimId FROM statusTable ";
$query .= "WHERE (`chaseStatus` = 'Open') ";
$query .= "GROUP BY claimId";

THis should result in the following table

Id  claimId
5 CL001
6 CL003

Here's a SQL Fiddle: http://sqlfiddle.com/#!2/b000e/1

mysql query select multiple rows where column value is same

$query = "SELECT * FROM `table` WHERE `Column_2` = 'value1' ";
$res = mysql_query($query);
if(mysql_num_rows($res)!=0) {
while($rowData = mysql_fetch_array($res)) {
var_dump($rowData);
}
}
  • Use mysql_num_rows to count number of results.
  • Use mysql_fetch_array or mysql_fetch_assoc to fetch data.


Related Topics



Leave a reply



Submit