LoveDroid
LoveDroid

Reputation: 85

Fetch data from same Mysql column with multiple Ids

Im trying to Fetch data from same Mysql column with multiple Ids and assign each to a variable.

My table is like this

|id |credit|
+----------+
|1  |10    |
+----------+
|2  |20    |
+----------+
|3  |30    |
+----------+

php code is

$sql = "SELECT credit FROM dailycredits Where id IN ('1','2','3')";
$result = $connect->query($sql);
while ($row = mysql_fetch_array($result)){
$id1= $row[0]["credit"];
$id2= $row[1]["credit"];
$id3= $row[2]["credit"];
}

Upvotes: 1

Views: 3373

Answers (1)

Shahnawaz Kadari
Shahnawaz Kadari

Reputation: 1571

Most of case id column is integer, then remove single quotes from following line

change this

$sql = "SELECT credit FROM dailycredits Where id IN ('1','2','3')";

to

$sql = "SELECT credit FROM dailycredits Where id IN (1, 2, 3)";

Note: Single quotes removed from IN

Try this...

$sql = "SELECT credit FROM dailycredits Where id IN (1,2,3)";
$result = $connect->query($sql);
$rows = []; //empty array.
while ($row = mysql_fetch_array($result)){
$rows[] = $row; //assigning credit to array.
}

print_r($rows);

Or you can now access like $rows[0], $rows[2].

Since mysql_ is deprecated in php 5.5.0, I'm strongly not recommend to use mysql_, use mysqli_* instead.

Upvotes: 1

Related Questions