I have a script that displays all the values in a db table. I'd like to be able to update the price value of each row individually on clicking the update button but as it's in a while loop it's only updating the final value successfully. I realise this probably requires foreach but I can't figure where to code it within the loop to send the data from each row to the processing script on the next page. Can anyone help? Thank you!
Display script
<h2>Boiler Prices</h2>
<?php
$sql = "SELECT * FROM emb_prices_boilers ORDER BY id ASC";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
/* Start Form and Table ---------------------------------------------------------*/
echo "<form action='../admin/actions/set-boiler-price.php' method='post'>";
echo "<table id='boiler-prices'>
<tr>
<th>ID</th>
<th>Type</th>
<th>Boiler</th>
<th>Ref</th>
<th>Price</th>
</tr>";
/* Start Loop and Variables --------------------------------------------*/
while($row = $result->fetch_assoc()) {
$id = $row["id"];
$type = $row["type"];
$manufacturer = $row["manufacturer"];
$model = $row["model"];
$boilerref = $row["boilerref"];
$price = $row["price"];
// output data of each row
echo "
<tr>
<td>" .$id. "</td>
<td>" .$type. "</td>
<td>" .$manufacturer. " " .$model. "</td>
<td>" .$boilerref. "</td>
<td>£<input type='text' name='price' value='" .$price. "' /><input type='hidden' name='boilerref' value='" .$boilerref. "' /><input type='submit' value='update' /></td>
</tr>";
}
/* End Loop -------------------------------------------------------*/
echo "</table>";
echo "</form>";
/* End Table and Form -------------------------------------------------------*/
}
else {
echo "0 results";
}
?>
Processing script
<?php
$boilerref = $_POST['boilerref'];
$price = $_POST['price'];
if ($setboilerprice = mysqli_prepare($connection, "UPDATE emb_prices_boilers SET price = ? WHERE boilerref = ?")
) {
/* bind parameters for markers */
mysqli_stmt_bind_param($setboilerprice, "ds", $price, $boilerref );
/* execute query */
mysqli_stmt_execute($setboilerprice);
/* close statement */
mysqli_stmt_close($setboilerprice);
}
else {
echo "error: Failed to write to db";
}
?>
What you need is to create a separate form for each record. Remove <form>/</form> tags from the beginning and the end of <table> and use this code in your last td:
echo "
...
<td>
<form action='../admin/actions/set-boiler-price.php' method='post'>
£<input type='text' name='price' value='" .$price. "' />
<input type='hidden' name='boilerref' value='" .$boilerref. "' />
<input type='submit' value='update' />
</form>
</td>
</tr>";
With such mark up each form will send it's own data to your set-boiler-price.php and updating will work as you expect.
Related
I have php table and a form field inside the table, that displays the status of some devices. I am displaying values like Date, Voltage, Current. user can choose any value so that the time corresponding to selected value will be used in the next page for average calculation. For average calculation I should choose immediate 5 values to the selected value. so time value from Date column is important (eg. 2019-04-17 16:14:44). The problem is when i am using hidden form value field, I am getting only date (eg. 2019-04-17) not 'time' .
form.php
$sql = "SELECT Date, Voltage, Current FROM DataTable WHERE Date>= (CURDATE() - INTERVAL 90 DAY) ORDER BY Datum DESC";
$result = $conn->query($sql);
$i=1;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<form action = 'formProcess.php' method =get>";
echo "<tr>
<td>" . $i. "</td>
<td>" . $row["Date"]. "</td>
<td>" . $row["Voltage"] . "</td>
<td>" . $row["Current"]. "</td>
<td>"." <input type=hidden name=getTime value =" .$row["Date"]." </td>
<td>"." <input type=submit name=timesubmit value=select class = classSubmit"." </td>
</tr>";
$i++;
echo "</form>";
}
echo "</table>";
} else { echo "0 results"; }
formProcess.php
include("DBconnect.php");
if(isset ($_GET['timesubmit'])){
echo "selected a value";
$selectedTime =$_GET['getTime'];
// the following echo only gives date, not time !! that is the problem.
echo $selectedTime;
// I wanna use the immediate 5 value, that selected value and immediate 4 values for avg calculation.
$sql = "SELECT * FROM DataTable
WHERE date =>$selectedTime AND ORDER BY Date DESC LIMIT 5 ";
$conn= mysqli_connect( $dbhost, $dbuser, $dbpass, $db );
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result_5_values = $conn->query($sql);
$i=1;
if ($result_5_values->num_rows > 0) {
while($row = $result_10_values->fetch_assoc()) {
echo "<tr>
<td>" . $i. "</td>
<td>" . $row["Date"]. "</td>
<td>" . $row["Voltage"] . "</td>
<td>" . $row["Current"]. "</td>
</tr>";
$i++;
}
echo "</table>";
} else { echo "0 results"; }
}else { echo "No selection has been made";}
Try this
$sql = "SELECT Date, Voltage, Current FROM DataTable WHERE Date>= (CURDATE() - INTERVAL 90 DAY) ORDER BY Datum DESC";
$result = $conn->query($sql);
$i=1;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<form action='formProcess.php' method ='get'>";
echo "<tr>
<td>" . $i. "</td>
<td>" . $row["Date"]. "</td>
<td>" . $row["Voltage"] . "</td>
<td>" . $row["Current"]. "</td>
<td>"." <input type='hidden' name='getTime' value='" .$row["Date"]."' /></td>
<td>"." <input type='submit' name='timesubmit' value='select' class='classSubmit'"." </td>
</tr>";
$i++;
echo "</form>";
}
echo "</table>";
} else { echo "0 results"; }
The issue is that the you didn't quote the value of the date, all element attribute value should be quoted. I'm expecting in the web source code of this would look like:
<input type=hidden name=getTime value=2019-04-17 16:14:44>
It should look like this
<input type="hidden" name="getTime" value="2019-04-17 16:14:44">
Input tag is not closed
<input type=hidden name=getTime value =" .$row["Date"]." </td>
it should be
<input type=hidden name=getTime value =" .$row["Date"]."/> </td>
As you have no html quotes, this will give you just the date for value. Have a look at the created html code (you can see that the syntax highlighter of stackoverflow already highlights how the browser sees your html):
<input type=hidden name=getTime value=2019-04-17 16:14:44>
You should add additional quotes for HTML inside PHPs echo:
echo ' <input type="hidden" name="getTime" value="' . $row["Date"] . '" />';
... to create a valid html output:
<input type="hidden" name="getTime" value="2019-04-17 16:14:44" />
To overcome this problem, I would advice you to use single quotes ' for php and " for html. This also has some performance improvements on the php side, but it should not influence your code that much ... ;)
I'm trying to make a HTML table as a frontend to a mySQL database. The table displays fine and I can type in the edits I want to make to each row of the table but when I press the submit button the changes aren't actually made. Can anyone see where I'm going wrong?
<?php
include("db.php");
$sql = "SELECT * FROM `artist`";
$result = mysqli_query($conn, $sql);
if (isset($_POST['update'])){
$artID = $_POST['artID'];
$artName = $_POST['artName'];
$key = $_POST['hidden'];
$UpdateQuery = "UPDATE `artist` SET `artID` = '$artID', `artName` = '$artName' WHERE `artist`.`artID` = '$key'";
mysqli_query($conn,$UpdateQuery);
header("Location: {$_SERVER['HTTP_REFERER']}");
exit;
};
echo "<table border='1'>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Name</th>";
echo "</tr>";
if ($result->num_rows > 0) {
echo "<form id ='artisttable' action ='getartiststable.php' method ='post'>";
// output data of each row
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" ."<input type='text' name ='artID' value ='" . $row['artID'] . "' </td>";
echo "<td>" . "<input type='text' name ='artName' value ='" . $row["artName"] . "' </td>";
echo "<td>" . "<input type = 'hidden' name ='hidden' value='" . $row['artID'] . "' </td>";
echo "<td>" . "<input type='submit' name ='update'" . " </td>";
echo "</tr>";
}
echo "</form>";
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
The db.php file simply includes the connection info to the mySQL database and I'm 100% sure there's nothing wrong with it as it retrieves the table correctly it just doesn't update.
You are putting form tag inside tr which is not allowed td are only allowed
so you have to remove that tr from there.
You have to use jquery or you can replace the table with some other grid structure so that it can look the same and the form can be placed there as well
One more suggestion Don't mix the php and html together separate them for the clean code
If you do all these you code will be like this
Your form is being constructed with multiple elements with the same name. When you submit the form it is using the last elements as the values so regardless of the record you want updated the last record is being updated (or throwing an error because of string encapsulation). You should use parameterized queries as well.
So instead of:
if ($result->num_rows > 0) {
echo "<form id ='artisttable' action ='getartiststable.php' method ='post'>";
// output data of each row
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" ."<input type='text' name ='artID' value ='" . $row['artID'] . "' </td>";
echo "<td>" . "<input type='text' name ='artName' value ='" . $row["artName"] . "' </td>";
echo "<td>" . "<input type = 'hidden' name ='hidden' value='" . $row['artID'] . "' </td>";
echo "<td>" . "<input type='submit' name ='update'" . " </td>";
echo "</tr>";
}
echo "</form>";
echo "</table>";
Use:
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_array($result)) {?>
<form class='artisttable' action ='getartiststable.php' method ='post'>
<tr>
<td><input type='text' name ='artID' value ='<?php echo $row['artID'];?>' /></td>
<td><input type='text' name ='artName' value ='<?php echo $row["artName"];?>' /></td>
<td><input type = 'hidden' name ='hidden' value='<?php echo $row['artID'];?>' /></td>
<td><input type='submit' name ='update'" . " </td>
</tr>
</form>
<?php } ?>
</table>
So you get a form for each data set. Here's a link on prepared statements with mysqli: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php. You also should update your mark up. Tables for formatting aren't the best approach. Your inputs also weren't closed missing >.
Also this changed artisttable from an id to class because there will be multiples. Update CSS/JS accordingly.
I am creating a webpage that is similar to a points system. It consists of a table with name and points columns. The user inputs a number, which then adds that value to the existing number in the table. My question is how would I be able to add those two values and update the table(database)?
<?php
$con = mysql_connect("xxx, xxx, xxx);
if (!$con) {
die("can not connect:" . mysql_error());
}
mysql_select_db("points", $con);
if(isset($_POST['update'])){
$UpdateQuery = "UPDATE coach_tbl set coachscore = coachscore + '$add' WHERE coach_score = '$_POST[hidden]'";
mysql_query($UpdateQuery, $con);
};
if (isset($_POST['submit'])){
$AddQuery = "INSERT INTO coach_tbl (coach_name, coach_score) VALUES('$_POST[name]', '$_POST[score]')";
mysql_query($AddQuery, $con);
};
$sql = "SELECT * FROM coach_tbl ORDER BY coach_score DESC";
echo "<table border=1>
<tr>
<th>NAME</th>
<th>Score</th>
</tr>";
$myData = mysql_query($sql, $con);
while($record = mysql_fetch_array($myData)) {
echo "<form action=index.php method=post>";
echo "<tr>";
echo "<td><input type=text name=coachname value='" . $record['coach_name'] . "'> </td>";
echo "<td><input type=text name=coachscore value='" . $record['coach_score'] . "'> </td>";
echo "<td><input type=hidden name=hidden value='" . $record['coach_score'] . "'> </td>";
echo "<td><input type=submit name=update value=update'" . "'> </td>";
echo "<td><input type=number min="1" max="10" name=add value=add'" . "'> </td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysql_close($con);
?>
If there are any questions I will gladly elaborate on anything. I am also fairly new to php.
Let's say you have an html form like so:
<form action="update.php" method="POST">
<input type="number" name="updateData" value=""/>
<input type="submit">
</form>
and an update.php:
<?php
//assuming you want 1-10 points max to be added each time
if( isset($_POST['updateData']) && $_POST['updateData'] >=1 && $_POST['updateData'] >=10){
//set to user inputed value
$insertData = $_POST['updateData'];
$sql = "UPDATE point_table SET points = points + $insertData WHERE id = 1";
//you will need to finish off the query by checking connecting with your database.
}
?>
How do I retrieve data from a SQL table, modify the data and store it in another database table with multiple rows & columns and with single submit button I want insert every rows at a time I don't know how to get that hidden value and work properly with that
<?php
include"connect_database.php";
if(isset($_POST['submit'])) {
$amt = $_POST['total'];
if($amt > 0) {
$qry = "INSERT INTO attendance(rollno, name, year, attendance, reason) VALUES "; // Split the mysql_query
for($i=1; $i<=$amt; $i++) {
$qry .= "('".$_POST["rollno$i"]."', '".$_POST["name$i"]."', '".$_POST["year$i"]."', '".$_POST["attendance$i"]."', '".$_POST["reason$i"]."' ),"; // loop the mysql_query values to avoid more server loding time
}
$qry = substr($qry, 0, strlen($qry)-2);
$insert = mysqli_query($dbcon, $qry); // Execute the mysql_query
}
// Redirect for each cases
if($insert) {
$msg = '<script type="text/javascript">alert("added");</script>';
}
else {
$msg = '<script type="text/javascript">alert("Server Error, Kindly Try Again");</script>';
}
};
if (isset($_POST['select']))
{
$sql = "SELECT * FROM data WHERE year='" . $_POST['yr'] . "'";
$myData = mysqli_query($dbcon, $sql);
$num = mysqli_num_rows($myData);
echo "<table border=1>
<tr>
<th>Rollno</th>
<th>Name</th>
<th>Year</th>
<th>Attendance</th>
<th>reason</th>
</tr>";
for ($i=0; $i <$num; $i++)
{
$record = mysqli_fetch_array($myData);
echo "<form action=smanage.php method=post>";
echo "<tr>";
echo "<td>" . "<input type=text name=rollno$i value=" . $record['rollno'] . " </td>";
echo "<td>" . "<input type=text name=name$i value=" . $record['name'] . " </td>";
echo "<td>" . "<input type=text name=year$i value=" . $record['year'] . " </td>";
echo "<td> "."<select name=attendance$i >
<option value=Present >present</option>
<option value=Absent >Absent</option>
</select>"."</td>";
echo "<td>". "<textarea cols=15 rows=2 name=reason$i placeholder=Enter reason ...></textarea>" . "</td>" ;
echo "<td>" . "<input type=hidden name=total value=" . $i-1 . "</td>";
echo "</tr>";
}
echo"</table>";
echo "<input type=submit name=submit value=save class=Button3>";
echo "</form>";
};
mysqli_close($dbcon);
?>
you are opening multiple forms, for each row in your table on.
This causes your html to be invalid, just start the form before displaying the table.
You could use this html
<table>
<?php
for ($i = 0; $i < $num; $i++) {
$record = mysqli_fetch_array($myData);
?>
<tr>
<td><input type="text" name="rollno[<?= $record['rollno'] ?>]" value="<?= $record['rollno'] ?>" </td>
<td><input type="text" name="name[<?= $record['rollno'] ?>]" value="<?= $record['name']?>" </td>
<td><input type="text" name="year[<?= $record['rollno'] ?>]" value="<?= $record['year'] ?>" </td>
<td><select name="attendance[<?= $record['rollno'] ?>]" >
<option value="Present" >present</option>
<option value="Absent" >Absent</option>
</select></td>
<td><textarea cols="15" rows="2" name="reason[<?= $record['rollno'] ?>]" placeholder="Enter reason ..."></textarea></td>
</tr>
<?php
}
?>
</table>
with this your values will every row will be put into the $_POST-Array, you can access the values via the indexes (I am guessing rollno represents the ID of the dataset).
When you really only want to insert all the values into a table, you can leave the index out. Meaning you could write
<td><input type="text" name="rollno[]" value="<?= $record['rollno'] ?>" </td>
Instead of
<td><input type="text" name="rollno[<?= $record['rollno'] ?>]" value="<?= $record['rollno'] ?>" </td>
You don't need the hidden field, you can just count the items in the array.
$total = count($_POST['rollno']);
<?php
include"connect_database.php";
if(isset($_POST['submit'])) {
$amt = $_POST['total'];
$rollnos= $_POST['rollno'];
if($amt > 0) {
$qry = "INSERT INTO attendance(rollno, name, year, attendance, reason) VALUES "; // Split the mysql_query
$i=0;
foreach($rollnos as $rollno) {
$qry .= "('".$rollno."', '".$_POST["name"][$i]."', '".$_POST["year"][$i]."', '".$_POST["attendance"][$i]."', '".$_POST["reason"][$i]."' ),"; // loop the mysql_query values to avoid more server loding time
$i=$i+1;
}
$qry = substr($qry, 0, strlen($qry)-2);
$insert = mysqli_query($dbcon, $qry); // Execute the mysql_query
}
// Redirect for each cases
if($insert) {
$msg = '<script type="text/javascript">alert("added");</script>';
}
else {
$msg = '<script type="text/javascript">alert("Server Error, Kindly Try Again");</script>';
}
};
if (isset($_POST['select']))
{
$sql = "SELECT * FROM data WHERE year='" . $_POST['yr'] . "'";
$myData = mysqli_query($dbcon, $sql);
$num = mysqli_num_rows($myData);
echo "<table border=1>
<tr>
<th>Rollno</th>
<th>Name</th>
<th>Year</th>
<th>Attendance</th>
<th>reason</th>
</tr>";
for ($i=0; $i <$num; $i++)
{
$record = mysqli_fetch_array($myData);
echo "<form action=smanage.php method=post>";
echo "<tr>";
echo "<td>" . "<input type='text' name='rollno[]' value='" . $record['rollno'] . "'> </td>";
echo "<td>" . "<input type='text' name='name[]' value='" . $record['name'] . "'> </td>";
echo "<td>" . "<input type='text' name='year[]' value='" . $record['year'] . "'> </td>";
echo "<td> "."<select name='attendance[]' >
<option value='Present' >present</option>
<option value='Absent' >Absent</option>
</select>"."</td>";
echo "<td>". "<textarea cols='15' rows='2' name='reason[]' placeholder='Enter reason ...'></textarea>" . "</td>" ;
echo "<td></td>";
echo "</tr>";
}
echo "<input type='hidden' name='total' value='" . $i-1 . "'>";
echo"</table>";
echo "<input type='submit' name='submit' value='save' class='Button3'>";
echo "</form>";
};
mysqli_close($dbcon);
?>
I've got a page where I render a table of values from Mysql using PHP and HTML.
I want to delete rows checked with a checkbox upon clicking a delete button. Unfortunately, nothing happens when clicking the button and I'm at a total loss as to where to look.
Code is below (database connection has been omitted, but it works).
<body>
<?php
$delete = $_POST['checkbox'];
$query = "SELECT * FROM Cards";
$result = mysql_query($query);
echo "<table>";
echo "<tr><td>Name</td><td>Quantity</td><td>Color</td><td>Type</td></tr>";
while ($row = mysql_fetch_array($result)){
echo "<tr><td><input type='checkbox' name='checkbox[]" . $row['id'] . "]'></td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Quantity'] . "</td>";
echo "<td>" . $row['Color'] . "</td>";
echo "<td>" . $row['CardType'] . "</td></tr>";
}
mysql_free_result($result);
echo "</table>";
?>
</body>
<tr>
<td colspan="5" align="center"><input name="delete" type="SUBMIT" id="delete" value="delete" action="POST"></td>
</tr>
<?php
if (isset($_POST['delete'])) {
$checkbox = $_POST['checkbox'];
$count = count($checkbox);
for($i = 0; $i < $count; $i++) {
$id = (int) $checkbox[$i]; // Parse your value to integer
if ($id > 0) { // and check if it's bigger then 0
mysql_query("DELETE FROM Cards WHERE id = $id");
}
}
}
?>
<?php include "../footer.htm";?>
Try this:
<body>
<?php
$connect=mysqli_connect("Host","Username","Password","Database"); /* REPLACE NECESSARY DATA */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
if (isset($_POST['delete'])){
$checkbox = $_POST['checkbox'];
$count = count($checkbox);
for($i=0;$i<$count;$i++){
if(!empty($checkbox[$i])){ /* CHECK IF CHECKBOX IS CLICKED OR NOT */
$id = mysqli_real_escape_string($connect,$checkbox[$i]); /* ESCAPE STRINGS */
mysqli_query($connect,"DELETE FROM Cards WHERE id = '$id'"); /* EXECUTE QUERY AND USE ' ' (apostrophe) IN YOUR VARIABLE */
} /* END OF IF NOT EMPTY CHECKBOX */
} /* END OF FOR LOOP */
} /* END OF ISSET DELETE */
$query = "SELECT * FROM Cards"; /* SELECT FROM Cards TABLE */
$result = mysqli_query($connect,$query); /* EXECUTE QUERY */
echo "<form action='' method='POST'>"; /* SUBMIT PAGE ON ITSELF */
echo "<table>";
echo "<tr><td>Name</td><td>Quantity</td><td>Color</td><td>Type</td></tr>";
while ($row = mysqli_fetch_array($result)){ /* FETCH ARRAY */
$id=mysqli_real_escape_string($connect,$row['id']);
echo "<tr><td><input type='checkbox' name='checkbox[]' value='$id'></td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Quantity'] . "</td>";
echo "<td>" . $row['Color'] . "</td>";
echo "<td>" . $row['CardType'] . "</td></tr>";
}
mysqli_free_result($result);
echo "</table>";
?>
<tr>
<td colspan="5" align="center"><input name="delete" type="SUBMIT" id="delete" value="delete" action="POST"></td>
</tr>
</form>
<?php include "../footer.htm";?>
</body>
I've converted your code to MySQLi from the deprecated MySQL.
And used empty() function to determine a checked checkbox.
You forgot to put a <form> function for your html.
And also forgot to use value tag for your checkbox.
I have put explanations quoted in /* */ inside the code I have provided.
Try this:
<body>
<?php
$delete = $_POST['checkbox'];
$query = "SELECT * FROM Cards";
$result = mysql_query($query);
echo "<form method=post action=''>";
echo "<table>";
echo "<tr><td>Name</td>
<td>Quantity</td>
<td>Color</td>
<td>Type</td></tr>";
while ($row = mysql_fetch_array($result)){
$content .= <<< END
<tr>
<td><input type="checkbox" name="checkbox" value="{$row['id']}"></td>
<td>{$row['Name']}</td>
<td>{$row['Quantity']}</td>
<td>{$row['Color']}</td>
<td>{$row['CardType']}</td>
</tr>
END;
}
echo $content;
mysql_free_result($result);
?>
<tr>
<td colspan="5" align="center"><input name="delete" type="SUBMIT" id="delete" value="delete"></td>
</tr>
</table></form>
</body>
<?php
if (isset($_POST['delete'])) {
$checkbox = $_POST['checkbox'];
foreach($checkbox as $id) {
$id = (int) $id;
mysql_query("DELETE FROM Cards WHERE id = $id");
}
}
?>
<?php include "../footer.htm";?>