0

In first case, i will get full array:

   <?php

   $servername = "localhost";
   $username = "root";
   $password = "";
   $dbname = "test.com";


   $conn = mysqli_connect($servername, $username, $password, $dbname);

   if (!$conn) {
       die("Connection failed: " . mysqli_connect_error());
   }

   $sql = "SELECT * FROM articles WHERE writer='$w_name' ";
   $result = mysqli_query($conn, $sql);


   if (mysqli_num_rows($result) > 0) {

       while ($row = mysqli_fetch_assoc($result)) {
            echo $row[header];
       }
   }
   mysqli_close($conn);

   ?>

In the second case, i will get just 1st value from array:

   <?php

   $servername = "localhost";
   $username = "root";
   $password = "";
   $dbname = "test.com";


   $conn = mysqli_connect($servername, $username, $password, $dbname);

   if (!$conn) {
       die("Connection failed: " . mysqli_connect_error());
   }

   $sql = "SELECT * FROM articles WHERE writer='$w_name' ";
   $result = mysqli_query($conn, $sql);


   if (mysqli_num_rows($result) > 0) {

       while ($row = mysqli_fetch_assoc($result)) {
            $q=$row[header];
       }
   }
   mysqli_close($conn);

   ?>

<div>
  <? echo $q ?>
</div>

What should I do, to make 2nd case work like 1st? I mean, how to put into $q, all values of array, not just the first.

2
  • 1
    It is defined in other part of code. Commented Feb 5, 2015 at 14:51
  • Your usage of mysqli_num_rows($result) is pointless in this case. Commented Feb 5, 2015 at 14:57

4 Answers 4

2

You are not defining $q as an array at all.

$q=array();
...
while ($row = mysqli_fetch_assoc($result)) {
   $q[]=$row['header'];
}
...

an example of output :

foreach($q as $header) {
   echo $header.'<br>';
}
Sign up to request clarification or add additional context in comments.

Comments

0

You are overwriting $q . Try using $q[]=

Comments

0

change $q=$row[header]; line to $q[]=$row[header];

and then not echo $q; but print_r($q);

Comments

0

Try to change this into the while

$q = array();

if (mysqli_num_rows($result) > 0) {

       while ($row = mysqli_fetch_assoc($result)) {
            array_push($q, $row['header']); // i guess header is a column of the table
       }
}

and then you must have your array when print the $q variable, i mean do an print_r($q)

More info about array_push: http://php.net/manual/es/function.array-push.php

Hope this helps :)

1 Comment

if header is already defined your code won't work. Because php will not interpret it as a string.

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.