I'm trying to use PDO
for a SELECT
Option, this is my functions.php
code:
<?php
class Benefits
{
public function fetch_all()
{
global $pdo;
$benfitssql = $pdo->query('SELECT * FROM lkup_benefits');
//$benfitssql->execute();
while ($row = $benfitssql->fetch(PDO::FETCH_ASSOC))
{
$ops.= "<option value='" . $row['BenefitOption'] . "'>"
. $row['Benfits'] . "</option>";
}
}
}
?>
This is my main page:
<label>Benefit Type</label>
<select class="select2_category form-control" data-placeholder="Choose a Category" tabindex="1" id="benefittype" name="benefittype">
<?php echo $ops; ?>
</select>
When I select the SELECT
Option, it opens with no records, why would this be, what have I missed?
There are two essential flaws with your code
first, you should never format HTML inside of a function,
second, you should return something from the function
class Benefits {
public function fetch_all() {
global $pdo;
return $pdo->query('SELECT * FROM lkup_benefits') ->fetchAll();
}
}
?>
<label>Benefit Type</label>
<select class="select2_category form-control" data-placeholder="Choose a Category" tabindex="1" id="benefittype" name="benefittype">
<?php foreach ($benefits->fetch_all() as $row): ?>
<option value="<?=$row['BenefitOption']?>"><?=$row['Benfits']?></option>
<?php endforeach ?>
</select>
Adding on to Your Common Sense's answer, everything he said is correct, but he forgot (You forgot right?) one important detail: Globals are evil!
If your function requires a PDO object in order to work, just ask for it!
class Benefits {
public function fetch_all(PDO $pdo) { //Ask for what you need in the constructor!
return $pdo->query('SELECT * FROM lkup_benefits') ->fetchAll();
}
}
?>
<label>Benefit Type</label>
<select class="select2_category form-control" data-placeholder="Choose a Category" tabindex="1" id="benefittype" name="benefittype">
<?php foreach ($benefits->fetch_all($pdo) as $row): //Pass it in when you need it! ?>
<option value="<?=$row['BenefitOption']?>"><?=$row['Benfits']?></option>
<?php endforeach; ?>
</select>
That makes your class a whole lot more flexible, you now don't silently rely on the fact that there's a global object called $pdo and is of PDO type, the code won't work otherwise, and it's very clear now!.
There are other issues, like mixing your data fetching logic with your presentation logic, but that's beyond the scope of this question.