1

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"];
}
4
  • What is the problem ? Commented Jul 7, 2018 at 21:51
  • the problem is the code doesnt fetch the data, i think its written wrongly. when I echo the variables it says null Commented Jul 7, 2018 at 21:53
  • the datatype of the credit column is Integer Commented Jul 7, 2018 at 22:05
  • Just a note about the usage of mysql* functions. Please see this question where it's explained why you should prefer mysqli* functions. Commented Jul 7, 2018 at 22:07

1 Answer 1

1

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.

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

8 Comments

thats not the case. it did not help and credit column and id column are different
@LoveDroid updated. You are selecting credit based on id column, so id column is also integer. If you pass single quote its considered as string and won't give you any results.
Yes, do you think the second part of the code is correct?
@LoveDroid you want fetch credit for specific ids by group?
I want to fetch the credit data and each credit data row gets saved in a variable. So, $id1 = 10 and $id2 = 20 and $id3 = 30
|

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.