Database won't stay updated after switching script - php

I'm trying to update this database, and I've verified within this script that the update is completed, and that the $nw and $p variables are correct.
<?php
session_start();
$num = (int) $_SESSION["cart"];
$cart = $num + 1;
$_SESSION["cart"] = (string) $cart;
$nme = $_POST['nameofitem'];
$pst = $_SESSION["user"];
$db = new mysqli('localhost', 'spj916', "cs4501", 'spj916');
$query = "select * from Items where Items.Id = '$nme'";
$result = $db->query($query) or die ($db->error);
$item = $result->fetch_array();
$nw = $item[5] - 1;
$p = (int) $pst;
echo $p;
$query3 = "update Items set Quantity = '$nw' where Id = '$p'";
$db->query($query3) or die ("Invalid insert " . $db->error);
$query2 = "insert into Bought (Name, Cost, BuyerID) values ('$item[1]', '$item[4]', '$pst')";
$db->query($query2) or die ("Invalid insert " . $db->error);
header("Location: store.php");
?>
However, when it redirects to this script, it echoes the information as if it weren't updated. What is the problem?
<?php
session_start();
$db = new mysqli('localhost', 'spj916', "cs4501", 'spj916');
$user = $_SESSION["user"];
$pw = $_SESSION["pw"];
# determines number of items in cart to display
if (!isset($_SESSION["category"]))
$_SESSION["category"] = "Book";
if (isset($_POST["Ccategory"])) {
$cat = $_POST["Ccategory"];
$_SESSION["category"] = $cat;
}
if (!isset($_SESSION["cart"]))
$_SESSION["cart"] = "0";
$cart = $_SESSION["cart"];
?>
<!DOCTYPE html>
<html>
<?php # setting up table with items to buy ?>
<table border = "1" border-spacing = "5px" >
<caption><h2> UVA Bookstore 2.0</h2>
<p align=right> Items in cart: <?php echo $cart?> </p> <br />
<b><i>Welcome to the new and improved bookstore with a better selection than ever</i></b>
<br/><br/>
</caption>
<tr align = "center">
<th>Item</th>
<th>Description</th>
<th>Price</th>
<th>Number left</th>
<th>Buy</th>
</tr>
<?php
$category = $_SESSION["category"];
$query = "select * from Items where Items.Category = '$category'";
$result = $db->query($query) or die ($db->error);
$rows = $result->num_rows;
for ($i = 0; $i < $rows; $i++)
{
$row = $result->fetch_array();
?>
<form action="addtocart.php"
method="POST">
<tr align = "center">
<td>
<?php
echo $row[1];
?>
</td>
<td> <?php echo $row[3];?> </td>
<td> <?php echo $row[4];?> </td>
<td> <?php echo $row[5];?> </td>
<?php # sets up add to cart button that adds item to cart ?>
<td> <input type = "hidden" name ='nameofitem'
value= "<?php echo $row[0]?>">
<input type='submit' value='Add to Cart'> </input> </td>
</tr>
</form>
<?php
}
# form to check out and go to summary page ?>
<form action = "store.php"
method = "POST">
<tr align = "center"> <td>
<select name = "Ccategory">
<option value = "Book">Books</option>
<option value = "Music">Music</option>
<option value = "Car">Cars</option>
</select>
<input type = "hidden" name = "cat"> </td>
<td> <input type = "submit" value = "Switch Category"> </td>
</form>
<form action="summary.php"
method="POST">
<td> <input type = "submit" value = "Check out"> </td> </tr>
</table><br/>
</form>
</html>

Have you tried changing
$query3 = "update Items set Quantity = '$nw' where Id = '$p'";
to
$query3 = "update Items set Quantity = '$nw' where Id = $p";
The best way to determine if an UPDATE should work is to replace it with a SELECT containing the same WHERE clause. This way you can see what rows would be changed if you were to run the original query.
Otherwise, it seems to be the case that your changes in the current transaction are never committed. Is this the only script that has an issue with updates to the database? Please see the PHP manual for more information:
//mysqli::commit -- mysqli_commit — Commits the current transaction
bool mysqli::commit ([ int $flags [, string $name ]] )
A commit should be issued when you are done doing all updates that have dependencies (or for those that are atomic), however, you don't always have to commit depending on the configuration of your server. Also, it looks like your script has SQL injection vulnerabilities as other have mentioned. It would probably be best to use prepared statements or sanitize your inputs.

Related

Creating an HTML form basing on information extracted from an SQL database using while loop

I am trying to create a form, basing on information picked from the database using a while loop. I need some guidance on how to go about this. When form is supposed to return multiple values (of students) and then a text field for inputting marks is assigned to the students returned, which should allow the user input the marks and then submit the form.
Here is the code i have sofar
<form method="post">
<?php
//picking student details
$sql = mysql_query("SELECT *
FROM student, class, subject, assesment
WHERE
student.class_id = '$assesment_class'
AND subject.idsubject = '$assesment_subject'
AND subject.subject_option = 'Major'
AND class.idclass = student.class_id
AND class.idclass = subject.class_id
AND assesment.subject_idsubject = subject.idsubject
AND assesment.idassesment = '$ass'
");
$Count = mysql_num_rows($sql); //counting the the selected rows
if($Count > 0){
while($row = mysql_fetch_array($sql)){
//picking database values
$student_id = $row["idstudent"];
$student_names = $row["student_names"];
//Query for checking results
$sql1 = mysql_query("SELECT *
FROM result, student_has_result, grade, student, assesment
WHERE
student_has_result.student_id = '$student_id'
AND student_has_result.student_class_id = '$assesment_class'
AND student_has_result.assesment_id = '$ass'
AND student_has_result.result_id = result.idresult
AND result.grade_idgrade = grade.idgrade
AND student_has_result.assesment_id = assesment.idassesment
AND student_has_result.student_id = student.idstudent
AND student_has_result.result_id = result.idresult");
$Count1 = mysql_num_rows($sql1); //counting the the selected rows
if($Count1 > 0){
while($row = mysql_fetch_array($sql1)){
//picking database values
$mark = $row["mark"];
//echo $mark;
}
}else{
$mark = "";
}
?>
<tr>
<td><?php echo $student_names; ?></td>
<td>
<input type="text" name="result" placeholder="<?php echo $mark; ?>"/>
<input type="hidden" name="student" value="<?php echo $student_id; ?>"/>
<input type="hidden" name="assesment" value="<?php echo $ass; ?>"/>
</td>
</tr>
<?php
}
?>
<tr>
<td></td>
<td><button name="submit-results-button" type="submit" class="btn btn-success">-Submit Students Results Now-</button><br><br></td>
</tr>
</form>
Any guidance will be highly appreciated.

Inserting multiple rows to database from a while loop

Good day! I am having a problem in storing values in my database. The flow of the program is the user will input in how many subject he will get. For example, he/she can put 6 subjects. So it will release 6 input types with values equal to text. My problem is I don't get 6 rows in my database as the user take 6 inputs.
HTML/PHP
<form method="POST">
<table>
<tr>
<td>SUBJECT CODE/SUBJECT DESCRIPTION/SEMESTER</td>
</tr>
<?php $counter=1 ;
while($counter <= $subj){?>
<tr>
<td>
<select name="sub">
<?php $select=mysql_query("SELECT * FROM subject
WHERE course_code = '$course' AND semester = '$sem'");
while($rows=m ysql_fetch_assoc($select)){
$code=$rows['subj_code'];
$desc=$rows['subj_desc'];
$units=$rows['units'];
$yr=$rows[ 'year_level'];
?>
<**option value="<?php echo $codes[$code]; ?>">
<?php echo $code. " - ".$desc; ?>
</option>**
<?php } ?>
</select>
</td>
<td>
</td>
</tr>
<?php $counter++; } } ?>
<tr>
<td>
<input type="submit" name="add" value="add subjects">
</td>
</tr>
</table>
</form>
PHP/SQL
<?php
if (isset($_POST['add'])) {
$data = array();
$subject = $_POST['sub'];
$sem = $_SESSION['sem'];
for ($i = 0; $i < count($subject); $i++) {
$subject = mysql_real_escape_string($subject[$i]);
$sem = mysql_real_escape_string($sem[$i]);
$yr = mysql_real_escape_string($yr[$i]);
$fac = mysql_real_escape_string($fac[$i]);
$col = mysql_real_escape_string($col[$i]);
$set = mysql_query("SET foreign_key_checks = 0");
if (!$set) {
die("Foreign key SET failed");
} else {
$insertmid = mysql_query("INSERT INTO grade_midterm
(midterm_grade, semester, year_level, subj_code, stud_id, fac_id, col_code)
VALUES ('NA','$sem','$yr','$subject', '$user','$fac','$col')");
if (!$insertmid) {
die("Failed to insert midterm" . mysql_error());
} else {
$insertfinal = mysql_query("INSERT INTO grade_final
(final_grade, semester, year_level, subj_code, stud_id, fac_id, col_code)
VALUES ('NA','$sem','$yr','$subject','$user','$fac','$col')");
if (!$insertfinal) {
die("Failed to indert final");
} else {
$set2 = mysql_query("SET foreign_key_checks = 1");
echo "<script>alert('Success Adding Subject');</script>";
}
}
}
}
}
?>
You have a select box with name sub in your loop
<select name="sub">
this means every next selectbox will overwrite the previous one
use
<select name="sub[]">
to create a array in your $_POST variable

MySQL UPDATE function is not working [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
I'm a new in PHP coding and this is one assignment that I have to do.
I have included DB Connect already in the file but these are codes I use in this assignment which is able to edit the job advertisement data.
This is advertisement table file.
$result = mysql_query("SELECT * FROM advertisement");
<TABLE border ='1'>
<table style="width:100%">
<tr>
<th>Advertisement ID</th>
<th>Position</th>
<th>Start Date</th>
<th>End Date</th>
<th></th>
<th></th>
</tr>
<?php
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
echo "<TR>";
echo "<TD>".$row['Ad_ID']."</TD>";
echo "<TD>".$row['Position_Name']."</TD>";
echo "<TD>".$row['Start_date']."</TD>";
echo "<TD>".$row['End_date']."</TD>";
echo "<TD><a href='edit-advertisement.php?ad_id=".$row['Ad_ID']."'>Edit</a></TD>";
echo "<TD><a href='delete-advertisement.php?ad_id=".$row['Ad_ID']."'>Delete</a></TD>";
echo "</TR>";
}
?>
And this is edit-advertisement.php file.
$result = mysql_query("SELECT * FROM advertisement WHERE Ad_ID='".$_REQUEST['ad_id']."'");
$row = mysql_fetch_array($result, MYSQL_ASSOC);
<form name = 'edit-advertise-form' method = 'POST' action = 'confirm-edit-adv.php'>
<br >
<input type='hidden' name='ad_id' value='<?=$row['Ad_ID']?>'>
Advertisement ID : <?=$row['Ad_ID']?><br><br />
Position to be recruited : <input type = "Textbox" Name = "Pos_Name" value = '<?=$row['Position_Name']?>'><br><br>
Job Description: <br ><br /> <textarea name="Job_Des" rows="5" cols="40" value = '<?=$row['Ad_Job_Description']?>'> </textarea><br><br>
Job Qualification: <br ><br /> <textarea name="Job_Quali" rows="5" cols="40" value = '<?=$row['Ad_Job_Qualification']?>'> </textarea><br><br>
Skill required: <br ><br /> <textarea name="Skill_Req" rows="5" cols="40"value = '<?=$row['Ad_Skill_Required']?>'> </textarea><br><br>
Salary offer: <input type = "Textbox" Name = "Salary" value = '<?=$row['Position_Salary_Detail']?>'><br><br>
Start date :
<SELECT name='s_day'>
<?php
$i = 1 ;
while($i<=31) {
?>
<OPTION value = '<?php echo $i;?>' > <?php echo $i;?> </OPTION>
<?php $i++; }
?>
</SELECT>
<SELECT name='s_month' >
<?php
$month = array( 1=> JANUARY,FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER);
$i = 1;
foreach ($month as $m){
?>
<OPTION value = '<?php echo $i;?>' > <?php echo $m;?> </OPTION>
<?php
$i++;}
?>
</SELECT>
<SELECT name = 's_year'>
<?php
$curYear = getdate();
for($year = 2016 ; $year <= $curYear['year']; $year++){
?>
<OPTION value = '<?php echo $year;?>'> <?php echo $year;?> </OPTION>
<?php
}
?>
</SELECT>
End date -> Same as Start date
<input type = 'Submit' name = 'edit-adv' value = 'Update'><br><br>
<button onclick="goBack()">Back</button>
</form>
And finally the update function page
$ad_id = $_POST["ad_id"];
$pos_name = $_POST["Pos_Name"];
$job_des = $_POST["Job_Des"];
$job_qua = $_POST["Job_Quali"];
$skill_req = $_POST["Skill_Req"];
$salary = $_POST["Salary"];
$s_date = $_POST["s_year"].'/'.$_POST["s_month"].'/'.$_POST["s_day"];
$e_date = $_POST["e_year"].'/'.$_POST["e_month"].'/'.$_POST["e_day"];
$sql = ("UPDATE advertisement SET Position_Name = '".$pos_name."',
Ad_Job_Description = '".$job_des."', Ad_Job_Qualification =
'".$job_qua."', Ad_Skill_Required = '".$skill_req."',
Position_Salary_Detail = '".$salary."', Start_date = '".$s_date."',
End_date = '".$e_date."' WHERE Ad_ID = '".$ad_id."'");
Which I have no idea what is wrong in $sql line or what.
I tried to echo $sql and nothing is there so it means that no value in $sql right?
How to solve this problem?
Thank you in advance !!!
Ps. sorry for a long code post
in new version
Connection
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWD);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysqli_select_db($con, DB_NAME) or die('Could not select database.' . mysql_error());
and then like this update your db table
$qr = mysqli_query($con, "UPDATE advertisement SET Position_Name= '$pos_name',Ad_Job_Description= '$job_des' WHERE Ad_ID= '$ad_id' ");

editing and deleting records in a database using radio buttons

<?php
$user_name = "root";
$password = "";
$database = "my_db";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if(isset ($_POST['name']))
{
$name = $_POST['name'];
if(mysql_query("INSERT INTO persons VALUES(' ' , '$name') "))
echo "Successful Insertion!";
else
echo "Please try again!";
}
$result = mysql_query("SELECT * FROM persons");
?>
<html>
<head>
<style type = "text/css">
li { list-style-type: none; display: inline; padding: 10px; text-align: center;}
</style>
</head>
<body>
<form action = " . " method = "POST">
Name: <input type = "text" name = "name"><br>
<input type = "submit" value = "Enter">
</form>
<form name = "delete_form" method = "POST" action = "delete.php" >
<input type = "submit" name = "deleteRecord" value = "Delete Record" />
</form>
<h1>List of Names</h1>
<table border = "1" width = "100%" cellpadding = "5" cellspacing = "2">
<tr>
<td><strong></strong></td>
<td><strong>ID</strong></td>
<td><strong>Company</strong></td>
<td><strong>Edit</strong></td>
<td><strong>Delete</strong></td>
</tr>
<?php while ($row = mysql_fetch_array($result)) { ?>
<tr>
<td><input type="radio" Name="id" value="<?php echo $row['id']; ?>" ></td>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo "<a href = 'edit.php?id=$row[id]'>edit</a>" ?></td>
<td><?php echo "<a href = 'delete.php?id=$row[id]'>delete</a>" ?></td>
</tr>
<?php } ?>
<form name = "edit_form" method = "POST" action = " edit.php?edit= "<?php echo $row['id'] ?> >
<input type = "submit" name = "editRecord" value = "Edit Record" />
</form>
</table>
<?php
while($row = mysql_fetch_array($result))
echo "<li>$row[id]</li> . <li>$row[name]</li> <li> <a href = 'edit.php?edit=$row[id]'>edit</a> </li> <li> <a href = 'delete.php?del=$row[id]'>delete</a></li> <br>";
?>
</body>
</html>
edit.php
<?php
$user_name = "root";
$password = "";
$database = "my_db";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$row = " ";
if (isset($_POST['id']))
{
// if there is an id sent through POST and it isn't null/empty, use that
$id = $_POST['id'];
$SQL = "SELECT * FROM persons WHERE id = '$id' ";
$result = mysql_query($SQL);
$row = mysql_fetch_array($result);
}
else
{
// otherwise use id sent through GET links
$id = $_GET['id'];
$SQL = "SELECT * FROM persons WHERE id = '$id' ";
$result = mysql_query($SQL);
$row = mysql_fetch_array($result);
}
if(isset($_POST['newName']))
{
$id = $_POST['id'];
$newName = $_POST['newName'];
$SQL = "UPDATE persons SET name = '$newName' WHERE id = '$id' ";
$result = mysql_query($SQL) or die("Could not update database" . mysql_error());
echo "<meta http-equiv = 'refresh' content = '0 ; url = index.php'>";
}
?>
<form action = " edit.php" method = "POST">
ID: <input type = "text" name = "id" value = "<?php echo $row[0] ?>"<br><br>
Name: <input type = "text" name = "newName" value = "<?php echo $row[1] ?>"<br><br>
<input type = "submit" value = "Update">
</form>
Hello,
The code above shows how to edit and delete records in a database. Originally, the edit and delete options were in the form of links to a php script which performed the required action. The ID number of the selected row gets passed to the edit or delete php file which then does the action that the user selects (refer to the comments in the code above) I am now trying to modify this code so that I can use a radio button to select a record and then edit or delete the record using radio buttons. I know this sounds trivial but I am having some difficulty with it. Any assistance would be greatly appreciated. Thank you.
Hello Tom. I have made the changes that you suggested but I it still giving the same problem. I have included the edit.php file in case you want to have a look.
The value of your radio buttons needs to contain the ID of the record to be edited.
<td><INPUT TYPE="Radio" Name="radio" value="<?php echo $row['id']; ?>"></td>
Then when you submit the form, you will know the record you are editing has id of value $_POST['radio'].
Though you are already using GET method to pass IDs (through your edit and delete links). I would recommend having consistency, and passing all IDs with parameter id. So
Use this
<td><?php echo "<a href = 'edit.php?id=$row[id]'>edit</a>"; ?></td>
<td><?php echo "<a href = 'delete.php?id=$row[id]'>delete</a>"; ?></td>
And this
<td><input type="radio" name="id" value="<?php echo $row[id]; ?>"></td>
Then in edit.php and delete.php, check to see if an ID was passed through POST (if someone submitted the form) or through GET (they clicked a link), then use whichever has a value.
<?php
if (!empty($_POST['id']))
{
// if there is an id sent through POST and it isn't null/empty, use that
$id = $_POST['id'];
}
else
{
// otherwise use id sent through GET
$id = $_GET['id'];
}
I should also mention that mysql_fetch_array is deprecated and you should be using PDO or MySQLi. Read more here: http://www.php.net/mysql_fetch_array

How to edit, delete and add in php mysql without jquery or java script?

I am trying to delete , edit and add new recodes on the same page but it seems am failing to make it work .And I do not want to do it using ajax jquery or java script but only php .I need some help please below are my code :
<?php
include_once('con.php');
$strSQL = "SELECT film_id, name
from
filmsbox";
$rs = mysql_query($strSQL);
echo "<table border='1' ><tr bgcolor='#eeeeee'><td>Name</td> <td colspan='2'>Action</td></tr>";
while($row = mysql_fetch_assoc($rs))
{
$film_id = $row['film_id'];
$name = $row['name'];
$hometeam= mysql_real_escape_string($name);
echo "<tr bgcolor='#eeeee'><td>$name</td> <td><a href='index.php?film_id=$film_id' name ='edit'>Edit</a></td><td><a href='index.php?film_id=$film_id' name ='delete'>Delete</a></td></tr>";
}
?>
<?php
$strSQL = "SELECT film_id, name
from
filmsbox";
$rs = mysql_query($strSQL);
$row = mysql_fetch_assoc($rs);
$film_id= $row['film_id'];
$name = $row['name'];
$name = mysql_real_escape_string($name);
$film_id= $_GET['film_id'];
?>
<?php
if(isset($_POST['edit'])){
?>
<table>
<form action="index.php" method="post">
<tr>
<td>
Name
</td>
<td>
<input type = "text" name = "name" value="<?php echo $name;?>">
</td>
</tr>
<input name="film_id" type="hidden" id="film_id" value="<?php echo $film_id; ?>">
<tr>
<td>
<input type = "submit" name = "submit" value="update">
</td>
</tr>
<?php
$name = (isset($_POST['name']))? trim($_POST['name']): '';
$film_id = $_POST['film_id'];
$sql = "UPDATE filmsbox SET name='$name'
WHERE film_id ='$film_id'";
$result = mysql_query($sql);
if($result)
{
echo "Success";
}
else
{
echo "Error";
}
}
?>
<?php
/*Delete section*/
if(isset($_POST['delete']))
{
$film_id = $_GET['film_id'];
$delete = "DELETE FROM filmsbox WHERE film_id = '$film_id'";
$result = mysql_query($delete);
if($result)
{
echo "Record deleted successfuly ";
}
else
{
echo "No data deleted";
}
}
?>
Couple of pointers:
You only need to escape values before they go into the database, not when they come out and are used in HTML i.e $hometeam = mysql_real_escape_string($name);
You are pulling the same query from the database twice in quick succession which is not needed. You can remove one of the 2 $strSQL = "SELECT film_id, name
from
filmsbox";
$rs = mysql_query($strSQL); sections from the top of your code
You need to run any update/delete queries on the data before you then do your select query to pull out the records for the page, otherwise your changes will not be shown
You should be escaping the values for your update and delete queries to prevent SQL injection
Edit:
To reload the page in an edit mode, you need to change the link URL in the table to something like
<a href='index.php?film_id=$film_id&edit=1' name ='edit'>Edit</a>
Then your edit block needs to be
if ($_GET['edit']) {
I want to be clear this is not in any way a secure method of editing values, as anyone can put ?edit=1 on the url and get to the form

Categories