Failing to update the new data entered by administrator - php

Look like everything is working fine with this code but in fact fails to update the database, Data are displayed correctly while fetching data but when i press update Button the data disappear but no update has been executed. It look fine to me but seems i am wrong.
This is a project for my professor so i don't care for the SQL injection and others.
<html>
<head>
<link rel="stylesheet" type="text/css" href="btnstyle.css">
<title>Managament System</title>
</head>
<body>
<h1>TU Chemnitz Student managament system</h1>
<br>
ADD Person
Edit Person
Manage Boards
Manage Departments
Search N&S
Triple Search
Membership
<br>
<br>
<?php
// set database server access variables:
$host = "localhost";
$user = "";
$pass = "";
$db = "";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$querys = "SELECT * FROM tblperson";
// execute query
$result = mysql_query($querys) or die ("Error in query: $query. ".mysql_error());
echo "<table border=1 align=center>
<tr>
<th>Personal ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Deparment</th>
<th>Board</th>
<th>Marticulation Number</th>
<th>Reg Date</th>
<th>Action</th>
</tr>";
while($row = mysql_fetch_array($result)) {
?>
<?php
echo '<tr>';
echo '<td>'. $row['personid'].'</td>';
echo '<td>'. $row['personname'].'</td>';
echo '<td>'. $row['personsurname'].'</td>';
echo '<td>'. $row['persondepartment'].'</td>';
echo '<td>'. $row['personboard'].'</td>';
echo '<td>'. $row['martinumber'].'</td>';
echo '<td>'. $row['personregdate'].'</td>';
echo '<td>'.' EDIT '.'</td>';
}
?>
</body>
</html>
and this is the edit file which seems to problematic.
<?php
include_once('coneksioni.php');
if(isset($_GET['edit']))
{
$personid = $_GET['edit'];
$res = mysql_query("SELECT * FROM tblperson WHERE personid='$personid'");
$row = mysql_fetch_array($res);
}
if(isset($_POST['newpersonname']))
{
$newpersonname = $_POST['newpersonname'];
$personid = $_POST['personid'];
$sql = "UPDATE tblperson SET personname = '$newpersonname' WHERE personid = '$personid'";
$res = mysql_query($sql) or die ("Cant be updated");
echo "< meta http-equiv='refresh' content='0;url=home.php'>";
}
?>
<form action="edit20.php" method="POST">
<table border="0">
<tr>
<td>First Name</td>
<td><input type="text" name="newpersonname" value="<?php echo $row[1];?>" maxlength="30" size="13"></td>
</tr>
<tr>
<td>Last Name</td>
<td> <input type="text" name="personsurname" value="<?php echo $row[2];?>" maxlength="30" size="30"></td>
</tr>
<tr>
<td>Department</td>
<td>
<select name='persondepartment'>
<option>Production</option>
<option>Sales</option>
</select>
</td>
</tr>
<tr>
<td>Board</td>
<td>
<select name='personboard'>
<option>Evaluation</option>
<option>Executive</option>
<option>Research</option>
</select>
</td>
</tr>
<tr>
<td>Marticulation Number</td>
<td> <input type="text" name="martinumber" maxlength="60" size="30"></td>
</tr>
<tr>
<td>Date of Registration</td>
<td><input type="date" name="personregdate" maxlength="7" size="7"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value=" Update"></td>
</tr>
</table>
</form>

You are looking for personid when the Update button is pressed on the form in edit20.php but that value has never been set so it will be empty and the update will fail.
After
<form action="edit20.php" method="POST">
add:
<input type="hidden" name="personid" value="<?php echo $personid; ?>">

On edit page seem your confusing the same variable with different values. If you state $personid variable to contain the edit value from get, then just re-use the variable don't assign new value. On this line you assign new value :
$personid = $_POST['personid'];
Don't assign new value since it has the initial value already to use just set the variable global for usage
$personid = $_GET['edit'];
Or else create a hidden element and pass edit value into it.

Please add name attribute for your update button
<td colspan="2"><input type="submit" name="update" value=" Update"></td>
and chk whether the update button set or reset as in the place of
if(isset($_POST['newpersonname'])) // change text 'newpersonname' as 'update'

You use a variable that doesn't excist:
<?php
include_once('coneksioni.php');
if(isset($_GET['edit']))
{
$personid = $_GET['edit'];
$res = mysql_query("SELECT * FROM tblperson WHERE personid='$personid'");
$row = mysql_fetch_array($res);
}
if(isset($_POST['newpersonname']))
{
$newpersonname = $_POST['newpersonname'];
$personid = $_POST['personid']; // this doesn't excist
$sql = "UPDATE tblperson SET personname = '$newpersonname' WHERE personid = '$personid'";
$res = mysql_query($sql) or die ("Cant be updated");
echo "< meta http-equiv='refresh' content='0;url=home.php'>";
}
?>
$personid = $_POST['personid']; doesn't excist in your code. Its simply a piece of code you put in there to probably proces, but forgot to define the variable in the code. Place the following in your form.
<input type="hidden" name="personid" value="<?php echo $_GET['edit']; ?>">
You only use this just once because you send the form back after proces to your home, hence it wont be used anymore. You can also use the avariable you defined as $personid; on that position.
If that fails, something maybe wrong in your query. Try to echo out the query (remove qucikly the meta command) by simply just do echo $sql after you do the sql query. 9 out of 10 times, it's a typo.

Related

how do fetching and then inserting from multi check boxes in php

I am going to fetching table values in a html table along checkbox in each row and then inserting values in another database table from multi check boxes in php.
Only the values of checked boxes should be submitted to that table.
db name "laboratory":
test: fetching values.
package: inserting table.
view
Status
Active
Inactive
<?php
$conn=mysqli_connect("localhost","root","","laboratory") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$query="SELECT * FROM test";
$result=mysqli_query($conn,$query);
if ($result) {
while ($record=mysqli_fetch_array($result)) {
Please try to follow this code and implement in your program . Hope that this will cooperate you much
if(isset($_POST['name'])){
$name = $_POST['name'];
$status = $_POST['status'];
if(empty($name) || empty($status)){
echo "Field Must Not be empty";
} else{
$conn=new mysqli("localhost","root","","test");
if($conn){
$query = "SELECT * FROM userdata limit 5";
$stmt = $conn->query($query);
$val = '<form action="" method=""> ';
$val .= '<table> ';
if ($stmt) { ?>
<form action="" method="post">
<table>
<?php while ($result=$stmt->fetch_assoc()) { ?>
<tr>
<td><?php echo $result['post']; ?></td>
<td><input value="<?php echo $result['post']; ?>" type="checkbox" name="check[]" /></td>
</tr>
<?php } ?>
<tr>
<td>Actual Price </td>
<td>Discount</td>
<td>Final Price</td>
</tr>
<tr>
<td><input type="text" name="actual"/></td>
<td><input type="text" name="discount"/></td>
<td><input type="text" name="final"/></td>
</tr>
<tr>
<td>Description</td>
<td><textarea name="description" id="" cols="30" rows="10"></textarea></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td><input type="reset" value="Cancel" /></td>
</tr>
</table>
</form>
<?php }} }}?>
<?php
if(isset($_POST)){
echo "<pre>";
print_r($_POST);
echo "<pre>";
}
?>`enter code here`
First of all you have to decide that what are you using either mysqli or mysql, if you are using mysqli then you have to improve your code
$query="SELECT * FROM test";
$result=mysqli_query($conn,$query);
if ($result) {
while ($record=mysqli_fetch_array($result)) {
and when you want to insert the checked data will be inserted in package table. If package table in another database then you have to give us the full detail i mean tell us the database name of package table.

How can i insert html table data into sql database using php?

This is my table html code. I tried sending the data using the normal insert but it only sends the last row data. I don't know how to send the full data . Can someone please help me with this.
<form action="admin_schedule_employee.php" id="schedule_employee" method="post" >
<input type="date" class="input-sm" name="scheduledate" style="margin:10px;">
<table class="table-responsive table table striped table-bordered">
<thead>
<tr>
<th style="width:20%">Employee First Name</th>
<th style="width:20%">Employee ID</th>
<th style="width:20%">Start Time</th>
<th style="width:20%">End Time</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)): ?>
<tr>
<td><input disabled name="employeename" type="text" value="<?php echo $row['fname']; ?>"></input></td>
<td><input disabled name="employeeid" type="number" value="<?php echo $row['employee_id']; ?>"></input></td>
<td><input name="starttime" type="time"></td>
<td><input name="endtime" type="time"></td>
</tr>
<?php endwhile; ?>
</thead>
<tbody>
</tbody>
</table>
<input type="submit" name="Schedule" value="Schedule">
</form>[This is how my table look like i want to send the whole data to sql database using php][1]
To start with, you will need to create multiple pages:
form.php
process.php
done.php
Creating your user form is simple, place the table in form tags like you have done above, here is an example. Save this page as form.php
<form id="new record" action="process.php" method="POST">
<table width="500px">
<tr>
<td width="50%">
<input type="text" name="fname" id="fname">
</td>
<td width="50%">
<input type="text" name="lname" id="lname">
</td>
</tr>
<tr>
<td width="50%">
</td>
<td width="50%">
<input type="submit" value="Add Record">
</td>
</tr>
</table>
</form>
Next, you will need to create a page which can process this data, and add it to your mysql database. For the following example, I have omitted my database details and substituted them, but you should add your own.
For this example, imagine my database has a table with only an fname and an lname column.
<meta http-equiv="refresh" content="0; url=/done.php" />
<?php
$servername = "your_server_name";
$username = "mysql_username";
$password = 'mysql_password';
$dbname = "database_name";
$fname = $_GET['fname'];
$lname = $_GET['lname'];
try {
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO online (fname, lname)
VALUES ('$fname', '$lname')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record inserted";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Hopefully, that will work to insert the record. Now we need a table on the done.php page which can display all the records in the database. Use the following code:
<html lang="en">
<head>
<meta http-equiv="refresh" content="5; url=/done.php" />
<meta charset="utf-8" />
<title></title>
</head>
<body>
<?php
$servername = "your_server_name";
$username = "mysql_username";
$password = 'mysql_password';
$dbname = "database_name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * from table_name";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["fname"]. ": ";
echo $row["lname"]. "<br /><br />";
}
} else {
echo "No messages";
}
mysqli_close($conn);
?>
</body>
</html>
Hopefully this will work for you.

Can't edit data in the database and cant fetch name with id?

I am trying to edit data into the database I don't know why I cant do. I have tried something till now. maybe someone can have a look please. I am trying to built a update where i can change name, surname blah blah blah, but i cant config even just for a name first..
Home file
Managament System
<body>
<h1>TU Chemnitz Student managament system</h1>
<br>
ADD Person
Edit Person
Manage Boards
Manage Departments
Search N&S
Triple Search
Membership
<br>
<br>
<?php
include_once('coneksioni.php');
// create query
$querys = "SELECT * FROM tblperson";
// execute query
$result = mysql_query($querys) or die ("Error in query: $query. ".mysql_error());
$res = mysql_query("SELECT * FROM tblperson");
echo "<table border=1 align=center>
<tr>
<th>Personal ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Deparment</th>
<th>Board</th>
<th>Marticulation Number</th>
<th>Reg Date</th>
<th>Action</th>
</tr>";
while($row = mysql_fetch_array($res)) {
?>
<tr>
<td><?=$row['personid']?></td>
<td><?=$row['personname']?></td>
<td><?=$row['personsurname']?></td>
<td><?=$row['persondepartment']?></td>
<td><?=$row['personboard']?></td>
<td><?=$row['martinumber']?></td>
<td><?=$row['personregdate']?></td>
<td>
edit |
del
</td>
</tr>
<?php
}
?>
</body>
</html>
and edit20.php
<?php
include_once('coneksioni.php');
if( isset($_GET['edit']) )
{
$personid = $_GET['edit'];
$res= mysql_query("SELECT * FROM tblperson WHERE personid='$personid'");
$row= mysql_fetch_array($res);
}
if( isset($_POST['personname']) )
{
$personname = $_POST['personname'];
$personid = $_POST['personid'];
$sql = "UPDATE tblperson SET personname='$personname' WHERE personid='$personid'";
$res = mysql_query($sql)
or die("Could not update".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=home.php'>";
}
?>
<form action="edit20.php" method="POST">
Name: <input type="text" name="personname" value="<?php echo $row[1]; ?>"><br />
<input type="hidden" name="personid" value="<?php echo $row[0]; ?>">
<input type="submit" value=" Update "/>
</form>
and in the database primary key in my table is personid name field personname (not Primary key).
Please use Prepared Statement for reduce the risk of SQL Injection
check the coneksioni.php
$conn = new mysqli(HOST, USER, PASS, DBNAME);
the edit.php
require_once ('coneksioni.php');
$edit_person = $conn->prepare("
UPDATE tblperson SET
personname = ? WHERE personid = ?
");
$edit_person->bind_param(
"si",
$personname, $personid
);
if(isset($_POST['personname']) && isset($_POST['personid']) ) {
$personname = $_POST['personname'];
$personid = $_POST['personid'];
if (!$edit_person->execute()) {
// action if failed
} else {
// action if success
}
$edit_person->close();
}
the form.html
<form action="edit.php" method="POST">
Name: <input type="text" name="personname" value="<?php echo $row[1]; ?>"><br />
<input type="hidden" name="personid" value="<?php echo $row[0]; ?>">
<input type="submit" value=" Update "/>
</form>
Cheers

Blank screen when updating data in php table

I have been working on a project and i am at the final stages of the project. My problem is whenever i try to update data in my database table into returns a blank screen with no error messages. Please find the php script and html form (the form responsible for updating the database table) below, i have divided it into about four sections:
Thanks in advance
Update Form:
<a name="inventoryEditForm" id="inventoryEditForm"></a>
<h3>↓Add New Question Form↓</h3>
<form action="inventory_edit.php" enctype="multipart/from-data" name="myForm" id="myForm" method="post">
<table width="80%" border="0" cellspacing="3" cellpadding="7">
<tr>
<td width="20%"> </td>
<td width="80%"> </td>
</tr>
<tr>
<td>Question</td>
<td><textarea rows="" name="question" cols=""><?php echo $question; ?></textarea></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Venue</td>
<td><input type="text" name="venue" maxlength="50" value="<?php echo $venue; ?>"></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Date</td>
<td><input type="date" name="questiondate" value="<?php echo $date; ?>"></td>
</tr>
</table>
<br>
<input name="thisID" type="hidden" value="<?php echo $targetID; ?>"/>
<input type="submit" name="submit" value="Update Question">
<input type="reset" name="clear" value="Clear Form">
</form>
PHP Script:
<?php
//Error reporting due to long script
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php
error_reporting(E_PARSE);
//Update question table
If (isset($_POST['question'])) {
$id = mysqli_real_escape_string($link, $_POST['thisID']);
$question = mysqli_real_escape_string($link, $_POST['question']);
$venue = mysqli_real_escape_string($link, $_POST['venue']);
$date = mysqli_real_escape_string($link, $_POST['questiondate']);
//Update question in the table
$sql = mysqli_query($link, "UPDATE DebateQuestion SET question='$question',venue='$venue',date='$date' WHERE qQuestionNo='$id'LIMIT 1") or die(mysql_error());
header("location: inventory.php");
exit();
}
?>
<?php
error_reporting(E_PARSE);
//Gather this questions full information and insert automatically into the edit form
if (isset($_GET['qid'])) {
$targetID = $_GET['qid'];
$sql = mysqli_query($link, "SELECT * FROM DebateQuestion WHERE qQuestionNo='$targetID'LIMIT 1") or die(mysql_error());
$questionCount = mysqli_num_rows($sql); // count the output amount
if ($questionCount > 0) {
while ($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)) {
$id = $row["qQuestionNo"];
$question = $row["qQuestion"];
$venue = $row["qDebateVenue"];
$date = strftime("%b %d, %Y", strtotime($row["qDate"]));
}
} else {
echo "Oops, no questions like that exists. Check <a href='inventory.php'>inventory</a>again";
exit();
}
}
?>
In your update query you have the data column without using ` back ticks , date is also a mysql's function try to wrap up your column names with back ticks if you are not sure whether they conflict with mysql's reserved keywords
$sql = mysqli_query($link,"UPDATE DebateQuestion SET
`question`='$question',`venue`='$venue',`date`='$date'
WHERE qQuestionNo='$id'LIMIT 1")
"SELECT * FROM DebateQuestion WHERE qQuestionNo='$targetID'LIMIT 1"
Here is qQuestionNo column a string type?if not remove quotes around $targetID.
Note : I have not tested the code - just read it on screen.
I've never seen an IF statement capitalized before :
If (isset($_POST['question'])) {
I'd guess this makes a difference however.
There's lots of other weird things going on in your files, but none that should give you white screen. Try lowercase 'I' in your if statement first.
ALSO - re: the UPDATE statement, you are missing a space between the $id and the LIMIT :
**qQuestionNo='$id'LIMIT 1**

Why are my values not being updated?

I have a simple, unsecured, local database that I'm learning with (yes still using MySQL for now) I can view my database rows in a table and click on an edit button which then displays the single record chosen with each column inside a text box to update and save. Here is my edit page.
<?php
$id = $_GET['id'];
$connect = mysql_connect("localhost", "XXXXXX", "XXXXXXX") or
die ("Check your connection.");
mysql_select_db("toner");
$quey1="select * from inventory where id ='".$id."'";
$result=mysql_query($quey1) or die(mysql_error());
?>
<html>
<form action="updateinfo.php" method="post">
<table>
<?php
while ($row=mysql_fetch_array($result))
{
?>
<tr>
<td align="right">Partnumber:</td>
<td align="left"><input type="text" name="partnumber" value="<?php echo $row['partnumber'];?>"/></td>
</tr>
<tr>
<td align="right">Description:</td>
<td align="left"><input type="text" name="description" value="<?php echo $row['description'];?>"/></td>
</tr>
<tr>
<td align="right">Vendor:</td>
<td align="left"><input type="text" name="vendor" value="<?php echo $row['vendor'];?>"/></td>
</tr>
<tr>
<td align="right">Price:</td>
<td align="left"><input type="text" name="price" value="<?php echo $row['price'];?>"/></td>
</tr>
<tr>
<td align="right">Quantity:</td>
<td align="left"><input type="text" name="quantity" value="<?php echo $row['quantity'];?>"/></td>
</tr>
</table>
<br>
<input type="hidden" name="id" value="<?php echo $row['id'];?>"/>
<input type="submit" value="Edit/Update Toner">
<?php
}
?>
</form>
</html>
Here is my UPDATED updateinfo
<?php
mysql_connect("localhost","XXXXX","XXXXX") or die("Error: ".mysql_error());
mysql_select_db("toner");
$id =$_POST['id'];
$partnumber = $_POST['partnumber'];
$description = $_POST['description'];
$vendor = $_POST['vendor'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];
$sql = "UPDATE inventory SET partnumber ='".$partnumber."',description ='".$description."',vendor ='".$vendor."',price ='".$price."',quantity ='".$quantity."' WHERE id ='".$id."'";
mysql_query($sql) or die ("Error: ".mysql_error());
echo "Updated successfully";
header( "refresh:10;url=toner.php" );
?>
After adding a primary key I'm able to update the DB however $id = $_POST['id']; still gives an error, any assistance is appreciated. Thanks. Yes I'm aware its vulnerable to injection and that I should be using PDO or MySQLi but I'm still a beginner and this is where I've chosen to start learning. Thank you.
the problem is because of partnumber,here you are again reseting the partnumber but the new one is not present in your database and because of that query does not update the new values.
$sql = "UPDATE inventory SET description ='".$description."',vendor ='".$vendor."',price ='".$price."',quantity ='".$quantity."' WHERE partnumber = '".$partnumber."'";
Solution
Don't again set the partnumber use it only in where clause.

Categories