Hacko Hacko - 5 months ago 25x
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);
//for($i=0; $row = $result->fetch(); $i++){

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>
$result2 = $pdo->prepare("SELECT id, city_name, post_code FROM cities");
<option value="<?PHP echo $row['id']; ?>"><?PHP echo $row['city_name']; ?></option> <?php

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
in the place of the second
, but then the form inputs are populated but the dropdown do not work.


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):

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... */);