Skip to main content
Inspiring
September 1, 2015
Answered

Using Array Result from Prepared Statement as Parameter in Subsequent Prepared Statement

  • September 1, 2015
  • 3 replies
  • 5346 views

Hi All,

Very new to PHP. Have a series of 3 Prepared Statements (see code below) I'm attempting to run through.  This page fires from a link on a page that lists the individual candidates and all that works OK.  Prepared Statement 1 works and displays the data in the particular row of the wanted columns, Access background thus I'd call it record and fields, but I think it's called row and columns here.  Prepared Statement 2 which quires on a cross-reference table (we have a many-to-many relationship between candidates and positions, thus need for the cross-reference table) works and I can tell the array $selected_positions loads since I can see the position_id data in the <body> of the file using this:

<?php

foreach ($selected_positions as $item) {

    echo $item.'<br>';

  }

  ?>

Can't take this array $selected_positions and use it as the parameter in Prepared Statement 3, at least not how I'm attempting to do it.  So, obviously Prepared Statement 3 is failing thus no way is an array I called $the_positions which is supposed to contain position ids, position titles and position numbers of the position_id that are in  array $selected_positions.  I can tell Prepared Statement 3 is failing because nothing shows in this table which is in the <body> of the file:

<table class="table table-striped">

    <tr>

        <th>Position ID</th>

        <th>Position Number</th>

        <th>Title</th>

    </tr>

    <?php while ($stmt->fetch()) { ?>

        <tr>

            <td><?= $position_id; ?></td>

            <td><?= $position_number; ?></td>

            <td><?= $title; ?></td>

        </tr>

    <?php } ?>

</table>

Here's the PHP script:

<?php

require_once '../includes/session_timeout_db.php';

?>

<?php

require_once '../includes/connection.php';

// initialize flag

$OK = false;

$conn = dbConnect('read');

// initialize statement

$stmt = $conn->stmt_init();

if (isset($_GET['candidate_id'])) {

$sql = 'SELECT candidate_id, last_name, first_name, company, mas_number, last_modified, notes

   FROM candidates WHERE candidate_id = ?'; }

if ($stmt->prepare($sql)) {

  // bind the query parameter

  $stmt->bind_param('i', $_GET['candidate_id']);

  // execute the query, and fetch the result

  $OK = $stmt->execute();

  //bind the results to variables

  $stmt->bind_result($candidate_id, $last_name, $first_name, $company, $mas_number, $last_modified, $notes);

  $stmt->fetch();

  // free the database resources for the second query

        $stmt->free_result();

}

// get positions associated with Candidate

$sql = 'SELECT position_id FROM pos2cands WHERE candidate_id = ?';

  if ($stmt->prepare($sql)) {

   // bind the query parameter

   $stmt->bind_param('i', $_GET['candidate_id']);

   // execute the query, and fetch the result

   $OK = $stmt->execute();

         $stmt->bind_result($position_id);

            // loop through the results to store them in an array

          $selected_positions = [];

            while ($stmt->fetch()) {

                $selected_positions[] = $position_id;

            }

        }

    // find position data from array

$sql = 'SELECT position_id, position_number, title

   FROM positions WHERE position_id = ?';

if ($stmt->prepare($sql)) {

  // bind the query parameter

  $stmt->bind_param('i', $_GET[$position_id]);

  // execute the query, and fetch the result

  $OK = $stmt->execute();

  //bind the results to variables

  $stmt->bind_result($position_id, $position_number, $title);

  // loop through the results to store them in an array

  $the_positions = [];

            while ($stmt->fetch()) {

                $the_positions[] = $position_id;

            }

}

// get error message if query fails

if (isset($stmt) && !$OK) {

$error = $stmt->error;

}

if (!$stmt) {

    $error = $conn->error;

} else {

    $numRows = $stmt->num_rows;

}

?>

Thanks in advancel

This topic has been closed for replies.
Correct answer Rob Hecker2

You want to use the value from query 1 or query2 as a parameter in query 3, right? Instead of building an array, you can simply use the value returned by each row the query returns. I use PDO, not MySQLi, so I can't quickly knock out the MySQLi example for you.

while ($result = $sql->fetch(PDO::FETCH_ASSOC)) {
    $field = $result['field'];

//  Now we can use the value of $field as a parameter for the next query.

// The curly bracket that closes the while loop is placed after the last query

// so no need to populate an array with the values

}

Your approach is doable with some changes to the way you traverse the array, but it's unnecessarily complicated.

You might be able to use a single query to get all the data if you used left joins. With this approach, you start with the table that MUST return a result or the table that requires no dependencies from the other tables. The structure is like this:

SELECT field1, field2, field3 FROM (SELECT * FROM table1 WHERE field3=param1)A

          LEFT JOIN (SELECT * FROM table2 WHERE A.field4=table2.field4)B

          LEFT JOIN table3 ON table3.field5=B.field5 ORDER BY field1

The A and B above are aliases for the table subsets. You can image an implied equal sign ()=A

3 replies

Rob Hecker2
Legend
September 1, 2015

Instead of this

query1

foreach {

}

query 2

query 3

you should do this:

query1

foreach {

query 2

query 3

}

I think you can get the idea from that.

Alternatively you could use left joins

RR456Author
Inspiring
September 1, 2015

Rob,

I know I'm dealing with arrays in query 2 and 3, but I don't quite follow the revised foreach structure to my current structure of these 3 Prepared Statements.  As I noted, I'm a beginner and have been studying David Powers' PHP Solutions but I'm sure David would not wish to come anywhere near this train wreck of code.  Even though query 1 and 2 did work, 3, as structured, doesn't have a prayer.

Any additional comments on your approach of

query1

foreach {

query 2

query 3

}

would be greatly appreciated.

Thanks Rob.

Rob Hecker2
Rob Hecker2Correct answer
Legend
September 2, 2015

You want to use the value from query 1 or query2 as a parameter in query 3, right? Instead of building an array, you can simply use the value returned by each row the query returns. I use PDO, not MySQLi, so I can't quickly knock out the MySQLi example for you.

while ($result = $sql->fetch(PDO::FETCH_ASSOC)) {
    $field = $result['field'];

//  Now we can use the value of $field as a parameter for the next query.

// The curly bracket that closes the while loop is placed after the last query

// so no need to populate an array with the values

}

Your approach is doable with some changes to the way you traverse the array, but it's unnecessarily complicated.

You might be able to use a single query to get all the data if you used left joins. With this approach, you start with the table that MUST return a result or the table that requires no dependencies from the other tables. The structure is like this:

SELECT field1, field2, field3 FROM (SELECT * FROM table1 WHERE field3=param1)A

          LEFT JOIN (SELECT * FROM table2 WHERE A.field4=table2.field4)B

          LEFT JOIN table3 ON table3.field5=B.field5 ORDER BY field1

The A and B above are aliases for the table subsets. You can image an implied equal sign ()=A

Legend
September 1, 2015

So is it a case of 'position_id' not being 'set'? if you actually use a position_id value you know exists do you get anything returned?

FROM positions WHERE position_id = 3';

RR456Author
Inspiring
September 1, 2015

When I put in position_id = 7, see code below:

// find position data from array

$sql = 'SELECT position_id, position_number, title

   FROM positions WHERE position_id = 7';

if ($stmt->prepare($sql)) {

  // bind the query parameter

  $stmt->bind_param('i', $_GET['position_id']);

  // execute the query, and fetch the result

  $OK = $stmt->execute();

  //bind the results to variables

  $stmt->bind_result($position_id, $position_number, $title);

  // loop through the results to store them in an array

  $the_positions = [];

            while ($stmt->fetch()) {

                $the_positions[] = $position_id;

            }

}

The data about position id 7 does not show up in the table see code below for my table:

<table class="table table-striped">

    <tr>

        <th>Position ID</th>

        <th>Position Number</th>

        <th>Title</th>

    </tr>

    <?php while ($stmt->fetch()) { ?>

        <tr>

            <td><?= $position_id; ?></td>

            <td><?= $position_number; ?></td>

            <td><?= $title; ?></td>

        </tr>

    <?php } ?>

</table>

Os, I'm going to see how I move this thread over to this new Code Corner.  Either I copy paste the original or someone can move it.  Thanks for your reply.

Nancy OShea
Community Expert
Community Expert
September 1, 2015

In case you don't know, we have a new coding forum for questions like this:

Coding Corner

Nancy O.

Nancy O'Shea— Product User & Community Expert
RR456Author
Inspiring
September 1, 2015

How do I get this over to Coding Corner

Can someone move it or do I copy paste the original?  Thanks!

Nancy OShea
Community Expert
Community Expert
September 1, 2015

A forum moderator would have to move it for you.

Nancy O.

Nancy O'Shea— Product User & Community Expert