Syeda Naqvi Syeda Naqvi - 7 months ago 14
SQL Question

Fetching data from Database and display it in Form using php

I created two files of PHP and placed it in same folder on localhost.
First file extract data from database and display it in table. I created edit option so when I click on it, it direct me to other page where the selected id data is displayed in the form.

But it's not working. Data is displayed in the form of table but when I click on edit, it do nothing. It's not directing me to second page.

First File Code:

<table border="2">
<tr>
<th>Roll_No</th>
<th>Name</th>
<th> Class</th>
<th>Marks</th>
<th> Edit </th>
</tr>
<?php
$conn=mysqli_connect("localhost","root","","cs_dpt");
$q2="select * from students";
$run=mysqli_query($conn, $q2);
while($row=mysqli_fetch_array($run))
{
$id=$row[0];
$name=$row[1];
$class=$row[2];
$section=$row[3];
?>
<tr>
<td><?php echo $id; ?></td>
<td><?php echo $name; ?></td>
<td><?php echo $class; ?></td>
<td><?php echo $section; ?></td>
<td><a href="edit.php?edit=<?php echo $id; ?>"> Edit </a></td>
</tr>
<?php } ?>
</table>


edit.php

<?php
$conn=mysqli_connect("localhost","root","","cs_dpt");
$edit=$_GET['edit'];
$q="select from students where roll_no='$edit'";
$run=mysqli_query($conn, $q);
while($row=mysqli_fetch_array($run)){
$roll_no=$row[0];
$name=$row[1];
$class=$row[2];
$section=$row[3];
}
?>
<form>
Roll No:<input type="text" name="roll_no" value="<?php echo $roll_no; ?>">
Name:<input type="text" name="name" value="<?php echo $name; ?>">
Class:<input type="text" name="class" value="<?php echo $class; ?>">
Section:<input type="text" name="marks" value="<?php echo $section; ?>">
<button type="button" name="button"><a href=""> Update Record</a></button>
<br><br>
</form>
<?php
header("Location:practise.php");
?>

Answer

Missing * in select query

$q="select from students where roll_no='$edit'";

It would be

$q="select * from students where roll_no='$edit'";

And use MYSQLI_NUM to fetch numeric array

 $run=mysqli_query($conn, $q);
    while($row=mysqli_fetch_array($run,MYSQLI_NUM)){
        $roll_no=$row[0];
        $name=$row[1];
        $class=$row[2];
        $section=$row[3];
    }

Read http://php.net/manual/en/mysqli-result.fetch-array.php