WooBin WooYeol WooBin WooYeol - 7 months ago 11
PHP Question

Data Only Returned For 1st DB Call

I am populating 4 selects with the same query but only the 1st select gets populated and the sub-sequent ones do not. Matter of fact once it reaches the second select page_load() stops.


Questions:

1) What is causing page_load to stop?


2) Is there a way to re-use code so that I do not have to make multiple DB Calls to return the same data?

Here is my syntax:

<div id="OrderInfo" runat="server">
<table id="orderinginfo">
<tr>
<td>
<label for="labelselect">Choose an Item</label>
<select>
<option value="null" selected="selected"></option>
<?php
include 'phpquery.php';
$sql = "Select item from items";
echo get_items($sql);
?>
</select>
</td>
</tr>
<tr>
<td>
<label for="labelselect1">Choose an Item:</label>
<select>
<option value="null" selected="selected"></option>
<?php
include 'phpquery.php';
$sql = "Select item from items";
echo get_items($sql);
?>
</select>
</td>
</tr>
</table>
</div>

<?php
function get_items($sql) {
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) { echo "<option value=".$row['item'].">".$row['item']."</option><br>"; }
}
else echo "<option value='null'>default</option>";
$conn->close();
}
?>

Answer

You are re-defining any function or class in phpquery.php. PHP aborts when you try to redefine such a function or class. Consider including that file phpquery.php once and then run your function get_items. You can use include_once or require_once.

require_once() and include_once() statement can be used to include a php file in another one, when you may need to include the called file more than once. If it is found that the file has already been included, calling script is going to ignore further inclusions.

Comments