Jump to content

Multiple data sets from one query


lemmin

Recommended Posts

Thanks for the reply. Can you direct me how to do this?

 

Thanks

 

I wrote this quick example to give you the idea of one way to do it:

<?php
$mysqli = new mysqli("localhost", "youusername", "youpassword", "yourdatabase");

/* Check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

// Define Multi-Query
$query  = "SELECT * FROM table1;";
$query .= "SELECT * FROM table2";

// Execute Multi-Query 
if ($mysqli->multi_query($query)) {
  // Use (or Store) and Process the first result set if it exists 
  // NOTE: Replace "field1"... "field4" with the  fieldnames from table1
  if ($result = $mysqli->use_result()) {
     while ($row = $result->fetch_assoc()) {
        echo $row['field1'] . " - " . 
             $row['field2'] . " - " .
             $row['field3'] . " - " .
             $row['field4'] . "<br />";
     }
     // Close and release first result set
     $result->close();
  }

  // Check if the query generated more results
  if ($mysqli->more_results()) {
     if ($mysqli->next_result()) {     // I wrote 2 if's only for demo purposes.. obviously can be done in only one if
        printf("-- Now Printing Records from Second Table --<br />");  
     
       // Use (or Store) and Process the second result set if it exists 
       // NOTE: Replace "field1"... "field4" with the fieldnames from table2
        if ($result = $mysqli->use_result()) {
           while ($row = $result->fetch_assoc()) {
              echo $row['field1'] . " - " . 
                   $row['field2'] . " - " .
                   $row['field3'] . " - " .
                   $row['field4'] . "<br />";
           }
           // Close and release the second result set
           $result->close();
        }
      }
  }    
}

// Close connection
$mysqli->close();
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.