PHP - Can't update information from table - php

I can't change the information from my database.
I'm trying to update information from my database. But it's not working.
The user just need to put one existing ID from the table, and it will update the information from the specific column, in this case, it's a column called "titulo".
Here my page code:
<?php
if(isset ($_POST['submit']))
{
include("../classes/administrador/Administrador.class.php");
$Administrador = new Administrador();
if ($Administrador->atualizarCD($_REQUEST['id'],$_REQUEST['titulo']))
{
echo "It works !!!<br>";
} else {
echo "its not working<br>";
}
$Administrador->endAdministrador();
}
else{
?>
<b>Alterar CD</b><br><br>
<form name="form3" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<b>ID</b>:
<input type="text" name="id" size="3">
<br>
<br>
<b>Titulo</b>:
<input type="text" name="titulo">
<br>
<input type="submit" name="submit" value="submit">
</form>
<p> </p>
<?php
}
?>
And my function code:
function atualizarCD($id, $titulo) {
$sql= "UPDATE `cds` SET `titulo` = '$titulo' WHERE `ID` = '$id";
if($this->bd->executarSQL($sql)) return true;
else return false;
}

You have missed to add ' end of the query
$sql= "UPDATE `cds` SET `titulo` = '$titulo' WHERE `ID` = '$id' ";

Related

How to set unique id on html form in while loop

How I can set unique id for html form which is in while loop, and get this id when check is the form is submit? You can check out my code:
while($row_lessons = mysqli_fetch_assoc($queryLessons)) {
echo 'someinfohere';
if(isset($_POST['buy'])) {
mysqli_query($link, "UPDATE users SET credits = credits - ".$row_lessons['price']." WHERE id = '".$_SESSION['userid']."' ");
mysqli_query($link, "INSERT INTO `lessonpurchases` (lesson_id, user_id, date) VALUES ('".$row_lessons['id']."', '".$_SESSION['userid']."', '".time()."')") or die(mysqli_error($link));
}
echo '
Цена: '.levche($row_lessons['price']).'лв. <br />
<form action="" method="post">
<input type="submit" name="buy" value="Купи" />
</form>';
}
The unique id is needed, because when submit the form the mysql queries are being executed for all results in loop.
If you want to keep it simple:
$i = 1;
while($row_lessons = mysqli_fetch_assoc($queryLessons)) {
echo 'someinfohere';
if(isset($_POST['buy'.$i])) {
mysqli_query($link, "UPDATE users SET credits = credits - ".$row_lessons['price']." WHERE id = '".$_SESSION['userid']."' ");
mysqli_query($link, "INSERT INTO `lessonpurchases` (lesson_id, user_id, date) VALUES ('".$row_lessons['id']."', '".$_SESSION['userid']."', '".time()."')") or die(mysqli_error($link));
}
echo '
Цена: '.levche($row_lessons['price']).'лв. <br />
<form action="" method="post">
<input type="submit" name="buy'.$i.'" value="Купи" />
</form>';
$i++;
}
You can use uniqid() as follow
$formId = uniqid();
In your form you can use it like
<form action="" method="post" id="<?php echo $formId;?>">
<input type="hidden" name="formId" value="<?php echo $formId;?>" />
<input type="submit" name="buy" value="Купи" />
</form>
On form submission you will get the formId by using $_REQUEST['formId']

IF condition not working in UPDATE query

In this code when I want to update the status from Pending to Accepted that time If statement not working.
In database I keep Pending by default. Problem is that when I'm going to update the status the STATUS will update but the code inside the If condition can't work.
please help me out from this problem.
Thanks in advance.
<?php
include("connect.php");//conection
if(isset($_REQUEST['leave_id']))
{
$id=$_REQUEST['leave_id'];
}
else
{
$id=NULL;
}
$result = mysqli_query($con,"SELECT TAKEN_LEAVES,BALANCE_LEAVE,STATUS
FROM xxxemi_person_leave_t
WHERE leave_id= $id");
$res = mysqli_fetch_array($result);
if (!$result)
{
die("Error: Data not found..");
}
$taken_leave = $res['TAKEN_LEAVES'];
$balance_leave = $res['BALANCE_LEAVE'];
$status = $res['STATUS'];
if(isset($_POST['save']))
{
if ($status=='ACCEPTED')
{
$status = $_POST['USTATUS'];
$updated_balance_leave = $_POST['UBALANCE_LEAVE'];
$updated_balance_leave = $balance_leave - $taken_leave;
mysqli_query($con,"UPDATE xxxemi_person_leave_t
SET STATUS ='$status', BALANCE_LEAVE ='$updated_balance_leave'
WHERE leave_id = '$id' ");
echo "<script>alert('Your Record Updated');</script>";
}
else
{
$status = $_POST['USTATUS'];
mysqli_query($con,"UPDATE xxxemi_person_leave_t
SET STATUS ='$status'
WHERE leave_id = '$id' ");
echo "<script>alert('Your Record Updated');</script>";
}
}
mysqli_close($con);
?>
/**************PHP CODE *******/
<form method="post">
<td><input type="hidden" name="id" value=<?php echo $_GET['leave_id'];?>>
<input type="hidden" name="UBALANCE_LEAVE" value="<?php echo $updated_balance_leave;?>">
<input type="checkbox" name="USTATUS" value="ACCEPTED" />
<img src="images/Approved.png" />
<input type="checkbox" name="USTATUS" value="REJECTED" />
<img src="images/Rejected.png" /></td>
<input type="submit" name="save" value="Update">
</form>
/************* HTML CODE**********/
It seems that ,you are using $statu = $res['STATUS']; // STATUS
$statu for STATUS, but in if condition you are checking for $status
Change This
if ($status=='ACCEPTED')
To
if($_POST['USTATUS']=='ACCEPTED')
AND type="checkbox" TO type="radio"

Increment id on click in MySQL

I have a problem to visualize the solution for the problem that I have now.
The user is allowed to insert a row in a table.
And I try to display a button (input) +1 who allow the user to increment a column (vote) in a selected row among all created.
The problem is that I don't get the thing for rely incrementation to the desired id.
Here my code :
<form action="" method="post">
<input type="text" name="disease">name
<input name="mainsubmit" type="submit" value="submit">
</form>
</body>
</html>
<?php
if(isset($_POST['mainsubmit']))
{
$nameDisease = $_POST['disease'];
$req = $db->prepare('INSERT into disease(name) VALUES(:name)');
$req->execute(array('name' => $nameDisease));
}
$query = $db->query('SELECT * FROM disease');
while ($result = $query->fetch())
{
$id = $result['id'];
echo $id ?>
<form action="" method="post"> <input name="secondsubmit" type="submit" value="+1"> </form><?php
if(isset($_POST['secondsubmit']))
{
$db->exec("UPDATE disease SET vote = vote + 1 WHERE id = " .$id);
}
}
Logically, the code above doesn't work but I don't understand how find the solution.
In brief, i want to allow the user to increment a column in a selected row.
Thanks
Edit: Shadow, it's not my problem because your solution is used for automatically chose between INSERT or UPDATE if the line doesn't exist or exist. Me, I want allow the user to create rows and allow he to vote +1 on each of one that exist, and it will not be possible for he to insert a row from the input +1.
I created code snippet similar to your code style.
You have two submit buttons so you need to separate handling of those two requests.
The $id of the item you want to update in the second submit need's to come from hidden value in form.
In order for this to work you need to create table in mysql:
create table disease (id MEDIUMINT NOT NULL AUTO_INCREMENT, name VARCHAR(20), vote INTEGER, PRIMARY KEY (id)); - for example like this
<html>
<body>
<form action="" method="post">
<input type="text" name="disease">name
<input name="mainsubmit" type="submit" value="submit">
</form>
</body>
</html>
<?php
$db = new PDO('mysql:dbname=phpapp;host=db', 'root', 'phpapptest');
if (isset($_POST['mainsubmit'])) {
$nameDisease = $_POST['disease'];
$req = $db->prepare('INSERT into disease (name, vote) VALUES(:name, 0)');
$req->bindParam(':name', $nameDisease);
$req->execute();
$query = $db->query('SELECT * FROM disease');
while ($result = $query->fetch()) { ?>
<form action="" method="post">
<p><?php echo $result['name'] . " : " . $result['vote'];?>
<input name="secondsubmit" type="submit" value="+1" />
<input type="hidden" name="id" value="<?php echo $result['id'];?>" />
</p>
</form>
<?php }
}
if (isset($_POST['secondsubmit'])) {
$req = $db->prepare("UPDATE disease SET vote = vote + 1 WHERE id = " . $_POST['id']);
$req->execute();
$query = $db->query('SELECT * FROM disease');
while ($result = $query->fetch()) {?>
<form action="" method="post">
<p><?php echo $result['name'] . " : " . $result['vote'];?>
<input name="secondsubmit" type="submit" value="+1" />
<input type="hidden" name="id" value="<?php echo $result['id'];?>" />
</p>
</form>
<?php }
}
?>

how to get the last inserted id and how to check in where condition to update query using php

Hi iam inserting the data into database table and redirecting to another page and need to insert the details into the same table by comparing ids and email.But how to get the last inserted id and compare in where condition to update the details.
Here is my code:
index.php
<form method="post" action="properties.php" id="myform">
<input type='hidden' value="<?php echo $username; ?>" name='email'>
<tr><th>Interest Paid</th><td><input type="text" name="house_interest_paid" value=""/></td>
<tr><th>Total Interest Paid</th><input type="text" name="house_total_interest_paid" value=""/></td>
<tr><th>House Number</th><input type="text" name="house_number" value=""/></td>
<tr><th>Street</th><input type="text" name="house_street" value=""/></td>
<button type="submit" class = "large awesome yellows" onClick="document.location.href='ownerproperty.php'"> Specify Co-owners Property</button> </span>
</form>
properties.php
$email=$_POST['email'];
$interest=$_POST['house_interest_paid'];
$interestpaid=$_POST['house_total_interest_paid'];
$number=$_POST['house_number'];
$street=$_POST['house_street'];
$query=mysql_query("INSERT INTO house_details(email,house_interest_paid,house_total_interest_paid,house_number,house_street)values ('$email','$interest','$interestpaid','$number','$street')");
if($query)
{
session_start();
header("Location:ownerproperty.php");
}
else{
echo "Registration has not been completed.Please try again";
}
ownerproperty.php
<form style="display:none" method="POST" action="owner.php">
<h2>Owner Property details</h2>
<input type='hidden' value="<?php echo $username; ?>" name='email'>
<?php include "ownership.php"; ?>
<p><label for="name_coowner">Coowner Name</label> <input value="<?php echo $row['name_coowner'];?>" type="text" name="name_coowner" /></p>
<p><label for="pan_coowner">PAN Of Coowner</label> <input value="<?php echo $row['pan_coowner'];?>" type="text" name="pan_coowner" /></p>
<button type="submit" class = "medium" style="background-color: #2daebf;">Save</button>
</form>
Ownership.php
$res = "SELECT * FROM house_details
WHERE email ='$username'";
$result=mysql_query($res);
$row = mysql_fetch_array($result);
Owner.php
$email=$_POST['email'];
$owner_name=$_POST['name_coowner'];
$pan_owner=$_POST['pan_coowner'];
$query=mysql_query("UPDATE house_details SET name_coowner='$owner_name',pan_coowner='$pan_owner'
WHERE email='$email' AND house_details_id='2'");
if($query)
{
session_start();
header("Location:rentalproperty.php");
}
For the first time when i click on submit button the data is inserting into db and redirecting to ownerproperty.php .in that i need to get the inserted id and need to comapre that id and email and need to update the owner property details in the same column when the email and id are same.But how to get that id and compare in the where condition can anyone help me.
properties.php
$query=mysql_query("INSERT INTO house_details(email,house_interest_paid,house_total_interest_paid,house_number,house_street)values ('$email','$interest','$interestpaid','$number','$street')");
$id = mysql_insert_id(); //For last inserted id.
if($query)
{
session_start();
$_SESSION['sess_id'] = $id; // Set one session variable for last inserted id.
header("Location:ownerproperty.php");
}
owner.php
<?php
session_start(); // Start your session
$id = $_SESSION['sess_id']; // Use this id in query
$email=$_POST['email'];
$owner_name=$_POST['name_coowner'];
$pan_owner=$_POST['pan_coowner'];
$query=mysql_query("UPDATE house_details SET name_coowner='$owner_name',pan_coowner='$pan_owner'
WHERE email='$email' AND house_details_id='2'");
if($query)
{
session_start();
header("Location:rentalproperty.php");
}
[NOTE : mysql extensions are deprecated. Use PDO or mysqli_ database extensions.]
You can add this:
$stmt = 'SELECT LAST_INSERT_ID() as sessionId';
Which should grab the ID from the last insert.
$query=mysql_query("INSERT INTO house_details(email,house_interest_paid,house_total_interest_paid,house_number,house_street)values ('$email','$interest','$interestpaid','$number','$street')");
if($query)
{
//Last inserted ID
$last_id = $query->insert_id;
session_start();
header("Location:ownerproperty.php");
}
else{
echo "Registration has not been completed.Please try again";
}
You can add this:
$stmt = 'SELECT MAX(house_details_id) AS "id" FROM house_details';
$result=mysql_query($stmt);
$row = mysql_fetch_array($result);
$id = $row['id'];

Editing a form in MySQL and PHP

I am working on a project. What I need to do is basically enter some info into a form, have that form save it into a database, display the data, and then be able to edit the data. So far, I am able to do everything except edit the data. I've tried using $_GET to get the ID of the particular "bug" I need to edit, and I am able to do that, and get all of the information but I am not sure how to edit that particular ID in my database. Here is my handler: http://pastebin.com/mR6QWpJ7 and my form:
<form action="week10handle.php" method="POST">
<fieldset width="300px">
<legend width="300px"><b>Add a bug report</b></legend>
Product Name:<br/><input type="text" name="product_name"><br/>
Product Version: <br/><input type="text" name="product_version"><br/>
Hardware Type: <br/><input type="text" name="hardware"><br/>
Operating System: <br/><input type="text" name="os"><br/>
Frequency: <br/><input type="text" name="frequency"><br/>
Proposed Solutions: <br/><textarea name="solutions"></textarea><br/>
<input type="submit" value="Submit">
</fieldset>
</form>
Here is where I obtain the get data in my edit form page so far, but as of right now, I am not sure how to edit a particular ID in the database.
$getbug = htmlspecialchars($_GET["bugid"]);
if (!empty($getbug)){
$getbuginfo = mysql_query("SELECT * FROM `bugs` WHERE `id`= '$getbug'");
if ($getbuginfo = mysql_fetch_assoc($getbuginfo)){
$edit_product_name = $getbuginfo['product_name'];
$edit_prod_version = $getbuginfo['product_version'];
$edit_hardware = $getbuginfo['hardware_type'];
$edit_os = $getbuginfo['os'];
$edit_frequency = $getbuginfo['frequency'];
$edit_solutions = $getbuginfo['solutions'];
?>
<form action="week10handle.php" method="POST">
<fieldset width="300px">
<legend width="300px"><b>Edit bug <?php echo $getbug;?></b></legend>
Product Name:<br/><input type="edit" name="product_name" value="<?php echo $edit_product_name;?>"><br/>
Product Version: <br/><input type="edit" name="product_version" value="<?php echo $edit_prod_version;?>"><br/>
Hardware Type: <br/><input type="edit" name="hardware" value="<?php echo $edit_hardware;?>"><br/>
Operating System: <br/><input type="edit" name="os"value="<?php echo $edit_os;?>"><br/>
Frequency: <br/><input type="edit" name="frequency"value="<?php echo $edit_frequency;?>"><br/>
Proposed Solutions: <br/><textarea name="solutions"><?php echo $edit_product_name;?></textarea><br/>
<input type="submit" value="Submit">
</fieldset>
</form>
EDIT: Here is my update php code, but it is still not working, when I submit my form, it refreshes the page, but it doesn't update the database:
<?php
if (mysql_connect('localhost','root','') && mysql_select_db('bug_reports')){
$errors = array();
if (isset($_POST['product_name'], $_POST['product_version'],$_POST['hardware'],$_POST['os'],$_POST['frequency'], $_POST['solutions'])){
$product_name = mysql_real_escape_string(htmlentities($_POST['product_name']));
$product_version = mysql_real_escape_string(htmlentities($_POST['product_version']));
$hardware = mysql_real_escape_string(htmlentities($_POST['hardware']));
$os = mysql_real_escape_string(htmlentities($_POST['os']));
$frequency = mysql_real_escape_string(htmlentities($_POST['frequency']));
$solutions = mysql_real_escape_string(htmlentities($_POST['solutions']));
$getbug = mysql_real_escape_string(htmlentities($_POST['bugid']));
if (empty($product_name) || empty($product_version) || empty($hardware) || empty($os) || empty($frequency) || empty($solutions)){
$errors[] = 'All fields are required.';
}
if (!is_numeric($product_version) || !is_numeric($frequency)){
$errors[] = 'Product version and frequency must both be numbers';
}
if (empty($errors)){
$update = "UPDATE `bugs` SET `product_name` = '$product_name', `product_version = '$product_version', `hardware_type = '$hardware', `os` = '$os', `frequency` = '$frequency', `solutions` = '$solutions' WHERE `id` = $getbug";
if ($update = mysql_query($update)){
header('Location: week10handle.php');
} else{
$errors[] = 'Something went wrong, please try again.';
}
} else{
foreach($errors as $error){
echo '<p><strong>'.$error.'</strong></p>';
}
}
}else{
$getbug = htmlspecialchars($_GET["bugid"]);
}
if (!empty($getbug)){
$getbuginfo = mysql_query("SELECT * FROM `bugs` WHERE `id`= '$getbug'");
if ($getbuginfo = mysql_fetch_assoc($getbuginfo)){
$bugid = $getbuginfo['id'];
$edit_product_name = $getbuginfo['product_name'];
$edit_prod_version = $getbuginfo['product_version'];
$edit_hardware = $getbuginfo['hardware_type'];
$edit_os = $getbuginfo['os'];
$edit_frequency = $getbuginfo['frequency'];
$edit_solutions = $getbuginfo['solutions'];
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<fieldset width="300px">
<legend width="300px"><b>Edit bug <?php echo $getbug;?></b></legend>
Product Name:<br/><input type="edit" name="product_name" value="<?php echo $edit_product_name;?>"><br/>
Product Version: <br/><input type="edit" name="product_version" value="<?php echo $edit_prod_version;?>"><br/>
Hardware Type: <br/><input type="edit" name="hardware" value="<?php echo $edit_hardware;?>"><br/>
Operating System: <br/><input type="edit" name="os"value="<?php echo $edit_os;?>"><br/>
Frequency: <br/><input type="edit" name="frequency"value="<?php echo $edit_frequency;?>"><br/>
Proposed Solutions: <br/><textarea name="solutions"><?php echo $edit_product_name;?></textarea><br/>
<input type="hidden" name="bugid" value="<?php echo $bugid;?>" >
<input type="submit" value="Update">
</fieldset>
</form>
<?
}else{
echo "something went wrong";
}
}else{
echo "No bug found.";
}
}else
echo 'Could not connect at this time.';
?>
A typical way to detect an update, as opposed to an insert, would be to check for a value for id. So, in your edit form add a hidden field to pass the id to the handler and then in your handler you can decide whether to process it as insert or update based on the presence of the id field.
if (isset($_GET['id']) {
// do update
$sql = 'UPDATE `bugs` SET ... WHERE id = ' . intval($_GET['id']);
} else {
// do insert
$sql = 'INSERT INTO `bugs` VALUES ....';
}
UPDATE `bugs` SET `product_name` = '...', `product_version` = '...', ... WHERE `id` = $bugid;
Where the "..." will be replaced with newly $_POST-ed values for each column

Categories