moesef
moesef

Reputation: 4851

SQL LIMIT query not woking

I have the following PHP code:

<?php
  include 'DBConnect.php';
  $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
  $query = "SELECT * FROM telejoke.jokes LIMIT 2";
  $data = mysql_query($query) or die('Error, insert query failed' . mysql_error());
  $info = mysql_fetch_array( $data ); 
  mysql_close($conn);
  echo json_encode($info);   
?>

For instance, if I put LIMIT 2, I want only the first 2 rows from the table to be gathered, encoded into a JSON Array and echoed. Regardless of this LIMIT number, echo json_encode($info); it prints out the whole table.

Trying echo json_encode($data); results in null output.

Help is appreciated. Thanks.

Upvotes: 0

Views: 289

Answers (2)

kernelpanic
kernelpanic

Reputation: 2956

trying doing this:

SELECT * FROM telejoke.jokes LIMIT 0,2

or

SELECT * FROM jokes LIMIT 0,2

Upvotes: 0

fire
fire

Reputation: 21531

Try this...

$info = array();
while ($row = mysql_fetch_array($data)) {
  $info[] = $row;
}

echo json_encode($info);

Upvotes: 3

Related Questions