0

I have echoed the first row value of a column with success. Now I was thinking if there is a way to echo the second and the third values separately . Here is the working code

... 
sql="SELECT `semester` FROM `$course`";
$retval=mysqli_query($link,$sql) ;
$row=mysqli_fetch_array($retval) ;
echo $row[0];
.... 

I tried to index the mysql array so that I can echo with indices but its not working. Just want to echo the values separately for js manipulation

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 2
    you can try while .... something like : `while($row = $result->fetch_array($retval)) { echo $row; }` also check this [question](https://stackoverflow.com/questions/14456529/mysqli-fetch-array-while-loop-columns) – jirarium May 20 '20 at 07:37
  • 2
    @jirarium `$row` would an array, so `var_dump`/`print_r` instead of `echo`. And `fetch_array()` doesn't exist – brombeer May 20 '20 at 07:40
  • @kerbh0lz , yes you're correct , the point is to use while . – jirarium May 20 '20 at 07:42
  • 1
    Use `mysqli_fetch_assoc` instead of `mysqli_fetch_array` if you wanted named indexes for your field names. Docs and examples here: https://www.php.net/manual/en/mysqli-result.fetch-assoc.php – ADyson May 20 '20 at 08:39
  • Or, I'm not sure if I understood the question correctly. Are you asking how to output the values on separate lines? Assuming you're outputting this to a browser, then have a think - what kind of markup language do browsers know about, which controls presentation? Answer: HTML. So how do you create a layout for your data? Answer: Use some HTML. So if you want to fetch multiple rows from the database and output each on a new line for example, then `while ($row=mysqli_fetch_array($retval)) { echo $row[0]."
    "; }` is the simplest way.
    – ADyson May 20 '20 at 08:42
  • I need to echo them separately so that I can Id a each separately and do JAVASCRIPT manipulation on the echoed elements –  May 20 '20 at 08:53
  • @Adyson, thanks so much for the assoc help, it was throwing an offset error –  May 20 '20 at 08:54
  • @Adyson so I should use assoc whenever I want to access an indexed element of mysqli_fetch_array? –  May 20 '20 at 08:56

2 Answers2

1

Guys I found the solution. Just define a new variable and access the $result with MYSQLI_FETCH_ROW which always returns the next row in the query. Thanks and all the best

0

If you want to access each row separately using an index you need to first fetch all rows into PHP array.

$sql = "SELECT `semester` FROM `table`";
$retval = $link->query($sql);
$rows = $retval->fetch_all(MYSQLI_BOTH);

echo $rows[0]['semester']; // value from first row
echo $rows[2]['semester']; // value from third row
Dharman
  • 30,962
  • 25
  • 85
  • 135