-3

I have the following code which choose all rows in MYSQL but it show the last row only

    $query = mysql_query("SELECT * FROM `users`") or die(mysql_error());
     while ( $row = mysql_fetch_assoc($query) )
          {
          $token = $row['instagram_access_token'];
          }
          echo "$token";
Princé Housein
  • 41
  • 1
  • 10

2 Answers2

1

Your code echo last row because, within while loop every time you overwrites $token value with new value. Try to connect using PDO & assign variable to array like this.

 $token=[];
 $user='your_user_name';
 $pass='your_password';
 $conn= new PDO('mysql:host=your_host_name;dbname=your_db_name', $user, $pass);
 $query = $conn->prepare('SELECT * FROM `users`');
 $query->execute();
// alternatively you could use PDOStatement::fetchAll() and get rid of the loop
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    $token[] = $row['instagram_access_token']; // see this line with []
}

 echo '<pre>';
 print_r($token);
 echo '</pre>';

Note: Don't use mysql_* see more here Why shouldn't I use mysql_* functions in PHP?

Community
  • 1
  • 1
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • 1
    @BigRabbit OP is using mysql_* this is just an answer to the question. – chris85 Apr 25 '15 at 17:02
  • @chris85, yaap , i know , i am going to edit my answer & put the total connection code with `PDO`, thanx – A l w a y s S u n n y Apr 25 '15 at 17:05
  • 1
    @BigRabbit Is answering a question for the general public better than answering the specific question asked? I think noting the user should use mysqli or PDO sufficed. – chris85 Apr 25 '15 at 17:56
-1

Change your code to this:

$query = mysql_query("SELECT * FROM `users` ORDER BY RAND()") or    
    die(mysql_error());
while ( $row = mysql_fetch_assoc($query) )
{
    $m = $row['instagram_access_token'];
    echo "$m";
}
Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
  • Why not simply echo $row['instagram_access_token'];? Why to assign to $m just for echo ? – RN Kushwaha Apr 25 '15 at 16:52
  • Concatenate or make it an array I think is a better solution. Then it will be accessible later if needed. – chris85 Apr 25 '15 at 16:52
  • You can echo directly or maybe the question is simplified and instead of echoing the user needs to do something else with that data – Lelio Faieta Apr 25 '15 at 16:53
  • 2
    @LelioFaieta - yes; but the values in `$row` are re-set every time the loop runs. If you want to access them outside the loop, then assigning the contents to another array will let you do that. – andrewsi Apr 25 '15 at 16:58