0

I have this table for example

+------+---------+------+
| id   | item_id | type |
+------+---------+------+
|    1 |       2 | book |
|    1 |       1 | pen  |
+------+---------+------+

I want retrieve all the data where id=1 in a php script, here is the code i used

 <?php 
    $stat="select item_id, type from tb where id=1"; 
    $query = mysqli_query($con, $stat); 
    $result = mysqli_fetch_array($query,MYSQLI_ASSOC);
    print_r($result); 
  ?>

the result is: Array ( [item_id] => 2 [type] => book ) and that is only the first row, how to retrieve all the rows in the php code?

1

3 Answers 3

5

Use this

 <?php 
    $stat="select item_id, type from tb where id=1"; 
    $query = mysqli_query($con, $stat); 
    while($result = mysqli_fetch_array($query,MYSQLI_ASSOC)){
        print_r($result); 
    }
  ?>

by the way: i would call the $stat variable $query (as it is your query). The $query variable actually contains a result, so I would call that $result and your fetch array might be called something else too..

Sign up to request clarification or add additional context in comments.

Comments

1

You have a function called mysql_fetch_array to read about at http://php.net/manual/en/function.mysql-fetch-array.php

Try this example:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM Persons");

while($row = mysql_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "<br />";
  }

mysql_close($con);
?>

For more http://www.w3schools.com/php/php_mysql_select.asp

Comments

1

Well. For oneyou can do that:

<?php
    $stat = "SELECT `item_id`, `type` FROM `tb` WHERE `id` = 1"; 
    $query = mysqli_query( $con, $stat );

    while ( null !== ( $result = mysqli_fetch_assoc( $query ) ) )
    {
        print_r( $result );
    } 
?>

Comments

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.