3示例如何在mysql中输出JSON。他们应该如何使用mysqli?

时间:2015-12-08 08:04:41

标签: mysql json mysqli

以下是从MySQL数据库中选择数据并将其作为json / array输出的三个选项。查询是在mysql中...他们将如何使用新的mysqli?所有三个选项都应保留。

<?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);

1 个答案:

答案 0 :(得分:0)

您首先要调用搜索功能。

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
}

请参阅......

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