I am trying to update table and add data if it doesnt exist in the table row.
$data = "red flowers";
$id = "12";
mysql_query("update shares set data = data + '".$data."' WHERE id = '".$id."' LIMIT 1")
But it doesnt work. What is the correct way to do it ?
Use the REPLACE statement instead of UPDATE.
It works exactly the same as a INSERT statement, but it will replace the data if data with the same primary keys exists.
Ex:
mysqli_query("REPLACE INTO shares (id,data) values (".$id.",'".$data."')");
You should sanitize your data to avoid SQL Injection.
You need DELETE privileges for this statement to work
First of all mysql_query is deprecated use mysqli_query or PDO.
Secondly don't use simple sql statements while constructing query. Use prepared statement , thereby preventing your code from mysql injections.
Thirdly, use http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html for insert if doesn't exist else update case.
Related
I have a table where user can input dates. It correctly goes to database and Replace the previous input and display in the table.
Now I want to store all the user's inputs in database and display only the last input. I have a button called update.
I believe that it is something with this update button. Hope You can help me to solve this. Please help. Thanks
if(isset($_POST['update'])){
$UpdateQuery = "UPDATE `fiber`.`fiberexcel` SET Quotation11='$_POST[A12]',
ApprovalJFSRequest13='$_POST[A14]',
ApprovalJFSReceived15='$_POST[A16]',
JFSDone17='$_POST[A18]',
OFNtoSAQ19='$_POST[A20]',
ApprovalDrawing21='$_POST[A22]',
TechEvaluation23='$_POST[A24]' ,
AllQuotationsRecieved25='$_POST[A26]' ,
MailConfirmationWorkStart27='$_POST[A28]',
POReceived28='$_POST[A29]',
WorkApprovalRequest30='$_POST[A31]',
WorkApprovalReceived32='$_POST[A33]',
IBWStarted34='$_POST[A35]',
IBWCompleted36='$_POST[A37]',
HandOverContractor38='$_POST[A39]',
RequestAuthority40='$_POST[A41]',
EstimateReceivedDialog42='$_POST[A43]',
SystemPRRequested44='$_POST[A45]',
SystemPODone46='$_POST[A47]',
DocumentToFIN48='$_POST[A49]',
PaymentFin50='$_POST[A51]',
PaymentContractor52='$_POST[A53]',
PaymentAuthority54='$_POST[A55]',
OSPWorkStart56='$_POST[A57]',
OSPWorkComplete58='$_POST[A59]',
TestingCompleted60='$_POST[A61]',
Remarks65='$_POST[Remarks]'
WHERE `fiberexcel`.`SiteID0`='$_POST[hidden]'";
//echo($UpdateQuery);
mysqli_query($conn, $UpdateQuery);
};
First at all you have to change UPDATE query to INSERT query, make that primary key to be autoincrement as well. After that you can simply do
ORDER BY DATE_TO_ORDER LIMIT 1,1;
this will give you only 1st record which is actually newest insert to database.
And please dont use $_POST directly in your query because your code is now SQL injectable. Make new variables for each post and then insert them in query.
I really recommend you to use PDO prepared statements.
By 'change UPDATE to INSERT':
UPDATE QUERY:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
INSERT QUERY:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
I'm trying to update a mysql database with data I fetched. (btw I need to do this for specific individual items, but that's not the problem.) When it comes to creating separate statements for fetching or updating I can do that. Separately, I'm able to fetch data like this:
$query = "SELECT starting_amount FROM comp ORDER BY item DESC LIMIT 3, 1";
$result = $conn->query($query);
$row = mysqli_fetch_assoc($result);
and I'm able to update data like this:
$sql = "UPDATE comp SET final_amount=25 WHERE item='Y'";
but I can't put the two together (I tried several ways and failed). In other words, I am able to update a table record with data that I manually type, e.g. I type "25" manually in the update statement, which in this example is the data from 'staring_amount', but I don't know how to update with a statement that will automatically use data I fetch from the table. Again in other words, how do I write the update statement so that "SET final_amount=" is followed by fetched data? Thanks in advance for any help!
So, you just need to pass your fetched data into the query
$starting_amount = $row['starting_amount'];
$sql = "UPDATE comp SET final_amount=$starting_amount WHERE item='Y'";
Firstly, I highly recommend looking into prepared statements - using a prepared statement to insert data is an easy way to prevent SQL injection attacks and also will make what you want to do a little easier.
Here's an example of a prepared update statement using mysqli based on your example:
$statement = $conn->prepare("UPDATE comp SET final_amount=? WHERE item='Y'")
$statement->bind_param(25);
I'll assume for this answer that you want to use just the first row of the resultset.
Using your example above, you can replace the value in bind_param with a value from your row.
$statement->bind_param($row['starting_amount']);
There's no need to do them as separate statements, since you can join queries in an UPDATE.
UPDATE comp AS c1
JOIN (SELECT starting_amount
FROM comp
ORDER BY item DESC
LIMIT 3, 1) AS c2
SET c1.final_amount = c2.starting_amount
WHERE c1.item = 'Y'
My main concern is the security of inserting, updating, & deleting of record in my database table.
If I use the following code:
$sql_room = "UPDATE `lf_rooms` SET room_count`=$room_count
WHERE id = $room_id";
mysqli_query($con, $sql_room);
Is this secure or do I need to use prepare statement?
The following code runs without any errors but doesn't actually delete anything:
$update = $mysqli->prepare('DELETE FROM table WHERE RetailerID = ? AND Amount = ? AND FXRate = ?');
$update->bind_param('iii', $rID, $base_value, $fx_rate);
$update->execute();
$update->close();
I have numerous mysqli prepared statments in this same file that execute fine, but this one is the only one that doesn't modify the table. No errors or shown, but the row isn't deleted from the table either. I have verified that $rID, $base_value, and $fx_rate are the correct values, and a row is DEFINITELY present in table that matches those values.
The only difference between this statement and the others are the parameters and the fact that it's DELETE instead of SELECT or UPDATE. I also tried doing a SELECT or UPDATE instead of DELETE using the same WHERE parameters, but no luck. The issue seems to be that it's not finding a row that fits the WHERE parameters, but like I said, the row is definitely there.
Any ideas?
Is amount an integer or a double? You're converting to integer ('iii'), but I presume it'll be $0.34 or similar. Try 'idi' instead.
Edit: same applies for rate - is that an integer or double too?
I am looking at how to update a specific table depending on whether the ID already exists in that table or whether the record needs to be created.
I am planning on using a function which is passed the id number from the main table in the database. The id value.
so something like update($id). But when this function is called I am not quite clear on how to check if the value already exists in the database, if it does then update the record. If it doesn't then create the record. Any thoughts?
I understand how to update the table, but not how to use the conditional statements I require.
$query = "UPDATE reports FROM them where id='$id'";
PSEUDOCODE:
Check if $id exists in table.
If $id exists, update that row
If $id does not exists, create the record.
You need to execute a select statement beforehand to check whether a record with that id already exists. If the results from executing the query are not empty, then use an UPDATE statement. If the results are empty, call INSERT instead.
To check for existing records, use the query like the one below. Code sample provided.
SQL:
"Select * from reports where id='$id'";
PHP:
$result = mysql_query("Select * from reports where id='$id'");
if (mysql_num_rows($result) > 0) {
mysql_query("UPDATE...(your update statement query string)");
} else {
mysql_query("INSERT...(your insert statement query string)");
}
Note that this is a basic example, and you should remember to do things like sanitize your query variables to prevent SQL injection, as well as check for error conditions whenever executing a query.