I'm trying to edit data(stored in DB). This is display.php. First it displays data from DB (if no data then blank fields). Then edit button to edit DB.
<html>
<body>
<?php
if(!isset($_POST['edit_pro']))
{
?>
//get data from DB and display in table.
<form>
<input type="submit" name= "edit" value="edit">
</form>
<?php
}
else
{
?>
<form name="edit_DB" action="edit.php">
//edit ...2 <select> fields and 1 text field.
//submit button
</form>
<?php
}
?>
And in edit.php
i simply update the DB. But what if i want to change only 1 field.(problem is all fields gets updated).Here's edit.php
<?php
include_once 'db_connect.php';
$db_con = dbConnect("dbname");
$uid = $_SESSION['uid'];
if(isset($_POST['edit']))
{
$c = $_POST['c'];
$s = $_POST['list'];
$t = $_POST['nm'];
$a = $_POST['a'];
$sql = "UPDATE `user` SET `c` = ?, `s` = ?, `t` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute(array($c,$s,$t,$uid));
header("Location:display.php");
}
?>
$sql = "UPDATE `user` SET `c` = ?, `s` = ?, `t` = ? WHERE u_id = ?";
this query means:
update table user
for each row in this table where u_id = [some value]
set fields C and S and T to some other distinct values
so, your query updates 3 fields at one time, and it is ok, as it what it should do
if you want to change this logic, to update only some fields you need to change query and arguments, for example if you want to change only c use:
$sql = "UPDATE `user` SET `c` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute(array($c, $uid)); // this array binds values to question marks, so count should be the same, we have 2 ? - we must use 2 variables
for c AND t:
$sql = "UPDATE `user` SET `c` = ?, `t` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute();
if you don't know exactly how many arguments will be, you need dynamic query building, like:
$arr = array();
$sqlA = array();
if (isset($_POST['c']) && $_POST['c']) {
$arr[] = $_POST['c'];
$sqlA[] = '`c`=?';
}
if (isset($_POST['s']) && $_POST['s']) {
$arr[] = $_POST['s'];
$sqlA[] = '`s`=?';
}
if (isset($_POST['t']) && $_POST['t']) {
$arr[] = $_POST['t'];
$sqlA[] = '`t`=?';
}
if (count($arr)) {
$sql = 'UPDATE `user` SET '.implode($sqlA, ',').' where u_id = ?';
$arr[] = $uid;
$q = $db_con->prepare($sql);
$q->execute($arr);
}
That means that WHERE clause of the request doesn't work. Check if you passing a quotation marks " in you variable $t so you close $sql before WHERE clause
Related
I am working on a project that takes students attendance in class and I want to update the database data through PHP whilst running a SQL function of UPDATE, but I want to be able to update it base on the id of the data.
This is the code that I am working with at the moment.
<?php
require_once './dba.php';
$status = "";
if(isset($_POST['time_in'])) {
$query = "INSERT INTO nameOfTable (datetime) VALUES (NOW())";
$d = $conn->prepare($query);
$d->execute();
} elseif(isset($_POST['time_out'])) {
$query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = ? ";
$d = $conn->prepare($query);
$d->execute();
} else {
$status = "Can't time in!";
}
Use $conn->lastInsertId() to get the ID that was assigned when they clocked in. Save that in a session variable and use it when they clock out.
<?php
require_once './dba.php';
$status = "";
if(isset($_POST['time_in'])) {
$query = "INSERT INTO nameOfTable (datetime) VALUES (NOW())";
$d = $conn->prepare($query);
$d->execute();
$_SESSION['clock_id'] = $conn->lastInsertId();
} elseif(isset($_POST['time_out'])) {
if (!isset($_SESSION['clock_id'])) {
$status = "You need to clock in first!";
} else {
$query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = :id ";
$d = $conn->prepare($query);
$d->execute(['id' => $_SESSION['clock_id']]);
}
} else {
$status = "Can't time in!";
}
You must remember to prepare the query and bind the parameters onto it.
Use the $id variable to prepare the query with the appropriate ID.
Make sure you authenticate the session before passing the ID to the query, otherwise an attacker can manipulate this data to pull anyone's data they wish.
// Its helpful to create elements within the code to bind onto. :id is ours.
$query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = :id ";
$d = $conn->prepare($query);
// Run the query & bind id to :id
$d->execute(['id' => $id]);
You try update
$query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = :id ";
$d = $conn->prepare($query);
$d->execute(['id' => $id ]);
I am facing a challenge right now.
I have a return page, if I selected the first row via the radio button, I would like to change the history_status inside my order history table from "DONE" to "RETURN PENDING". The reason why I am doing this is to run a query to show only history_status value with "DONE".
Below are the code I am working with:
<?php
$db = mysqli_connect('localhost','root','','customercaremodule');
date_default_timezone_set('Asia/Kuala_Lumpur');
$FBdate = date("Y-m-d H:i:s");
$sql = "SELECT p.product_id ,p.product_name , p.price, p.product_description, o.history_id ,o.qty , o.subtotal, o.history_datetime , o.history_status FROM product p, orderhistory o where o.product_id = p.product_id AND o.history_status = 'DONE'";
$result=mysqli_query($db,$sql);
$Cntsql = "SELECT count(return_id) AS total FROM retrn";
$res = mysqli_query($db,$Cntsql);
$value = mysqli_fetch_assoc($res);
$num = $value['total'];
if (isset($_POST['submitbuttonform']))
{
$return_id = $num+1;
$return_status = 'PENDING';
$return_reason = $_POST['reasonselected'];
$return_option = $_POST['returnoption'];
$return_datetime = $FBdate;
$history_id = $_POST['selectitemradio'];
$history_status = "UPDATE orderhistory SET history_status = 'RETURN PENDING'";
$sql = "INSERT INTO `retrn`(`return_id`, `return_status`, `return_reason`, `return_option`, `return_datetime`, `history_id`) VALUES ('$return_id','$return_status','$return_reason','$return_option','$return_datetime','$history_id')";
$sql = "INSERT INTO 'orderhistory'('history_status') VALUES ('$history_status')";
$result=mysqli_query($db,$sql);
Order History Table
Return page layout
From your code
$history_id = $_POST['selectitemradio']; I assume you get the history id from the page.
So you can use the history_id in the where clause. Now only the selected row will be updated.
UPDATE orderhistory SET history_status = 'RETURN PENDING' where history_id=$history_id
I want to make for each data exist on databases then do loop up to get unique data.
Here my code:
$id = rand(10000000,99999999);
$check_id = $db->prepare("SELECT * FROM sh_url WHERE sh_id='$id'");
$check_id->execute();
$count_id = $check_id->rowCount();
for ($count_id != 0) {
$lid = $id+1;
}
$shorturl = htmlentities(base_convert($lid,20,36));
$query = $db->prepare("INSERT INTO `sh_url`(`sh_id`) VALUES (:id)");
$query->bindParam(":id", $lid);
$query->execute();
Why don't you use distinct keyword to do this.
SELECT DISTINCT column1, column2, ...
FROM table_name;
When I click on the save button only all_university table updates but the all_colleges table has not been updated. How can I update two tables on one save button?
<?php
if(isset($_POST['save'])) {
$chk = implode(",", $_POST['company_name']);
$sql = "update all_university set placement = '$chk' where university_name = '".$_POST['university_name']."'";
$sql = "update all_colleges set placement = '$chk' where college_name = '".$_POST['college_name']."'";
$value = mysqli_multi_query($link,$sql);
if($value == true){
$msg .="<h5 style='color:green'>Successfull</h5>";
} else {
$msg .="<h5 style='color:red'>Error!</h5>";
}
}
?>
It doesn't matter how many queries you have. Just run them all one by one.
Besides, you should be using prepared statements.
<?php
if(isset($_POST['save'])) {
$chk = implode(",", $_POST['company_name']);
$sql = "update all_university set placement = ? where university_name = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("ss", $chk, $_POST['university_name']);
$stmt->execute();
$sql = "update all_colleges set placement = ? where college_name = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("ss", $chk, $_POST['college_name']);
$stmt->execute();
$msg .="<h5 style='color:green'>Successfull</h5>";
}
DO NOT use mysqli_multi_query(). It will do you no good and won't work the way you think.
If you want to use the multi-query function, you have to concatenate the two query strings:
$sql = "update all_university set placement = '$chk' where university_name = '".$_POST['university_name']."';";
$sql .= "update all_colleges set placement = '$chk' where college_name = '".$_POST['college_name']."'";
And then execute mysqli_multi_query.
Or, as Rory already mentioned, just query twice using the normal mysqli_query function.
But you should really look into prepared statements as you are vulnerable to SQL injection!
Separate both query with semicolon (;)
$sql = "update all_university set placement = '$chk' where university_name = '".$_POST['university_name']."';";
$sql = "update all_colleges set placement = '$chk' where college_name = '".$_POST['college_name']."'";
Then, Append Both Query.
$sql = "update all_university set placement = '$chk' where university_name = '".$_POST['university_name']."'";
$sql .= "update all_colleges set placement = '$chk' where college_name = '".$_POST['college_name']."'";
Execute it.
$value = mysqli_multi_query($link,$sql);
The mysqli_multi_query() function performs one or more queries against
the database. The queries are separated with a semicolon.
can you say me where are i am making mistakes in this simple query
$q = "UPDATE users SET ".$aItemSlot." = '$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$q = "UPDATE items SET item_position='3' WHERE it_id='$seton'";
$r = #mysqli_query($dbc, $q);
error-
1064 - You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''$aItemSlot' = '$seton' WHERE username='$us'' at line 1
Here is my source
$q = "SELECT * FROM users WHERE username='$us'";
$r = #mysqli_query($dbc, $r);
$row = mysqli_fetch_array($r);
$aHelmet_Slot = $row['helmet_slot'];
$aShield_Slot = $row['shield_slot'];
$aWeapon_Slot = $row['weapon_slot'];
$aGloves_Slot = $row['g1loves_slot'];
$aShoes_Slot = $row['shoes_slot'];
$aArmor_Slot = $row['armor_slot'];
$aEar_Slot = $row['ear_slot'];
$aBelt_Slot = $row['belt_slot'];
$aRing1_Slot = $row['ring1_slot'];
$aRing2_Slot = $row['ring2_slot'];
$aRing3_Slot = $row['ring3_slot'];
$aRing4_Slot = $row['ring4_slot'];
$aCharLevel = $row['char_lvl'];
if ($aItemSlot == 'ring_slot'){
if($aCharLevel >= $aItem_Level){
$NotEmpty = false;
if ($aRing1_Slot == 0){
$q = "UPDATE users SET ring1_slot='$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$NotEmpty = true;
}
if (($aRing2_Slot == 0) && (!$NotEmpty)){
$q = "UPDATE users SET ring2_slot='$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$NotEmpty = true;
}
if (($aRing3_Slot == 0) && (!$NotEmpty)){
$q = "UPDATE users SET ring3_slot='$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$NotEmpty = true;
}
if(($aRing4_Slot == 0) && (!$NotEmpty)){
$q = "UPDATE users SET ring4_slot='$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$NotEmpty = true;
}
if(!$NotEmpty){
$q = "UPDATE items SET item_position='2' WHERE it_id='$aRing1_Slot'";
$r = #mysqli_query($dbc, $q);
$q = "UPDATE users SET ring1_slot='$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$NotEmpty = true;
}
$q = "UPDATE items SET item_position='3' WHERE it_id='$seton'";
$r = #mysqli_query($dbc, $q);
}
}
else
{
if ($aCharLevel >= $aItem_Level){
$link_slot_var = "a" .$aItemSlot;
$aSlotItemID = $$link_slot_var;
if($aSlotItemID <> 0){
$q = "UPDATE items SET item_position='2' WHERE it_id='$aSlotItemID'";
$r = #mysqli_query($dbc, $q);
}
$q = "UPDATE users SET '$aItemSlot' = '.$seton.' WHERE username='$us'; // it fails there
$r = #mysqli_query($dbc, $q);
$q = "UPDATE items SET item_position='3' WHERE it_id='$seton'";
$r = #mysqli_query($dbc, $q);
}
}
There Should not be a $ symbol before the mysql database field name it should be something like this
UPDATE users SET aItemSlot = '".$seton."' WHERE username='".$us."'
Modify your query in the above format and try to execute
Why do you use a table name as variable?
{$aItemSlot}
In general it should be like this:
$mysqli->query("Update users
set aItemSlot = '$seton'
where username = $us
") ;
Also, try to use prepared statements.
UPDATE
Make update of the row which related to this table:
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
UPDATE statement updates columns of existing rows in the named table
with new values. The SET clause indicates which columns to modify and
the values they should be given. Each value can be given as an
expression, or the keyword DEFAULT to set a column explicitly to its
default value. The WHERE clause, if given, specifies the conditions
that identify which rows to update. With no WHERE clause, all rows are
updated. If the ORDER BY clause is specified, the rows are updated in
the order that is specified. The LIMIT clause places a limit on the
number of rows that can be updated.
You can also perform UPDATE operations covering multiple tables.
UPDATE items,month SET items.price=month.price
WHERE items.id=month.id;
UPDATE2
You need to check/update each row.
$stmt = $mysqli->prepare("UPDATE table SET col1 = ?, col2 = ?, col3 = ? WHERE id = ? ")
$stmt->bind_param('sssi', $var1, $var2, $var3, $id);
This shows what you need to do.
You missed assignment operator :
UPDATE users SET " . $aItemSlot . " = '" . $seton . "' WHERE username='$us'";
Your query should be like this:
"UPDATE users SET " . $aItemSlot . "='$seton' WHERE username='$us'";
^ assignment operator
This is a valid syntax.. how ever you have to be sure that those params are VALID before making the query...
$sql = "UPDATE users SET {$aItemSlot} = '{$seton}' WHERE username = '{$us}'";
Try this, this will surely work
$q = "UPDATE users SET ".$aItemSlot." = " . $seton . " WHERE username= " . $us;
You will need to make some slight adjustments.
PHP/SQL
$q = "UPDATE users SET aItemSlot = '".$seton."' WHERE username='".$us."'";
// Or if $aItemSlot actually is a variable
$q = "UPDATE users SET '".$aItemSlot."'='".$seton."' WHERE username='".$us."'";
Bottom note: because $aItemSlot starts with an 'a' I am wondering if this is an array. In that case your script will fail saying that the array to string conversion has failed. If this is the case, check what value $aItemSlot holds using var_dump().