Cant seem to EDIT/MODIFY my php table by id - php

<?php
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
if(!isset($_POST['submit'])){
$result = mysql_query("SELECT * FROM pleasework ORDER BY ID");
$row = mysql_fetch_array($result);
}
?>
<form action="?php echo $_SERVER['PHP_SELF'];?>" id="form2" method="post" name="form2">
<img id="close1" src="X.png" width="25" height="25" onclick ="div_hide1()">
<h2><font size="6">Please change existing data</font></h2>
<hr>
<br>
<font color="yellow">Change Name to: </font><input type="text" name="New" value="<?php echo $row['Name'];?>"/><br><br>
<font color="yellow"> Change Cause to: </font> <input type="text" name="New1" value="<?php echo $row['Cause'];?>"/><br><br>
<font color="yellow">Change Symptom to: </font><input type="text" name="New2" value="<?php echo $row['Symptom'];?>"/><br><br>
<font color="yellow"> Change Gene_affected to: </font><input type="text" name="New3"value="<?php echo $row['Gene_affected'];?>" /><br><br>
<input type="hidden" name="id" value="<?php echo $_GET['ID'];?>"/>
<input type="submit" onclick="clicked(event)" />
</form>
<?php
if(isset($_POST['submit'])){
mysql_query("UPDATE pleasework SET Name= '$_POST[New]' WHERE ID='$_POST[id]'");
mysql_query("UPDATE pleasework SET Cause= '$_POST[New1]' WHERE ID='$_POST[id]'");
mysql_query("UPDATE pleasework SET Symptom= '$_POST[New2]' WHERE ID='$_POST[id]'");
mysql_query("UPDATE pleasework SET Gene_affected= '$_POST[New3]' WHERE ID='$_POST[id]'");
echo "Change Successful<br>" ;
header("Location: databse.php");
mysql_close($con);
}
else {}
?>
This is my php file.
while($row = mysql_fetch_array($result))
{
echo "<TR>";
echo "<TD>" . $row['ID'] ."</TD>";
echo "<TD>" . $row['Name'] . " </TD>";
echo "<TD>" . $row['Cause'] . " </TD>";
echo "<TD>" . $row['Symptom']. " </TD>";
echo "<TD>" . $row['Gene_affected'] . " </TD>";
echo "<TD><font color='red'>Delete row</font> </TD>";
echo "<TD><font color='red'>modify</font> </TD>";
echo "</TR>";
}
And this is the section which has a modify button that links to the edit.php file. The error here is that is doesnt bring over the values in the table to the editing page and then submitting the form doesnt work too. help please

Your code appears a bit confused.
First of all, why to put the modify routine after output the form? Especially since after modify you send the header function, that fails if previously there are some output.
Note also a typo: you forgot to properly open the php tag in the form declaration. Change-it in this way:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" id="form2" method="post" name="form2">
The main problem is that you check if the $_POST[submit] if set, but this is not set, due to the absence of attribute name.
Change it in this way:
<input type="submit" name="submit" onclick="clicked(event)" />
Now your script should work (I don't have tested the sql).
Please also note that your UPDATE routine is redundant: you can reduce the 4 statement to only one in this way:
$result = mysql_query
(
"UPDATE pleasework SET Name='{$_POST[New]}', Cause='{$_POST[New1]}', Symptom='{$_POST[New2]}', Gene_affected='{$_POST[New3]}' WHERE ID={$_POST[id]}"
);
About PHP Original MySQL API:
This extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0

NOTE: mysql_* deprecated, so try to use PDO or mysqli_*.
Simple way:
<?php
if(isset($_POST['submit'])){
$result = mysql_query("UPDATE pleasework
SET Name='".$_POST['New']."',
Cause='".$_POST['New1']."',
Symptom='".$_POST['New2']."',
Gene_affected='".$_POST['New3']."'
WHERE ID=".$_POST['id'].");
if($result ){
echo "Change Successful<br>" ;
header("Location: databse.php");
}
mysql_close($con);
}
YOUR PHP:
while($row = mysql_fetch_array($result))
{ $spaces = " ";
echo "<TR>";
echo "<TD>" . $row['ID'] ."</TD>";
echo "<TD>" . $row['Name'] . $spaces."</TD>";
echo "<TD>" . $row['Cause'] . $spaces."</TD>";
echo "<TD>" . $row['Symptom']. $spaces."</TD>";
echo "<TD>" . $row['Gene_affected'] . $spaces."</TD>";
echo "<TD><a href='delete.php?id=".$row['ID'] ."'>";
echo "<font color='red'>Delete row</font></a>".$spaces."</TD>";
echo "<TD><a href='edit.php?id=" . $row['ID'] ."'>";
echo "<font color='red'>modify</font></a>".$spaces."</TD>";
echo "</TR>";
}

Related

I have 3 users with different id in the database and it keeps getting the last user id that been loop when I accept or reject?

There are 3 id that been view from this table
$sql = mysqli_query($conn, "SELECT * FROM user_appointment WHERE event = '' ");
while($row = mysqli_fetch_assoc($sql)){
$id = $row["id"];
$date = $row["date"];
$office = $row['office'];
echo "<table>";
echo "<tr>";
echo "<td colspan='2'> <strong>Name: </strong>" . $row['first_name'] . " " . $row['middle_name'] . " " . $row['last_name'] . "</td>";
echo "<td><strong>You're request is: </strong>" . $row['event'] . "</td>";
echo "</tr>";
echo "<tr><td colspan='3'> <strong>Address: </strong>" . $row['address'] . " </td></tr>";
echo "<tr><td colspan='3'> <strong>Office to go: </strong>" . $row['office'] . " </td></tr>";
echo "<tr>";
echo "<td> <strong>Contact#: </strong>" . $row['phone'] . "</td>";
echo "<td> <strong>Request made from: </strong>" . $row['curdate'] . "</td>";
echo "<td> <strong>Time request: </strong>" . $row['time'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td colspan='3'><strong><i>Message: </i></strong><br>". $row['message'] . "</td>";
echo "</tr>";
echo "<tr> <td colspan='3'>";
echo "<center><form method='GET'>
<div class='center'>
<label for=''>Select Date:</label><br>
<input type='date' name='userDate' id='userDate' value='' required>
</div><br>
<button type='submit' name='approveSubmit' class='btn btn-success'>ACCEPT</button>
<button type='submit' name='rejectSubmit' class='btn btn-danger'>REJECT</button>";
echo "</form> </center>";
echo "</td></tr>";
echo "</table>";
echo 'Either I choose one of the users, it still getting the user id that been loop last';
if(isset($_GET['approveSubmit'])){
isset($_GET['userDate']);
$date = $_GET['userDate'];
header("location: ../approve_insert.php?id=$id&date=$date");
}
if(isset($_GET['rejectSubmit'])){
header("location: ../reject_insert.php?id=$id");
}
}
You are not passing the correct $id to your header: Location(...
To solve this you would need to pass the id of the user to the form as well, so this value become available when an user is clicked.
You can do this by adding an extra hidden input to the form you are creating
<input type='hidden' name='id' value='".$id."' />
Also there is no need to place the code that controls the action you want to do inside the loop that creates the table. Just place it above (or below) the code that generates the table
<?php
if(isset($_GET['approveSubmit'])){
$date = $_GET['userDate'];
header('location: ../approve_insert.php?id='.$_GET['id'].'&date='.$date);
exit;
}
if(isset($_GET['rejectSubmit'])){
header('location: ../reject_insert.php?id='.$_GET['id']);
exit;
}
$sql = mysqli_query($conn, "SELECT * FROM user_appointment WHERE event = '' ");
while($row = mysqli_fetch_assoc($sql)){
$id = $row["id"];
$date = $row["date"];
$office = $row['office'];
echo '... table start ...';
echo "<center><form method='GET'>
<div class='center'>
<label for=''>Select Date:</label><br>
<input type='date' name='userDate' id='userDate' value='' required>
</div><br>
<button type='submit' name='approveSubmit' class='btn btn-success'>ACCEPT</button>
<button type='submit' name='rejectSubmit' class='btn btn-danger'>REJECT</button>
<input type='hidden' name='id' value='".$id."' />
";
echo "</form> </center>";
echo '... table end ...';
}
Keep in my mind you would still need to sanitize the input of $_GET['id'] and $_GET['userDate'] before using it in your code/queries
My assumption at this point is that multiple users meet the conditions at the end of your loop. If your goal is to redirect to the location specified, from the first header location call, you'd have to prevent the loop from continuing. Typically this would be done with exit().
header("location: ../reject_insert.php?id=$id");
exit();
Also, you're going to get an error that you can't set headers because you've already output body content. The header("location...") can only be called before your echo ... statements.

How do I fill each input value with the data fetched from $row?

The first part of the code, where the id is fetched from another sheet works fine and the data from while($row = mysqli_fetch_assoc($result)) are returned correctly. What I'm trying to do though is put this data in each input value by doing this <input name="visitingdate" type="date" value="<?=$row['visitingdate']?>">. I'm getting this error: "Notice: Trying to access array offset on value of type null in "Directory" on line "line"." This is what I've got so far:
<?php
require('config.php');
$id=$_REQUEST['id'];
$query = "SELECT * from records where id='".$id."'";
$result = mysqli_query($link, $query) or die ( mysqli_error());
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row["visitingdate"]. "</td>";
echo "<td>" . $row["department"] . "</td>";
echo "<td>" . $row["visitingreason"]. "</td>";
echo "<td>" . $row["importance"]. "</td>";
echo "<td>" . $row["visitorname"]. "</td>";
echo "<td>" . $row["company"]. "</td>";
echo "<td>" . $row["internalrecipientname"]. "</td>";
echo "<td>" . $row["visitinglocation"]. "</td>";
echo "<td>" . $row["ETA"]. "</td>";
echo "<td>" . $row["ETD"]. "</td>";
echo "<td>" . $row["HRverification"]. "</td>";
echo "<td>" . $row["visitcompleted"]. "</td>";
}
?>
<!DOCTYPE html>
<html>
<body>
<form action="records.php" method="post">
<br><br><br>
Visiting Date<br><input name="visitingdate" type="date" value="<?=$row['visitingdate']?>"><br><br>
Department <br><input name="department" type="text" value="<?=$row['department']?>"><br><br>
Visiting Reason<br><input name="visitingreason" type="text" value="<?=$row['visitingreason']?>"><br><br>
Importance<br><input name="importance" type="text" value="<?=$row['importance']?>"> <br><br>
Visitor Name<br><input name="visitorname" type="text" value="<?=$row['visitorname']?>"><br><br>
Company<br><input name="company" type="text" value="<?=$row['company']?>"><br><br>
Internal Recipient Name<br><input name="internalrecipientname" type="text" value="<?=$row['internalrecipientname']?>"><br><br>
Visiting Location<br><input name="visitinglocation" type="text" value="<?=$row['visitinglocation']?>"><br><br>
ETA<br><input name="ETA" type="time" value="<?=$row['ETA']?>"><br><br>
ETD<br><input name="ETD" type="time" value="<?=$row['ETD']?>"><br><br>
HR Verification<br><input name="HRverification" type="checkbox" value="<?=$row['HRverification']?>"><br><br>
Visit Completed<br><input name="visitcompleted" type="checkbox" value="<?=$row['visitcompleted']?>"><br><br>
<input name="submit1" type="submit" value="Update">
</form>
<?php
?>
</body>
</html>
The problem is you're trying to access data which is never defined outside the loop.
The varialbe you're trying to access $row will work within the loop only.
To achieve what you want you need to define a variable outside the loop and than set the value of variable in loop.
For example, below sharing an example with one input, for rest you can do the same or tweak around as per your need :
<?php
require('config.php');
$id=$_REQUEST['id'];
$query = "SELECT * from records where id='".$id."'";
$result = mysqli_query($link, $query) or die ( mysqli_error());
$visitingdate = "";
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row["visitingdate"]. "</td>";
$visitingdate = $row["visitingdate"];
}
?>
<!DOCTYPE html>
<html>
<body>
<form action="records.php" method="post">
<br><br><br>
Visiting Date<br><input name="visitingdate" type="date" value="<?=$visitingdate?>"><br><br>
<input name="submit1" type="submit" value="Update">
</form>
<?php
?>
</body>
</html>
I hope this will help you. Thank you.
FYI: Your code is vulnerable to SQL Injection, please write safe code. Provided solution for the requested code in case for learning beginner purpose.

PHP POST yields empty result using sqlite3 database

I have a simple web form in HTML using POST and PHP against an SQLite3 database. The form asks for a database id. When entered and hitting submit, the result does not output to the screen.
Here is the code. Please help! It appears the variable is empty. Where am I going wrong?
Original Form HTML (edit_entry1.html):
<body bgcolor = "#C7CFCA">
</p></p>
<center><h2>Update a Record<br>
<form method="POST" action="update_record.php">
<br />
<center>
<h3>To update a record click on 'View Database' and find the record ID you want to update and enter that ID here.</h3>
</center>
<table>
<tr><td><h2>Record ID: </td><td><h2><input style="font-size:20px" type="text" name="archivo" size="80"></td></tr>
<tr><td><input type="submit" name="save" value="Submit" style="font-size:20px"></td><td><input type=reset value="Reset Form" style="font-size:20px"></td>
</table>
</form>
</center>
</html>
This is the corresponding php script (update_record.php):
<?php
{
//open the database
$db = new SQLite3('wc.db');
// Set Variables from POST
$record = $_POST["archivo"];
//now output the data to a simple html table...
echo "<!DOCTYPE html>\n";
echo "<html lang=\"en\">\n";
echo "<body bgcolor = \"#C7CFCA\" text = \"black\">\n";
echo "<center>";
echo "<p>Record ID is <?php echo $record ?>.</p>";
echo "<table>\n";
echo "<h2>Update a Record</h2>";
echo "<tr><th><u><h3>ID</th><th><u><h3>Last Name</th><th><u><h3>First Name</th>";
echo "<th><u><h3>Middle Name</th><th><u><h3>Section</th>";
echo "<th><u><h3>Lot</th><th><u><h3>Plot</th><th><u><h3>Burial Date</th><th><u><h3>Veteran</th></tr>\n";
$results = $db->query('SELECT id,last_name,first_name,middle_initial,section,lot,plot,burial_date,veteran FROM burials WHERE id = $record');
while ($row = $results->fetchArray()) {
echo "<tr><td><center><h3>" . $row['id'] . "</td><td><center><h3>" . $row['last_name'] . "</td><td><center><h3>" .
$row['first_name'] . "</td><td><center><h3>" . $row['middle_initial'] . "</td><td><center><h3>" .
$row['section'] . "</td><td><center><h3>" . $row['lot'] . "</td><td><center><h3>" . $row['plot'] . "</td><td><center><h3>" . $row['burial_date'] . "</td><td><center><h3>" . $row['veteran'] . "</td></tr>\n";
}
echo "</table>\n";
echo "<p>Record ID is <?php echo $record ?>.</p>";
echo "<label for=\"sql\"><h3>What do you want to update? </label>";
echo "<select id=\"option\">";
echo "<h3><option value=\"last_name\"><h3>Last Name</option>";
echo "<option value=\"fist_name\"><h3>First Name</option>";
echo "<option value=\"middle_initial\"><h3>Middle Name</option>";
echo "<option value=\"section\"><h3>Section</option>";
echo "<option value=\"lot\"><h3>Lot</option>";
echo "<option value=\"plot\"><h3>Plot</option>";
echo "<option value=\"burial_date\"><h3>Burial Date</option>";
echo "<option value=\"veteran\"><h3>Veteran Status</option>";
echo "</select>";
echo "<h2><input style=\"font-size:15px\" type=\"text\" name=\"opt\" size=\"30\">";
echo "</body>\n";
echo "</html>";
}
?>
When I put, say, 1 as the record id in the form, nothing is outputted. I'm new to this and would definitely appreciate some pointers/tips.
To prevent a SQL injection attack, you should consider using the prepare/bind/execute pattern. Use example 1 in the SQLITE3::prepare doc as a guide.
Regarding the problem at hand: From the PHP: Strings doc:
When a string is specified in double quotes or with heredoc, variables
are parsed within it.
Since the SQL query is enclosed in single-quotes ('), the $record variable is not parsed. In other words, what you see is what is being sent to the database, thus no rows are returned.

beginner form with "update from" and "remove" buttons

I'm a beginner with PHP. I watched a tutorial to create a form which modifies my wamp-created mysql database table. Copied the video at first, but then made my own table from scratch and tried to upgrade it.
My add row works correctly, but the update and remove do not. I think the WHERE clause is not correct, referencing reg_id.
I created a unique primary key, which auto-increments and cannot be modified; this is what I want to reference when changes are made (since it cannot be changed).
if (isset($_POST['update'])){
$UpdateQuery = "UPDATE register SET First_Name='$_POST[first_name]', Last_Name='$_POST[last_name]', Breed='$_POST[breed]', Weight='$_POST[weight]', Age='$_POST[age]', Sex='$_POST[sex]' WHERE '$_POST[reg_id]'='$_POST[reg_id]'";
mysqli_query($con,$UpdateQuery);};
if (isset($_POST['delete'])){
$DeleteQuery = "DELETE FROM register WHERE reg_id='$_POST[reg_id]'";
mysqli_query($con,$DeleteQuery);};
Here is the rest of it where the form is located:
while($record=mysqli_fetch_array($myData)){
echo "<form action=register.php method=post>";
echo "<tr>";
echo "<td>" . $record['reg_id'] . " </td>";
echo "<td>" . "<input type=text name=first_name value=" . $record['First_Name'] . " </td>";
echo "<td>" . "<input type=text name=last_name value=" . $record['Last_Name'] . " </td>";
echo "<td>" . "<input type=text name=breed value=" . $record['Breed'] . " </td>";
echo "<td>" . "<input type=int name=weight value=" . $record['Weight'] . " </td>";
echo "<td>" . "<input type=int name=age value=" . $record['Age'] . " </td>";
echo "<td>" . "<input type=text name=sex value=" . $record['Sex'] . " </td>";
echo "<td>" . "<input type=submit name=update value=update" . " </td>";
echo "<td>" . "<input type=submit name=delete value=delete" . " </td>";
echo "</tr>";
echo "</form>";
}
Please help me fix it.
if (isset($_POST['update'])){
$UpdateQuery = "UPDATE register SET First_Name='".$_POST['first_name']."',Last_Name='".$_POST['last_name']."', Breed='".$_POST['breed']."', Weight='".$_POST['weight']."', Age='".$_POST['age']."', Sex='".$_POST['sex']."' WHERE reg_id ='".$_POST['reg_id']."'";
mysqli_query($con,$UpdateQuery);
};
if (isset($_POST['delete'])){
$DeleteQuery = "DELETE FROM register WHERE reg_id='".$_POST['reg_id']."'";
mysqli_query($con,$DeleteQuery);
};
should be enclosed by ' ,that is optional.add hidden will be more better
echo "<td><input type='hidden' name='reg_id' value='".$record['reg_id']."'></td>";
echo "<td><input type='submit' name='update' value='update'></td>";
echo "<td><input type='submit' name='delete' value='delete'></td>";
You are using $_POST without '.
Try this : {$_POST['first_name']} and replace all $_POST according to this.
So your update query will be like this :
"UPDATE register SET First_Name='{$_POST['first_name']}', Last_Name='{$_POST['last_name']}', Breed='{$_POST['breed']}', Weight='{$_POST['weight']}', Age='{$_POST['age']}', Sex='{$_POST['sex']}' WHERE reg_id='{$_POST['reg_id']}'";
There is no field with name reg_id, so your $_POST['reg_id'] will not work.Also please change your where condition. You are matching same value in where condition.
And your delete query will be :
"DELETE FROM register WHERE reg_id='{$_POST['reg_id']}'";
Your query is open for sql injection. Refer this :How can I prevent SQL injection in PHP?
display page
while($record = mysqli_fetch_array($myData)) {
echo "<table>";
echo "<tr>";
echo "<td>".$record['reg_id']."</td>";
echo "<td>".$record['First_Name']."</td>";
echo "<td>".$record['Last_Name']."</td>";
echo "<td>".$record['Breed']."</td>";
echo "<td>".$record['Weight']."</td>";
echo "<td>".$record['Age']."</td>";
echo "<td>".$record['Sex']."</td>";
echo "<td><a href='edit.php?reg_id=".$record['reg_id']."'>EDIT</a></td>";
echo "<td><a href='delete.php?reg_id=".$record['reg_id']."'>DELETE</a></td>";
echo "</tr>";
echo "</table>";
}
delete.php
<?php
if (isset($_POST['delete'])){
$DeleteQuery = "DELETE FROM `register` WHERE `reg_id`={$_GET['reg_id']}'";
mysqli_query($con,$DeleteQuery);
header("Location: your display page");
};
?>
Edit Form
while($record = mysqli_fetch_array($myData)) {
echo '<form action="edit.php" method="Post">
<input type="text" name="First_Name" value="'.$record['reg_id'].'"/>
<input type="text" name="First_Name" value="'.$record['First_Name'].'"/>
<input type="text" name="Last_Name" value="'.$record['Last_Name'].'"/>
<input type="text" name="Breed" value="'.$record['Breed'].'"/>
<input type="text" name="Weight" value="'.$record['Weight'].'"/>
<input type="text" name="Age" value="'.$record['Age'].'"/>
<input type="text" name="Sex" value="'.$record['Sex'].'"/>
<imput type="submit" value="save" name="submit" />
</form>';
}
edit.php
if (isset($_POST['update'])){
$UpdateQuery = "UPDATE `register` SET `First_Name`='{$_POST['first_name']}', `Last_Name`='{$_POST['last_name']}', `Breed`='{$_POST['breed']}', Weight='{$_POST['weight']}', `Age`={$_POST['age']}, Sex='{$_POST['sex']}' WHERE `reg_id`={$_GET['reg_id']}";
mysqli_query($con,$UpdateQuery);
header("Location: your display page");
};

Change table content using a link

I am new to PHP and I made a simple program where you can apply your name and age, it will take the data to the database and the table will be added with a new row.
I want to add a new column where you can click "change", only the data from that particular row will show up in a few textboxes and can be changed. when pressing submit I want to use the UPDATE function to update the records.
example/plot:
Mike Towards 23 Change
Tyler Frankenstein 24
Change Sophie Baker 22
Change
I want to change the age of Sophie Baker to 24 so I press Change on that row.
Now I only want to get the data from that row and make some changes.
The code I have this far:
Drawing the table above the input fields and the input:
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='2'> <tr> <th>Voornaam</th> <th>Achternaam</th> <th>Leeftijd</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<html>
<body>
<br />
<form action="insert.php" method="post"><br />
<input type="text" name="firstname"> Firstname <br />
<input type="text" name="lastname"> Lastname <br />
<input type="text" name="age"> Age
<p><input type="submit"></p>
</form>
</body>
</html>
Parser:
<?php
$con = mysqli_connect("localhost", "user" , "", "personInfo");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added to the database";
echo "<p><a href=sql2.php>Back to form</a></p>";
mysqli_close($con);
?>
I have tried a few things, but I cant figure out how to show the content on the row I want to select.
Change the actual data with the update function won't be the problem, so I only need help to get the actual data from the correct row.
you'd need to select with the primary key of that table if any exists. if not you should create one. I assume you have a primary key named PersonID:
$query = "SELECT * FROM Persons WHERE PersonID = '" . ($_GET['PersonID']) . "'";
to add the edit button:
echo "<table border='2'> <tr> <th>Voornaam</th> <th>Achternaam</th> <th>Leeftijd</th><th>Action</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td><a href = '?PersonID=" . $row['PersonID'] . "'>Edit</a></td>";
echo "</tr>";
}
echo "</table>";
I assume you have a column named "id".
you can do the following:
<?php
$con = mysqli_connect("localhost", "user" , "", "personInfo");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// when you are in "edit mode" just display the row you will edit row
if (isset($_GET['id'])
$result = mysqli_query($con,"SELECT * FROM Persons where id = ".(int)$_GET['id']);
else
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='2'> <tr> <th>Voornaam</th> <th>Achternaam</th> <th>Leeftijd</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td><a href='?id=" . $row['id'] . "'>change</a></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<html>
<body>
<br />
<form action="update.php" method="post"><br />
<input type="hidden" name="id" value="<?php echo isset($_GET['id']?$_GET['id']:'') ?>" />
<input type="text" name="firstname" value="<?php echo isset($row['FirstName'])?$row['FirstName']:'' ?>"/> Firstname <br />
<input type="text" name="lastname" value="<?php echo isset($row['LastName'])?$row['LastName']:'' ?>"/> Lastname <br />
<input type="text" name="age" value="<?php echo isset($row['Age'])?$row['Age']:'' ?>"/> Age
<p><input type="submit"></p>
</form>
</body>
</html>
update.php (handle both insertion and update):
<?php
$con = mysqli_connect("localhost", "user" , "", "personInfo");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['id'])
$sql="UPDATE Persons set FirstName = ?, LastName = ?, Age = ?
WHERE id = ".(int)$_POST['id'];
else
$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES (?, ?, ?)";
$sth = mysqli_prepare($con, $sql);
$sth->bind_param($_POST[firstname],$_POST[lastname],$_POST[age]);
if (!$sth->execute())
{
die('Error: ' . mysqli_error($con));
}
echo "1 record ".(isset($_POST['id']?'modified':'added')." to the database";
echo "<p><a href=sql2.php>Back to form</a></p>";

Categories