Skip to content
Advertisement

SQL data displayed from a table to a textbox

I currently have a search screen to display results. A user can click on a link in that search screen to open a new window and view additional information. Currently i’m able to display the additional information as a table however I want to display the data in text boxes.

Currently my code to display the data ins a table is as follows: Code to get the id of the row that the user has clicked on

$id = $_GET['id'];
$sql = "SELECT user_id, name, age, address
FROM details
WHERE user_id= '".id."'";
$query = mysqli_query($connection, $sql);
$_SESSION['user_id'] = $id;?>

Code to display the data as a table:

<tr>
<th>name</th>
<th>age</th>
<th>address</th>
</tr>
<tbody>
<?php while ($row = mysqli_fetch_array($query)){ ?>
<tr>
<td><?php echo $row['name'] ?></td>
<td><?php echo $row['age'] ?></td>
<td><?php echo $row['address'] ?></td>
</tr>
</tbody>

I want to display the data in text boxes and its not as easy as I thought. I thought I could just changethe row to a text box as below.

<label for="name">Full Name:</label>
<input id="name" style="width: 150px; type="text" value="<?php echo $row['name']; ?>

Any pointers would be greatly appreciated.

Advertisement

Answer

As another has said you are open to abuse here but because anyone can type anything into the address bar as a get variable. Try this instead.

<?php
// First check you have the get, then if so retrieve it and run this till the end
if ($_GET) {

// Sanitize the get data
$id = mysqli_real_escape_string($connection, $_GET['id']);
$id = strip_tags($id);
$id = trim($id);
$id = urldecode($id);
$id = htmlspecialchars($id);

// Select the get data from your table
$select = mysqli_query($connection, "select user_id,name,age,address from details where user_id='$id'");

// Check if at least one record actually exists
if (mysqli_num_rows($select)>0) {

// Retrieve an array from your select, this will get all records for that ID so you may want to close the while loop before echoing the results in HTML if you have multiple records...
while ($row=mysqli_fetch_array($select)) {
$real_id = $row['user_id'];
$name = $row['name'];
$age = $row['age'];
$address = $row['address'];

// Display the results in HTML
echo "
<label for='id'>ID</label>
<input type='text' id='id' value='$real_id'>
<label for='name'>Name</label>
<input type='text' id='name' value='$name'>
<label for='age'>Age</label>
<input type='text' id='age' value='$age'>
<label for='address'>Address</label>
<input type='text' id='address' value='$address'>
";

}

}
}
mysqli_close($connection);
?>

Conclusions: if there is no GET data or if the GET data doesn’t correspond to anything in your table nothing will happen.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement