php mysql UPDATE command wont update - php

All the data is loaded into a table, each row as a button. Once the button has been pressed, the row has to be updated. But when I click on the button, nothing happens. The text box on the rows return to its original value... It is really starting to cheese me off
<!DOCTYPE html>
<head>
<title>Edit Students</title>
</head>
<?php
$user = 'root'; //Database username ("Root for xampp")
$pass = ''; //Database password ("empty for exampp")
$db = 'dragondrivingschooldb'; //Name of database
$con = new mysqli('localhost', $user, $pass, $db) or die("Unable to connect"); //Create new data connection ('name of host/server', user, password, database name)
if (isset($_POST['btnUpdate'])) { //Once Update button pressed perform this code
$updatequery = mysqli_query($con, "UPDATE booking SET FirstName='$_POST[txtfirstname]' WHERE BookingID='$_POST[txtid]' "); //excute UpDate Query
};
$sql = mysqli_query($con, "SELECT * FROM booking"); //Select All from Booking
//Create Headers for table
echo "<table border='1'>
<tr>
<th></th>
<th>Booking ID</th>
<th>First Name</th>
</tr>";
//Show Edit Form///////////////////////////////////////////////////////////////////////////////////////////////////
while($row = mysqli_fetch_array($sql)) { //Run sql code till there are no more rows to import
echo "<form action=EditStudent.php method=post>"; //Run update code at top of this page
//Populate table with query (sql)
echo "<tr>";
echo "<td> <input name=update type=submit value=update /> </td>"; //once press update row this button is apart of
echo "<td> <input type=text value=" . $row['BookingID'] . " name=txtid /> </td>";
echo "<td> <input type=text value=" . $row['FirstName'] . " name=txtfirstname /> </td>";
echo "</tr>";
}
echo "</table>";
echo "</form>";
mysqli_close($con); //Close connection
?>
</html>

I think that BookingID it is an integer, so your update line need to be:
$updatequery = mysqli_query($con, "UPDATE booking SET FirstName='" . $_POST['txtfirstname'] . "' WHERE BookingID=" . $_POST['txtid'] . ""); //excute UpDate Query
EDIT:
I tested your script and the problem was that you closed the form outside the while loop. Now its working
<!DOCTYPE html>
<head>
<title>Edit Students</title>
</head>
<?php
$user = 'root'; //Database username ("Root for xampp")
$pass = ''; //Database password ("empty for exampp")
$db = 'all_tests'; //Name of database
$con = new mysqli('localhost', $user, $pass, $db) or die("Unable to connect"); //Create new data connection ('name of host/server', user, password, database name)
if (isset($_POST['btnUpdate'])) { //Once Update button pressed perform this code
$updatequery = mysqli_query($con, "UPDATE test_1 SET FirstName='" . $_POST['txtfirstname'] . "' WHERE BookingID='" . $_POST['txtid'] . "'"); //excute UpDate Query
};
$sql = mysqli_query($con, "SELECT *FROM test_1"); //Select All from Booking
//Create Headers for table
echo "<table border='1'>
<tr>
<th></th>
<th>Booking ID</th>
<th>First Name</th>
</tr>";
//Show Edit Form///////////////////////////////////////////////////////////////////////////////////////////////////
while($row = mysqli_fetch_array($sql)) { //Run sql code till there are no more rows to import
echo "<form method=post>"; //Run update code at top of this page
//Populate table with query (sql)
echo "<tr>";
echo "<td> <input name='btnUpdate' type='submit' value='update' /> </td>"; //once press update row this button is apart of
echo "<td> <input type='text' value=" . $row['BookingID'] . " name='txtid' /> </td>";
echo "<td> <input type='text' value=" . $row['FirstName'] . " name='txtfirstname' /> </td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con); //Close connection
?>

at first check that $_POST[txtid] has value or not. and be sure that field name is correct or incorrect.

There are no input field in your html that has name btnUpdate. What I can see its name is update. Therefore your row:
if (isset($_POST['btnUpdate'])) {
would never be true

Related

How to delete a row in php?

I made from in php. When I select a class, for example I select the class9, it shows me the table of class9. I also have inserted a row in the table containing the delete button to delete the corresponding row. Now I want to delete a row buy clicking the button which is in the row. how can I do that?
First I choose a class from this option as in the image below ;The image from which we select the class
And then the corresponding table is going to be shown.
This is the image. When I click on the button, the corresponding row should be deleted.
<?php
include "connection.php";
?>
<!doctype html>
<html>
<head>
<title>KDR</title>
</head>
<body>
<table border="2px" width="50%" height="auto">
<tr>
<th>No</th>
<th>Name</th>
<th>F/Name</th>
<th>Age</th>
<th>Delete</th>
</tr>
<?php
$table = $_POST['formCountry'];
$sql = "SELECT * FROM $table";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td><form method='POST' ><input type='submit' name='deletestudent' value='Delete'/></form></td>";
echo "</tr>";
}
?>
</table>
</body>
Something like this. Maybe will need to adjust it a bit.
Your table button:
echo "<td><form method='POST' action="delete_row.php" ><input type='submit' name='deletestudent' value="'.$row['id'].'"/></form></td>";
In PHP (delete_row.php) you should do the following
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['id']) and is_numeric($_POST['id']))
{
$delete = $_POST['id']
$stmt = $conn->prepare("DELETE FROM YOURTABLENAME WHERE id = ?");
$stmt->bind_param('i', $delete);
$stmt->execute();
$stmt->close();
}
Note: Not tested and I'm using mysqli_* here.
Update: As #icecub suggested you can use also hidden field to get the ID
echo "<td>
<form method='POST' action='delete_row.php' >
<input type='hidden' name='deletestudent' value='".$row['id']."'/>
<input type='submit' value='Delete'/>
</form>
</td>";
This is how not to do , see the comments below , important !
Should be send the current id of the element , so when you click the button
get the element ID by $_GET['id'];
<td><a href='?id=".$row['id']."'>delete</a></td>
if (isset($_GET['id'])) {
//Throw query DELETE ... WHERE id = $_GET['id'];
}

PHP executes but doesnt execute SQL update correctly

I have a table which displays
-Staff ID (Primary Key)
-Staff Name
-Staff Position
All the data loads in to my grid, the grid has an update button witch should let me to update it but it returns original result after clicking update.
<html>
<head>
</head>
<body>
<?php
$conn = mysql_connect("localhost", "root", "");
if (!$conn){
die("Can not connect: " . mysql_error());
}
mysql_select_db("pizza_shop",$conn);
if (isset($_POST['submit']) && $_POST['submit'] == 'update'){
$UpdateQuery = "UPDATE staff SET StaffName='$_POST[staffname]', Position='$_POST[staffposition]' WHERE StaffID='$_POST[hiddenid]'";
mysql_query($UpdateQuery);
}
$sql = "SELECT * FROM staff";
$myData = mysql_query($sql, $conn);
echo "<table border=1>
<tr>
<th>Staff Name<th>
<th>Staff Position<th>
</tr>";
while($record = mysql_fetch_array($myData)){
echo "<form action=#edit_staff.php method=post>";
echo "<tr>";
echo "<td>" . "<input type=text name =staffname value=" . $record['StaffName'] ." </td>";
echo "<td>" . "<input type=text name =staffposition value=" . $record['Position'] ." </td>";
echo "<td>" . "<input type=hidden name=hiddenid value=" . $record['StaffID'] . "</td>";
echo "<td>" . "<input type=submit name = update values=Update" . "</td>";
echo "</form>";
}
echo "</table>";
$conn = null;
?>
</body>
</html>
You need to change your update query from
$UpdateQuery = "UPDATE staff SET StaffName='$_POST[staffname]', Position='$_POST[staffposition]' WHERE StaffID='$_POST[hiddenid]'";
to
$UpdateQuery = "UPDATE staff SET StaffName='".$_POST['staffname']."', Position='".$_POST['staffposition']."' WHERE StaffID='".$_POST['hiddenid']."'";
What you were doing is $_POST[staffname] which must be like as $_POST['staffname'] and always try to check using error_reporting(E_ALL) function and need to check that your values are set or not

Update retrieved data

Hi there im in the process of making a page to approve and deny names in a database, I currently have it so it finds an pulls the pending requests im looking for now i wanna know how to update the row once i click approve or deny.
the values it needs to update is the NameState column to either ("approved") or ("REJECTED")
there can be any where from 1 to 100 names at a time.
Thanks Ryan
$DB_HOST = "IP";
$DB_USER = "user";
$DB_PASS = "Pass";
$DB_DTBS = "DB";
mysql_connect($DB_HOST, $DB_USER, $DB_PASS) or die(mysql_error()); // Connect to database server(localhost) with username and password.
mysql_select_db($DB_DTBS) or die(mysql_error()); // Select registration database.
$search = mysql_query('SELECT * FROM TABLE WHERE `NameState` = \'(\"PENDING")\'') or die(mysql_error());
$match = mysql_num_rows($search);
if($match > 0){
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Current Name</th>
<th>Requested Name</th>
<th>Approve or Deny</th>
</tr>";
while($row = mysql_fetch_array($search)) {
echo "<tr>";
echo "<td>" . $row['object_id'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['WishName'] . "</td>";
echo '<td> <form method="post" action=<?php echo Approve:<input type="radio" value="Approve" name="name"> Deny:<input type="radio" value="Deny" name="name"><br /> </td>';
echo "</tr>";
}
echo "</table>";
echo '<input type="Submit" value="Submit" name="Submit"> </form>';
} else {
echo("No Names to Approve");
}
?>

Only updating last database record - Array required?

Could someone help me out, I am only new to PHP and SQL. I have created a database, and want to update it using a form on a HTML page. It all works fine except it only updates the last record. I presume this is because I need an array but am unsure how to do this. WOuld anyone have some good examples or point me in the right direction?
The code is as follows:
Display Page
<?php
$con=mysqli_connect("xx","xx","xx","xx");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM webquestion");
if ($result) {
// create a new form and then put the results
// into a table.
echo "<form method='post' action='delete.php' >";
echo "<table class='webquestion' >
<tr>
<th width='12%'>Department</th>
<th width='15%'>Name</th>
<th width='25%'>E-mail</th>
<th width='20%'>Message</th>
<th width='20%'>Notes</th>
<th width='8%'>Delete</th>
</tr>";
while ($row = $result->fetch_object()) {
$department = $row->department;
$name = $row->name;
$email = $row->email;
$message = $row->message;
$notes = $row->notes;
$id = $row->id;
//put each record into a new table row with a checkbox
echo "<tr>
<td>$department</td>
<td>$name</td>
<td>$email</td>
<td>$message</td>
<td><input type='text' name='notes' id='notes' value='$notes' />
<td><input type='checkbox' name='checkbox[]' id='checkbox[]' value=$id />
<td><input type='hidden' name='id' value=$id />
</tr>";
}
// when the loop is complete, close off the list.
echo "</table><p><input id='delete' type='submit' class='button' name='delete' value='Delete Selected Items' style='float:left'/>
</table><p><input id='update' type='submit' class='button' name='update' value='Update' style='float:left'/></p>
</form>
<form action='showContactUs.php' >
<input type='submit' value='Refresh Records' style='float:left'>
</form>";
}
?>
PHP Code
<?php
if(isset($_POST['update'])) // from button name="update"
$hostname = 'xx';
$username = 'xx';
$password = 'xx';
$dbname = 'xx';
/*** create a new mysqli object with default database***/
$mysqli = #new mysqli($hostname, $username, $password, $dbname);
/* check connection */
if(!mysqli_connect_errno())
{
/*** if we are successful ***/
echo 'Connected Successfully<br />';
/*** sql to UPDATE an existing record ***/
$notes = $_POST['notes'];
$sql = "UPDATE webquestion
SET notes = '$notes'
WHERE id = '$id'";
/*** execute the query ***/
if($mysqli->query($sql) === TRUE)
{
echo mysqli_affected_rows($mysqli). ' Records UPDATED successfully<br />';
}
else
{
echo 'Unable to UPDATE Records: '.$sql.'<br />' . $mysqli->error;
}
/*** close connection ***/
$mysqli->close();
}
else
{
/*** if we are unable to connect ***/
echo 'Unable to connect';
exit();
}
?>
Thanks for your help.
To pass an array via POST simply add a '[]' to the name atribute:
<td><input type='text' name='notes[]' id='notes' value='$notes' />
<td><input type='hidden' name='id[]' value=$id />
Then on the server side you would do:
$notes = $_POST['notes']; //notes array
foreach($_POST['id'] as $index=>$id) //traverse the ids array
{
$note = $notes[$index]; //Get the note on the same row as id
/*** sql to UPDATE an existing record ***/
$sql = "UPDATE webquestion SET notes = '$note' WHERE id = '$id'";
/*** execute the query ***/
if($mysqli->query($sql) === TRUE)
{
echo mysqli_affected_rows($mysqli). ' Records UPDATED successfully<br />';
}
else
{
echo 'Unable to UPDATE Records: '.$sql.'<br />' . $mysqli->error;
}
}
If you want to update several rows at the same time by matching with their IDs, you need an array of IDs:
array(25,33,26,24)
or any other type of array.
Then you should loop through your array and update the db accordingly:
for($i=0; $i < count($id_array); $i++)
{
$id = $id_array[$i];
$sql = "UPDATE webquestion
SET notes = '$notes'
WHERE id = '$id'";
// and the rest of SQL update
}

HTML table inputting data to a mysql database

I am trying to get a form to input data into my "mysql database" however i am getting an error message and also it is inputting a blank data everytime the page loads.
Here is my code:
<form action="insert.php" method="post">
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
// This is the connection to my database
$con = mysql_connect('127.0.0.1', 'shane', 'diamond89');
if (!$con){
die('Could not Connect: ' . mysql_error());
}
// This creates my table layout
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Delete</th>
</tr>";
// This selects which database i want to connect to
$selected = mysql_select_db("shane",$con);
if (!$con){
die("Could not select examples");
}
// This inserts new information to the Database
$query = "INSERT INTO test1 VALUES('id', '$name')";
$result = mysql_query($query);
if ($result){
echo("Input data is Successful");
}else{
echo("Input data failed");
}
// This chooses which results i want to select from
$result = mysql_query("SELECT `id`, `name` FROM `test1` WHERE 1");
// This outputs the information into my table
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . "[D]" . "</td>";
echo "</tr>";
}
echo "</table>";
// This closes my connection
mysql_close($con);
?>
Here is the error message:
( ! ) SCREAM: Error suppression ignored for
( ! ) Notice: Undefined variable: name in C:\wamp\www\sql_table.php on line 36
Call Stack
Time Memory Function Location
1 0.0006 250360 {main}( ) ..\sql_table.php:0
You are trying to access to the POST data, so you should do something like that :
EDIT: be careful about the data you put into your database. You should use a modern database API, or, at least, escape your data (cf bellow code)
<form action="insert.php" method="post">
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
// Following code will be called if you submit your form
if (!empty($_POST['name'])) :
// This is the connection to my database
$con = mysql_connect('127.0.0.1', 'shane', 'diamond89');
if (!$con){
die('Could not Connect: ' . mysql_error());
}
// This creates my table layout
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Delete</th>
</tr>";
// This selects which database i want to connect to
$selected = mysql_select_db("shane",$con);
if (!$con){
die("Could not select examples");
}
// This inserts new information to the Database
$query = "INSERT INTO test1 VALUES('id', \'".mysql_real_escape_string($_POST['name'])."\')";
$result = mysql_query($query);
if ($result){
echo("Input data is Successful");
}else{
echo("Input data failed");
}
// This chooses which results i want to select from
$result = mysql_query("SELECT `id`, `name` FROM `test1` WHERE 1");
// This outputs the information into my table
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . "[D]" . "</td>";
echo "</tr>";
}
echo "</table>";
// This closes my connection
mysql_close($con);
endif;
?>

Categories