Hello so i'm learning php and basiclly i want that any field that has been already added to the database to be "editable"
Let me make it more clear with an example
My from looks like this (ver basic)
Firstname [input field]
Lastname [input field]
ZIP Code [input field]
send button
<form method="post" action="">
<table>
<tr>
<td>Vorname</td>
<td><input type="text" name="firstname"></td>
</tr>
<tr>
<td>Nachname</td>
<td><input type="text" name="lastname"></td>
</tr>
<tr>
<td>PLZ</td>
<td><input type="number" name="plz"></td>
</tr>
</table>
<button type="submit" name="send">Send</button>
</form>
When the send button is pressed the output is beeing shown in a table below like so
|---------------------|------------------|------------------|
| Firstname | Lastname | Zip Code |
|---------------------|------------------|------------------|
| Tomas | Möller | 123123 |
|---------------------|------------------|------------------|
and next to those to rows i still have these two (which didn't fit)
|---------------------|------------------|
| Update | Delete |
|---------------------|------------------|
| update | delete |
|---------------------|------------------|
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">PLZ</th>
<th scope="col">Delete</th>
<th scope="col">Update</th>
</tr>
</thead>
<tbody>
<?php
/**
* #var $contact ContactDto
*/
$contacts = $contactRepository->findAll();
foreach ($contacts as $contact) {
?>
<tr>
<th scope="row"><?php echo $contact->getId()?></th>
<td><?php echo $contact->getFirstname() ?></td>
<td><?php echo $contact->getLastname() ?></td>
<td><?php echo $contact->getPlz() ?></td>
<td><a href=delete.php?id=<?php echo (int)$contact->getId()?> >Delete</a></td>
<td><a href=update.php?id=<?php echo (int)$contact->getId()?> >Update</a></td>
</tr>
<?php
}
?>
</tbody>
</table>
So basicaly each row has this own update and delte button.
Here is my problem..im not sure how to do this the right way.
I want when the update is clicked, the value from to fields "go back" to the top field and when send is pressed again the values are updated.
Here is my query
public function update(ContactDto $contactDto) {
$stmt = $this->pdo->prepare("UPDATE contacts SET firstname=:firstname,
lastname=:lastname,
plz=:plz
WHERE id=:id");
$stmt->bindValue(':firstname', $contactDto->getFirstname(), PDO::PARAM_STR);
$stmt->bindValue(':lastname', $contactDto->getLastname(), PDO::PARAM_STR);
$stmt->bindValue(':plz', $contactDto->getPlz(), PDO::PARAM_INT);
$stmt->bindValue(':id', $contactDto->getId(), PDO::PARAM_INT);
$stmt->execute();
}
I did try and make a new update.php file where the data is send, and the fields get filled like so (but that didnt quite work)
this is my update.php file
$contactRepository = new ContactRepository(
DatabaseConnection::getConnection()
);
$contactDto = new ContactDto();
$contactDto->setId($_GET['id']);
$contactDto->setFirstName($_POST['firstname']);
$contactDto->setLastName($_POST['lastname']);
$contactDto->setPlz($_POST['plz']);
$contactRepository->update($contactDto);
?>
<form method="post" action="update.php">
<input type="hidden" name="id" value="<?php echo $contactDto->getId(); ?>" />
<?PHP
?>
<table>
<tr>
<th>First Name: </th>
<td>
<input type="text" id="vorname" name="firstname" placeholder="Dein Vorname" size="35" value="<?php echo $contactDto->getFirstName(); ?>">
</td>
</tr>
<tr>
<th>Last Name: </th>
<td>
<input type="text" id="nachname" name="lastname" placeholder="Dein Nachname" size="35" value="<?php echo $contactDto->getLastName(); ?>">
</td>
</tr>
</table>
<input type="submit" name="save" value="Update" >
Which leaves me with..
>
Notice: Undefined index: firstname in C:\xampp\htdocs\test\update.php on line >14
Notice: Undefined index: lastname in C:\xampp\htdocs\test\update.php on line >15
Notice: Undefined index: plz in C:\xampp\htdocs\test\update.php on >line 16
About the update.php page: the error messages you're getting are saying that 'firstname', 'lastname' and 'plz' are not defined.
This is because you tried to define them using POST:
$contactDto->setFirstName($_POST['firstname']);
$contactDto->setLastName($_POST['lastname']);
$contactDto->setPlz($_POST['plz']);
But in fact, the values of firstname, lastname and plz were not posted to this page. POST is only 'activated' when you click a submit button in a form where you wrote
<form method="POST"...
But you didn't get on the update.php page via a form, but via a hyperlink in this table you made:
foreach ($contacts as $contact) {
?>
<tr>
<th scope="row"><?php echo $contact->getId()?></th>
<td><?php echo $contact->getFirstname() ?></td>
<td><?php echo $contact->getLastname() ?></td>
<td><?php echo $contact->getPlz() ?></td>
<td><a href=delete.php?id=<?php echo (int)$contact->getId()?> >Delete</a></td>
<td><a href=update.php?id=<?php echo (int)$contact->getId()?> >Update</a></td>
</tr>
<?php
}
?>
This is not wrong tho! This table is very good.
But on the update.php page, you can't define 'firstname', 'lastname' and 'plz' using $_POST['....'].
The only thing on the update.php page that IS defined, is 'id'. This is because 'id' was the only thing that you sent to this page using the get method. Again: this is the right way to do it so don't change that.
**
What you DO need to change, is this:
**
change your code:
$contactDto = new ContactDto();
$contactDto->setId($_GET['id']);
$contactDto->setFirstName($_POST['firstname']);
$contactDto->setLastName($_POST['lastname']);
$contactDto->setPlz($_POST['plz']);
To this:
$contactDto = new ContactDto();
$contactDto->setId($_GET['id']);
So only 'id' is defined.
Now define 'firstname', 'lastname' and 'plz' by getting those values from your database, using a query.
Like this:
$getstuff = "SELECT * FROM yourtablename WHERE id = $thevariablethatcontainstheid";
(I guess the variable that contains the 'id' is $contactDto->setId(); ??)
Then execute the query on the next line:
$results = mysqli_query($yourconnectingthing,$getstuff);
And write this below:
$row = $results->fetch_assoc();
And then you can define 'firstname', 'lastname' and 'plz'! By writing this:
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$plz = $row['plz'];
Now the last thing you need to change is the values in the editing form.
This was your code:
<tr>
<th>First Name: </th>
<td>
<input type="text" id="vorname" name="firstname" placeholder="Dein Vorname" size="35" value="<?php echo $contactDto->getFirstName(); ?>">
</td>
</tr>
change it to:
<tr>
<th>First Name: </th>
<td>
<input type="text" id="vorname" name="firstname" placeholder="Dein Vorname" size="35" value="<?php echo $firstname ?>">
</td>
</tr>
Related
I have a table which fetch the data from database except the issued column. The number of row in that table is not fixed. There is an update button and which update the record. After entering the value in issued column i update that record.My data is not updating in the table . I have doubt how to give name to to the td element of the table.Code for table is
<form role="form" method="post" class="form-inline">
<table >
<thead>
<tr >
<th width="50px" >Sl.No.</th>
<th style="display:none;" >Txn ID.</th>
<th width="175px">Stationery Type</th>
<th width="73px">REQUESTED</th>
<th width="73px">ISSUED</th>
</tr>
</thead>
<tbody>
<tr class="table-row-2" >
<td> <?php echo htmlentities($cnt);?></td>
<td style="display:none;"><?php echo htmlentities($result->txnid);?></td>
<td><?php echo htmlentities($result->stationerytype);?></td>
<td><?php echo htmlentities($result->REQUESTED);?></td>
<td><input type="number" name="stationeryqtyissued" > </td>
</TABLE>
<input type="submit" name="submit" value="Submit" class="btn pull-right" style="margin-left:375px; margin-bottom:30px;">
</form>
Mysql code to update database is
if(isset($_POST['submit']))
{
$samplecount=$_GET["total"];
for($i=0;$i<$samplecount;$i++){
$status="issued";
$txnid=$_POST['txnid'];
$stationeryqtyissued=$_POST['stationeryqtyissued'];
$sql="update tblstationerystock set status=:status,stationeryqtyissued=:stationeryqtyissued where txnid=:txnid";
$query = $dbh->prepare($sql);
$query->bindParam(':status',$status,PDO::PARAM_STR);
$query->bindParam(':stationeryqtyissued',$stationeryqtyissued[$i],PDO::PARAM_STR);
$query->bindParam(':txnid',$txnid[$i],PDO::PARAM_STR);
$query->execute();
$_SESSION['msg']="Stationery Added successfully";
Add the following line to you form
<input type="hidden" id="txnid" name="txnid" value="<?php echo htmlentities($result->txnid);?>">
If you want to send an array
<input type="hidden" name="txnid[]" value="<?php echo htmlentities($result->txnid);?>">
then you would have more than one row for that to work
and you can then
get it by
$txnid=$_POST['txnid'];
But that is no array, so that should be valid
$query->bindParam(':stationeryqtyissued',$stationeryqtyissued,PDO::PARAM_STR);
$query->bindParam(':txnid',$txnid,PDO::PARAM_STR);
So i am unclear why you are running a loop for the update over $total that i also don't see in your form.
<td style="display:none;"><?php echo htmlentities($result->txnid);?></td>
Would not send data to your php with POST or GET
The Scenario
I have a scoring card that is populated from another table in the MTSQL with an unknown amount of players. each week the players needs to be scored and those scores needs to be input into the mySQL.
The dynamic html table create for the Mysql table call member.
<form method="post" action="scores-add" id="member-add-form" enctype="multipart/form-data">
<div class="table-responsive">
<table id="data-table-1" class="table table-striped table-bordered">
<thead>
<tr>
<th class="align-middle">Name</th>
<th class="align-middle">Team</th>
<th class="align-middle">Week</th>
<th class="align-middle">Score 1</th>
<th class="align-middle">Score 2</th>
<th class="align-middle">Score 3</th>
<th class="align-middle">Score 4</th>
<th class="align-middle">Score 5</th>
<th class="align-middle">Score 6</th>
<th class="align-middle">Score 7</th>
<th class="align-middle">Score 8</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM member ORDER BY member_name ASC";
$result = mysqli_query($db,$sql) or die("Database access failed: " . mysqli_error());
while ($team = mysqli_fetch_assoc($result)) {
?>
<tr >
<td class="align-middle"><input type="text" name="scoring_1" value="<?php echo $team["member_name"]; ?>" readonly hidden> <?php echo $team["member_name"]; ?></td>
<td class="align-middle"><input type="text" name="scoring_2" value="<?php echo $team["member_team"]; ?>" readonly hidden> <?php echo $team["member_team"]; ?></td>
<td class="align-middle"><input type="text" name="scoring_3" value="" readonly hidden> </td>
<td class="align-middle"><input type="checkbox" name="scoring_4" value="5"></td>
<td class="align-middle"><input type="checkbox" name="scoring_5" value="10"></td>
<td class="align-middle"><input type="checkbox" name="scoring_6" value="5"></td>
<td class="align-middle"><input type="checkbox" name="scoring_7" value="5"></td>
<td class="align-middle"><input type="checkbox" name="scoring_8" value="5"></td>
<td class="align-middle"><input type="checkbox" name="scoring_9" value="5"></td>
<td class="align-middle"><input type="checkbox" name="scoring_10" value="20"></td>
<td class="align-middle"><input type="checkbox" name="scoring_11" value="50"></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<div class="form-row mb-3">
<button type="submit" class="btn btn-primary btn-block" name="score_add_btn">Add Score</button>
</div>
</form>
The function to add the table to the SQL
/ call the team_edit() function if team_edit_btn is clicked
if (isset($_POST['score_add_btn'])) {
score_add();
}
// LOGIN USER
function score_add(){
global $db, $errors, $member_id, $member_name_edit, $member_team_edit, $members_view_url;
// grap form values
$scoring_1 = $_POST['scoring_1'];
$scoring_2 = $_POST['scoring_2'];
$scoring_3 = $_POST['scoring_3'];
$scoring_4 = $_POST['scoring_4'];
$scoring_5 = $_POST['scoring_5'];
$scoring_6 = $_POST['scoring_6'];
$scoring_7 = $_POST['scoring_7'];
$scoring_8 = $_POST['scoring_8'];
$scoring_9 = $_POST['scoring_9'];
$scoring_10 = $_POST['scoring_10'];
$scoring_11 = $_POST['scoring_11'];
// make sure form is filled properly
if (empty($scoring_1)) {
array_push($errors, "Name is required");
}
if (count($errors) == 0) {
$query = "INSERT INTO scoring (scoring_1, scoring_2, scoring_3, scoring_4, scoring_5, scoring_6, scoring_7, scoring_8, scoring_9, scoring_10, scoring_11 )
VALUES ('$scoring_1', '$scoring_2', '$scoring_3', '$scoring_4', '$scoring_5', '$scoring_6', '$scoring_7', '$scoring_8', '$scoring_9', '$scoring_10', '$scoring_11')";
mysqli_query($db, $query);
$_SESSION['success'] = "<h4>Done</h4>";
header("location: $leaderboard_menmber_url");
}else {
$_SESSION['failure'] = "Error updating record: " . $db->error;
header("location: $leaderboard_menmber_url");
}
$db->close();
}
The Problem
The function only adds the last line from the dynamic html table to the database.
The desired outcome.
Each entry in the dynamic HTML table needs to be added to the MySQL as its own entry.
<input type="text" name="scoring_1" value="<?php echo $team["member_name"]; ?>
here you set your variable name to scoring_1 but the next row of table will override that (Instead the browser may send the data, but php will create a variable scoring_1 and assign one of the given values to them. To solve this problem set the name to scoring_1[]
<input type="text" name="scoring_1[]" value="<?php echo $team["member_name"]; ?>
This say php to make an array and store the values there. Futher you can inprove your code when you use something like the team id as row index and used a fixed number as column in a 2 dimensional array
<input type="text" name="scoring[<?php echo $team["id"];>][1]" value="<?php echo $team["member_name"]; ?>
I'm not a complete noob, but I don't have more than a handful of months experience with HTML any help with this will be appreciated. I have a webpage that shows a table with several columns and several rows. I have an Edit link at the end of each row that takes you to another page that is supposed to make the data in the row editable. I can make the first page and the link takes me to another page, but i can't figure out how to get the data from the table row on the first page and put into the table on the second page. I want it to go from a table with 1 row selected to a table with 2 columns and 1 row for each of the columns in the first table.
Here's the page with the table:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Testing PHP</title>
<link rel="StyleSheet" href="StyleSheet.css" type="text/css">
</head>
<body>
<!--h2>This will pull down all the Names from the QDef table</h2-->
<link rel="StyleSheet" type="text/css" href="StyleSheet.css">
<p>4 Results</p>
<table class="tab"id="NameTable">
<thead>
<tr>
<th class="cell">Edit</th>
<th class="cell">TempID</th>
<th class="cell">Name</th>
<th class="cell">CountryCode</th>
<th class="cell">Budget</th>
<th class="cell">Used</th>
</tr>
</thead>
<tbody>
<tr class="row1">
<td>
Edit
</td>
<td contenteditable>1</td>
<td contenteditable>Win Temp</td>
<td contenteditable>TH</td>
<td contenteditable>1000000.000000000</td>
<td contenteditable>60000.000000000</td>
</tr>
</tbody>
<tbody>
<tr class="row">
<td>
Edit
</td>
<td contenteditable>2</td>
<td contenteditable>Test Temp</td>
<td contenteditable>UK</td>
<td contenteditable>100000.000000000</td>
<td contenteditable>5000.000000000</td>
</tr>
</tbody>
<tbody>
<tr class="row1">
<td>
Edit
</td>
<td contenteditable>3</td>
<td contenteditable>Number 3</td>
<td contenteditable>UK</td>
<td contenteditable>1000000.000000000</td>
<td contenteditable>50000.000000000</td>
</tr>
</tbody>
<tbody>
<tr class="row">
<td>
Edit
</td>
<td contenteditable>4</td>
<td contenteditable>Number 4</td>
<td contenteditable>US</td>
<td contenteditable>50000.000000000</td>
<td contenteditable>.000000000</td>
</tr>
</tbody>
</table>
<br/>
</body>
</html>
Here's the Page that is supposed to allow me to edit the data from the table in the first page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>FormToEditMaterial</title>
<link rel="StyleSheet" href="StyleSheet.css" type="text/css">
</head>
<body>
<table id="FormToEditMaterialTable">
<tr>
<th contenteditable="false" >Field Name</th>
<th contenteditable="false">Field to be edited</th>
</tr>
<tr contenteditable>
<td id="TempIDColumn" contenteditable="false">Name of Field</td>
<td>Data to be updated</td>
</tr>
<tr contenteditable>
<td id="NameColumn" contenteditable="false">Name of field 2</td>
<td>Data 2 to be updated</td>
</tr>
<tr contenteditable>
<td id="CountryCodeColumn" contenteditable="false">Name of field 3</td>
<td>Data 3 to be updated</td>
</tr>
<tr contenteditable>
<td id="BudgetColumn" contenteditable="false">Name of field 4</td>
<td>Data 4 to be updated</td>
</tr>
<tr contenteditable>
<td id="UsedColumn" contenteditable="false">Name of field 5</td>
<td>Data 5 to be updated</td>
</tr>
</table>
<br/>
<input type="button" name="SubmitUpdate" class="ok" value="Submit Update"/>
</body>
</html>
I've seen where people use forms and $POST to get the data from one page to another, but I'm not using a form. I'm actually using PHP and this is the resulting HTML and what is being pulled from the SQL server. However, I just need help with getting this working in HTML, I will figure out how to translate it into the PHP. Here is what the files look like that I'm working with:
JSFiddle TestingPHP - First Table
JSFiddle FormToEditMaterial - Second Table
If you need more info let me know and I'll provide what ever I can.
Edit
Here's the updated FormToEditMaterial file, I did not update the JSFiddle:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>FormToEditMaterial</title>
<link rel="StyleSheet" href="StyleSheet.css" type="text/css">
</head>
<body>
<table id="FormToEditMaterialTable">
<tr>
<th contenteditable="false" >Field Name</th>
<th contenteditable="false">Field to be edited</th>
</tr>
<tr contenteditable>
<td id="TempIDColumn" contenteditable="false">Name of Field</td>
<td>Data to be updated</td>
</tr>
<tr contenteditable>
<td id="NameColumn" contenteditable="false">Name of field 2</td>
<td>Data 2 to be updated</td>
</tr>
<tr contenteditable>
<td id="CountryCodeColumn" contenteditable="false">Name of field 3</td>
<td>Data 3 to be updated</td>
</tr>
<tr contenteditable>
<td id="BudgetColumn" contenteditable="false">Name of field 4</td>
<td>Data 4 to be updated</td>
</tr>
<tr contenteditable>
<td id="UsedColumn" contenteditable="false">Name of field 5</td>
<td>Data 5 to be updated</td>
</tr>
</table>
<br/>
<input type="button" name="SubmitUpdate" class="ok" value="Submit Update"/>
<br/>
<br/>
<form>
TempID: <input type="text" name="1"><br>
Name: <input type="text" name="2"><br>
CountryCode: <input type="text" name="3"><br>
Budget: <input type="text" name="4"><br>
Used: <input type="text" name="5"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
EDIT 2
Here's the new FormToEditMaterial.php:
<?php
$servername = "ServerName";
$username = "User";
$password = "Password";
$dbname = "DBName";
$db = new PDO("sqlsrv:server=$servername;database=$dbname", $username,$password);
$row = array();
if (isset($_POST['submit']))
{
$row = $_POST;
$q = 'UPDATE dbo.MyTable SET Name = ?, CountryCode = ?, Budget = ?, Used = ? WHERE TempID = ?';
$sth = $db->prepare($q);
$sth->execute(array($row['Name'], $row['CountryCode'], $row['Budget'], $row['Used'], $row['TempID']));
print_r($db->errorInfo());
echo "<br>";
var_dump($sth);
echo "<br>";
var_dump($row);
if ($sth->rowCount() == 1) header('Location: Index.php');
}
else if (!empty($_GET['id']))
{
$q = 'SELECT TempID, Name, CountryCode, Budget, Used FROM MyTable WHERE TempID = ?';
$sth = $db->prepare($q);
$sth->execute(array($_GET['id']));
$row = $sth->fetch();
}
else
{
// Show error message here
}
?>
<link rel="StyleSheet" href="stylesheet.css" type="text/css">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<p>
<label>TempID:
<input type="text" name="TempID" value="<?php echo $row['TempID']?>"></label>
</p>
<p>
<label>Name:
<input type="text" name="Name" value="<?php echo $row['Name']?>"></label>
</p>
<p>
<label>CountryCode:
<input class="CountryCode" type="text" name="CountryCode" value="<?php echo $row['CountryCode']?>"></label>
</p>
<p>
<label>Budget:
<input type="text" name="Budget" value="<?php echo $row['Budget']?>"></label>
</p>
<p>
<label>Used:
<input type="text" name="Used" value="<?php echo $row['Used']?>"> </label>
</p>
<p>
<input type="submit" name="submit" value="Submit">
</p>
</form>
And here's the Index.php:
<?php
$servername = "ServerName";
$username = "User";
$password = "Password";
$dbname = "DBName";
$db = new PDO("sqlsrv:server=$servername;database=$dbname", $username,$password);
$q = 'SELECT TempID, Name, CountryCode, Budget, Used FROM MyTable';
?>
<link rel="StyleSheet" href="stylesheet.css" type="text/css">
<table>
<thead>
<tr>
<th>Edit</th>
<th>TempID</th>
<th>Name</th>
<th>CountryCode</th>
<th>Budget</th>
<th>Used</th>
</tr>
</thead>
<tbody>
<?php foreach ($db->query($q) as $row) :?>
<tr>
<td>Edit</td>
<td><?php echo $row['TempID']?></td>
<td><?php echo $row['Name']?></td>
<td><?php echo $row['CountryCode']?></td>
<td><?php echo $row['Budget']?></td>
<td><?php echo $row['Used']?></td>
</tr>
<?php endforeach?>
</tbody>
</table>
I've made a quick example:
In index.php:
<?php
$db = new PDO('host', 'username', 'password');
$q = 'SELECT TempID, Name, CountryCode, Budget, Used FROM MyTable';
?>
<table>
<thead>
<tr>
<th>Edit</th>
<th>TempID</th>
<th>Name</th>
<th>CountryCode</th>
<th>Budget</th>
<th>Used</th>
</tr>
</thead>
<tbody>
<?php foreach ($db->query($q) as $row) :?>
<tr>
<td>Edit</td>
<td><?php echo $row['TempID']?></td>
<td><?php echo $row['Name']?></td>
<td><?php echo $row['CountryCode']?></td>
<td><?php echo $row['Budget']?></td>
<td><?php echo $row['Used']?></td>
</tr>
<?php endforeach?>
</tbody>
</table>
In FormToEditMaterial.php:
<?php
$db = new PDO('sqlite:db.sqlite3');
$row = array();
if (isset($_POST['submit']))
{
$row = $_POST;
$q = 'UPDATE MyTable SET Name = ?, CountryCode = ?, Budget = ?, Used = ? WHERE TempID = ?';
$sth = $db->prepare($q);
$sth->execute(
array($row['Name'], $row['CountryCode'], $row['Budget'], $row['Used'], $row['TempID'])
);
if ($sth->rowCount() == 1) header('Location: index.php');
}
else if (!empty($_GET['id']))
{
$q = 'SELECT TempID, Name, CountryCode, Budget, Used FROM MyTable WHERE TempID = ?';
$sth = $db->prepare($q);
$sth->execute(array($_GET['id']));
$row = $sth->fetch();
}
else
{
// Show error message here
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<p>
<label>TempID:
<input type="text" name="TempID" value="<?php echo $row['TempID']?>"></label>
</p>
<p>
<label>Name:
<input type="text" name="Name" value="<?php echo $row['Name']?>"></label>
</p>
<p>
<label>CountryCode:
<input type="text" name="CountryCode" value="<?php echo $row['CountryCode']?>"></label>
</p>
<p>
<label>Budget:
<input type="text" name="Budget" value="<?php echo $row['Budget']?>"></label>
</p>
<p>
<label>Used:
<input type="text" name="Used" value="<?php echo $row['Used']?>"></label>
</p>
<p>
<input type="submit" name="submit" value="Submit">
</p>
</form>
This example doesn't include any error checking whatsoever.
Ajax is a good solution for your problem, because you won't need to jump to a secondary page, not even refresh the page! Next code is an example and it works like this:
Every row in the HTML table has one button to save changes.
The click event of every button calls the ajax function with the data values.
The ajax function calls "update.php" with the data values as POST parameters.
"update.php" gets the data as $_POST values and updates the database record.
"update.php" sends a success message back to the ajax function to display it.
In order to test it, create two files with the given names, copy-paste next codes and run! (You don't need anything else but those codes).
main.php
<html>
<head>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type="text/javascript">
//--------------------------------------------------
function myAjax ( id )
{ if ( ! confirm( "Save data for id=" + id + " ?" ) )
return;
$.ajax( { type : 'POST',
url : 'update.php',
data : { 'id' : id,
'name' : $("#name"+id).val(), // VALUE FROM EDIT FIELD.
'phone' : $("#phone"+id).val(), // VALUE FROM EDIT FIELD.
},
success : function ( result )
{ alert( result ); },
error : function ( xhr )
{ alert( "error" ); }
}
);
}
//--------------------------------------------------
</script>
</head>
<body>
<table>
<tr><td>NAME</td>
<td>PHONE</td>
<td></td>
</tr>
<?php
//--------------------------------------------------
// SAMPLE DATA.
$database = Array( Array( "id" => "1",
"name" => "Mike",
"phone" => "123" ),
Array( "id" => "2",
"name" => "Midas",
"phone" => "456" ),
Array( "id" => "3",
"name" => "Jay",
"phone" => "789" )
);
$i = 1;
foreach ( $database as $row ) // DISPLAY "DATABASE" ROWS.
{ echo "<tr><td><input type='text' id='name" . $row["id"] .
"' value='" . $row["name"] . "'/></td>\n" .
" <td><input type='text' id='phone" . $row["id"] .
"' value='" . $row["phone"] . "'/></td>\n" .
" <td><button onclick='myAjax(\"" . $row["id"] .
"\")'>Save changes</button></td>\n" .
"</tr>";
$i++;
}
//--------------------------------------------------
?>
</table>
</body>
</html>
update.php
<?php
// CHECK IF VALUES ARE COMING FROM AJAX.
if ( isset( $_POST[ "id" ] ) &&
isset( $_POST[ "name" ] ) &&
isset( $_POST[ "phone" ] ) )
{ // "update my_table set name=$_POST[ "name" ],
// phone=$_POST[ "phone" ]
// where id=$_POST[ "id" ]
echo "Record " . $_POST[ "id" ] . " updated with " .
$_POST[ "name" ] . " and " . $_POST[ "phone" ];
}
?>
Oops! Just fixed one little problem, ready to run!
If you right-click the webpage to see the code, you will notice the input fields have the ids "name1", "name2", ..., and "phone1", "phone2", .... This method gives every textbox a unique id (necessary for ajax function to get the value entered by user and send it to PHP). The code in charge of this is :
id='name" . $row["id"] .
"' value=
When I use the sql UPDATE query, it only affects the first row of my members.
<?php
$query = mysqli_query($db, "SELECT * FROM `members` ORDER BY `siteRank`");
$result = mysqli_fetch_assoc($query);
?>
<?php
if($_POST['AccountUpdate'])
{
//mysqli_query($db, "UPDATE members SET username='$Username' WHERE id='$$IdentifcationNumber' ORDER BY id DESC LIMIT 1");
echo $result['id'];
echo $result['username'];
echo 'separeator';
echo $IdentifcationNumber;
}
?>
<form method="post" action="viewprofile.php">
<table border="1px">
<tr>
<th>ID</th>
<th>Username</th>
<th>Password</th>
<th>Email</th>
<th>Browser</th>
<th>IP</th>
<th>Site Rank</th>
<th>PyroCoins</th>
<th>PIN</th>
<th>Status</th>
<th>Date Joined</th>
<th>Update Account</th>
</tr>
<?php
while($result = mysqli_fetch_assoc($query)){
?>
<form method="post" action="viewprofile.php">
<tr>
<td><input readonly="readonly" value="<?php echo $result['id'];?>" /></td>
<td><?php echo $result['username'];?></td>
<td><input text="text" name="ChangePassword" value="<?php echo $result['password'];?>" /></td>
<td><?php echo $result['email'];?></td>
<td><?php echo $result['browser'];?></td>
<td><?php echo $result['ip'];?></td>
<td><?php echo $result['siteRank'];?></td>
<td><input type="text" name="ChangePyroCoins" value="<?php echo $result['PyroCoins'];?>" /></td>
<td><?php echo $result['pin'];?></td>
<td>
Current Status:
<input readonly="readonly" value="<?php echo $result['status'];?>" />
<select name="ChangeStatus">
<option value="<?php echo $result['status'];?>"><?php echo $result['status'];?></option>
<option value="[ Content Deleted ]">[ Content Deleted ]</option>
</select>
</td>
<td><?php echo $result['date'];?></td>
<td><input type="submit" name="AccountUpdate" value="Update Account"></td>
</tr>
<?php
}
?>
</table>
</form>
My $_POST data should be self explanatory, but its only affecting the first row and not the row that Im trying to affect. When I click my html update button, it only displays only the first ID and not the ID or the account credentials that i'm trying to update. For example, When I try to edit somes details with an ID of 28, it affects the first table ID which is 1
'ORDER BY id DESC LIMIT 1' in the query is unnecessary.
UPDATE members SET username='$Username' WHERE id='$IdentifcationNumber'
#Isaak Markopoulos - this is not tested but there are no nested forms so hopefully there should be less confusion when posting the form. The id field in the html has been named so at least there should be an id available in the posted vars
<html>
<head>
<title>crazy little monkey</title>
</head>
<body>
<?php
/* This only gets executed if it is a POST request */
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['AccountUpdate'] ) && isset( $_POST['IdentifcationNumber'] ) ){
/* I assume this is the correct id - there was no name for the form element previously */
$IdentifcationNumber=$_POST['IdentifcationNumber'];
$sql="UPDATE members SET username='$Username' WHERE id='$IdentifcationNumber';";
mysqli_query( $db, $sql );
echo $result['id'];
echo $result['username'];
echo 'separeator';
echo $IdentifcationNumber;
}
/* This gets executed for any request */
$query = mysqli_query( $db, "SELECT * FROM `members` ORDER BY `siteRank`;" );
$result = mysqli_fetch_assoc( $query );
?>
<!-- parent table -->
<table border="1px">
<tr>
<th>ID</th>
<th>Username</th>
<th>Password</th>
<th>Email</th>
<th>Browser</th>
<th>IP</th>
<th>Site Rank</th>
<th>PyroCoins</th>
<th>PIN</th>
<th>Status</th>
<th>Date Joined</th>
<th>Update Account</th>
</tr>
<tr>
<td colspan=12>
<!-- begin a form / table for each row in rs -->
<?php
$rc=0;
while( $result = mysqli_fetch_assoc( $query ) ){
$rc++;
echo "
<!-- unique name for each form - not essential -->
<form name='vpf_{$rc}' action='viewprofile.php' method='post'>
<!-- nested child table fully contained within it's parent form element -->
<table>
<td><input type='text' name='IdentifcationNumber' readonly='readonly' value='".$result['id']."' /></td>
<td>".$result['username']."</td>
<td><input text='text' name='ChangePassword' value='".$result['password']."' /></td>
<td>".$result['email']."</td>
<td>".$result['browser']."</td>
<td>".$result['ip']."</td>
<td>".$result['siteRank']."</td>
<td><input type='text' name='ChangePyroCoins' value='".$result['PyroCoins']."' /></td>
<td>".$result['pin']."</td>
<td>
Current Status:
<input readonly='readonly' value='".$result['status']."' />
<select name='ChangeStatus'>
<option value='".$result['status']."'>".$result['status']."
<option value='[ Content Deleted ]'>[ Content Deleted ]
</select>
</td>
<td>".$result['date']."></td>
<td><input type='submit' name='AccountUpdate' value='Update Account'></td>
</table>
</form>";
}/* Close the while loop - note that the form(s) is/are FULLY contained within the loop - NO nesting */
?>
</td>
</tr>
</table>
</body>
</html>
I am new to PHP(loving it already)
I have a form that looks up a table that sends 'golf hole' info back and allows a golfer to input their score of the hole. Problem I have is that I can present the first hole by looking up the hole_detail table but then cant figure out how loop through the table for hole 2, 3.....18 when the form is submitted. I have searched stackoverflow but cant find anything that specific about it. I have tried an if statement, if (isset($_POST['Submit'])) to try increment the $hole_id. Am I completely going about it the wrong way? Thanks in advance.
<?php
include ('../scripts/dbconfig.php');
# get the most recent course name:
$get_course_name = mysql_query("SELECT course_name FROM comp ORDER BY PID DESC LIMIT 1");
$show_course_name = mysql_fetch_array($get_course_name);
if (isset($_POST['Submit'])) {
$hole_id =1;
else {
$hole_id = $hole_id + 1;
}
}
# get the hole yardage and SI from most recent selected golf course:
$get_course_detail = mysql_query("SELECT * FROM `course_detail` WHERE course_name = '". $show_course_name['course_name'] . "'");
$show_course_detail = mysql_fetch_array($get_course_detail);
$get_hole_detail = mysql_query("SELECT * FROM `course_detail`,`phoenix_hole` WHERE Course_ID = 6 AND hole_id = $hole_id");
$show_hole_detail = mysql_fetch_array($get_hole_detail);
?>
</head>
<body>
<table width="300" cellspacing="0" cellpadding="0">
<tr>
<td width="40"><?php echo $show_course_name['course_name'];?></td>
</tr>
<tr>
<td width="20">HOLE <?php echo $show_hole_detail['hole_id']?></td>
<td width="5"> PAR <?php echo $show_hole_detail['hole_par'];?></td>
</tr>
<tr>
<td width="20">Yards</td>
<td width="20">S.I</td>
</tr>
<tr>
<td bgcolor="yellow"><?php echo $show_hole_detail['yellow_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
<tr>
<td border="1px" bgcolor="white"><?php echo $show_hole_detail['white_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
<tr>
<td bgcolor="red"><?php echo $show_hole_detail['red_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
</table>
</p>
<form id="game_form" name="game_form" method="post" action="game_form.php">
<table width="300" border="0" align="left" cellpadding="2" cellspacing="0">
<tr>
<td><b>Hole Shots</b></td>
<td><input name="hole_shots" type="text" class="textfield" id="hole_shots" maxlength="2" size="3" ></td>
<td><b>Putts</b></td>
<td><input name="putts" type="text" class="textfield" id="putts" maxlength="2" size="3"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Next Hole" align="center" /></td>
</tr>
</table>
</form>
</body>
</html>
Or you can use a hidden field that keeps the hole number and you can increment it from php.
$hole_id, in this scenario, will always be 1, because when a user clicks the Submit button, $_POST['Submit'] will always have a value. What you should do instead is have $_POST['Submit'] contain the value of $hole + 1. PHP is not going to "remember" what $hole_id was last time around; it's up to you to remind it. As soon as a request is sent to the browser--unless you're using sessions--PHP forgets everything about that request (HTTP is "stateless").
<?php
if (isset($_POST['Submit'])) {
$hole_id = (int)$_POST['Submit'];
} else {
$hole_id = 1;
}
# other code here
?>
You are on hole #<?php echo $hole_id; ?>.
<form>
<!-- form stuff here -->
<button type="submit" name="Submit" value="<?php echo $hole_id + 1; ?>">Next hole</button>
</form>