Hacko Hacko - 6 months ago 32
PHP Question

PHP PDO fetch form data with while and foreach inside the while

I have trouble updating database from form that populate with select option.
This is my code to fill the update form with values from MSSQL database:

$result = $pdo->prepare("SELECT d.id as iddr, d.EGN, d.Names, d.NickName, d.Residence, d.PersonalMobilePhone, d.HomeAddress,d.GarantPerson, c.id as cid, c.city_name, c.post_code, t.id, t.IdDriver, t.StartDateVisa, t.EndDateVisa FROM paerp.dbo.Driver d FULL JOIN paerp.dbo.cities c ON d.Residence = c.id FULL JOIN dbo.TrVisas t ON d.id = t.IdDriver WHERE d.id = :id");

$result->bindParam(':id', $id, PDO::PARAM_STR);
$result->execute();
//for($i=0; $row = $result->fetch(); $i++){
while($row=$result->fetch(PDO::FETCH_ASSOC)){
?>


This is the select option place. This shows only the value from database. Without possibility to change from dropdown.

<select id="residence" name="residence">
<option value="<?PHP echo $row['id']; ?>" selected><?PHP echo $row['city_name']; ?></option>
<?PHP
$result2 = $pdo->prepare("SELECT id, city_name, post_code FROM cities");
$result2->execute();
while($row=$result2->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?PHP echo $row['id']; ?>"><?PHP echo $row['city_name']; ?></option> <?php
}
?>
</select>


I have more inputs after that select option but they are not filled with values from database. Everything stops to this dropdown.
Can sameone help me to figured it out the right way? Thank you!
I try with
foreach
in the place of the second
while
, but then the form inputs are populated but the dropdown do not work.

Answer

You are executing two query while fetch loops, with one nested inside another. There may be other ways of organizing your logic, such as using fetchAll() to retrieve all rows from the outer query at once and then using a foreach to loop them.

But the main problem here is that you use the variable name $row in both fetch loops. This will cause the inner fetch to overwrite the previous contents of $row, breaking any future intended use of that array. Simply using a different variable name than $row for the inner loop will help.

You may have been seeing PHP complain about unset array indexes that would have pointed more closely to problems with $row. Always when developing and testing code, ensure PHP is displaying errors on screen. At the top of your script, (or enable in php.ini on a development workstation):

error_reporting(E_ALL);
ini_set('display_errors', 1);

And ensure that PDO is throwing useful exceptions to help debug its behavior. By default it will error silently.

$pdo = new PDO(/* connection details... */);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Comments