How can I take a query result and pass it to a form input as a value?

I want to create a form which is populated with the users details taken from an SQL query suing SQL Server and PHP.

Here is my query:

$result2 = sqlsrv_query( $conn, $query, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
			
				if( $result2 === false)
				{
					 echo "Error in query preparation/execution.\
";
					 die( print_r( sqlsrv_errors(), true));
				}
			
					 while( $row = sqlsrv_fetch_array ( $result2, SQLSRV_FETCH_ASSOC))
				{
		
					echo '<p id="productsContent">'.$row['firstname'];
					echo '<br/>'.$row['surname'];
					echo '<br/>'.$row['email'];
					echo '<br/>'.$row['address'];
					echo '<br/><br/><a href="products.php?productID='.$row['productID'].'"><img id="searchimage" src="' . $row['picture'] .'" /></a>';
					echo '<br/><br/><p/>';
				}

Here is what I am trying to do with my form:

<label class="mandatory">*First name :</label>
<input type="text" name="fName" id="fname" <?php echo'value="'.$row['firstname'].'"'; ?> onfocus="value=''" onblur="if (this.value=='') this.value=this.defaultValue"/><br />

But when I run page the form inputs are empty, so I tried many different things trying to assign $row results to variables and use them instead but it didn’t work, can anyone tell me where I am going wrong with this please?

Many thanks!

The reason is because the line while ($row = …) will get reset as a precursor to exiting the loop.

If you’re expecting only one row returned, you can remove the while loop.

So you can do something like

$row = sqlsrv_fetch_array ( $result2, SQLSRV_FETCH_ASSOC)

instead of

while ($row = sqlsrv_fetch_array ( $result2, SQLSRV_FETCH_ASSOC))

This will give you $row for use later as you seem to need. I would recommend though, to use something other than $row, something more relevant to the data it’s holding, such $user_data if it’s holding user information. This will make code easier to read and understand later, and you won’t into the habit of using arbitrary names like $row, which you might overwrite later on in the page.

Thanks for your advice!

You are right, I will assign the values to user variables, that should be better!

Many thanks!