0

Below are three options to select data from a MySQL database and output it as a json/array. The queries are in mysql though ... how would they look like with new mysqli? All three options should retain.

<?php

// Connect to MySQL
$link = mysql_connect( 'host', 'user', 'password' );
if ( !$link ) {
die( 'Could not connect: ' . mysql_error() );
}

// Select the data base
$db = mysql_select_db( 'database', $link );
if ( !$db ) {
  die ( 'Error selecting database \'test\' : ' . mysql_error() );
}

// Fetch the data
$query = "
  SELECT category, value1, value2
  FROM table
  ORDER BY value1 ASC";
$result = mysql_query( $query );

// All good?
if ( !$result ) {
  // Nope
  $message  = 'Invalid query: ' . mysql_error() . "\n";
  $message .= 'Whole query: ' . $query;
  die( $message );
}

// Print out rows (Option 1)
while ( $row = mysql_fetch_assoc( $result ) ) {
  echo $row['category'] . ' | ' . $row['value1'] . ' | ' .$row['value2']  . "\n";  
}

// Print out rows (Option 2)
$prefix = '';
echo "[\n";
while ( $row = mysql_fetch_assoc( $result ) ) {
 echo $prefix . " {\n";
 echo '  "category": "' . $row['category'] . '",' . "\n";
 echo '  "value1": ' . $row['value1'] . ',' . "\n";
 echo '  "value2": ' . $row['value2'] . '' . "\n";
 echo " }";
 $prefix = ",\n";
}
echo "\n]";

// Print out rows (Option 3)
$data = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
  $data[] = $row;
}
echo json_encode( $data );

// Close the connection
mysql_close($link);
Dharman
  • 30,962
  • 25
  • 85
  • 135
Philipp M
  • 3,306
  • 5
  • 36
  • 90

1 Answers1

-2

You would first call the seek function.

while ($row = mysql_fetch_assoc($result)) {
    // do stuff with $row
}

mysql_data_seek($result, 0);

while ($row = mysql_fetch_assoc($result)) {
    // do other stuff with $row
}

Please see...

http://php.net/manual/en/function.mysql-data-seek.php