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.
Related
I have two queries. One selects the rows, and other one sets the row values;
mysql_query("SELECT * from messages where user='12'");
mysql_query("UPDATE messages set read='yes' where user='12'");
Is it possible to make it work using one query using if statement ? if read row is not equals to yes, update ?
$result = mysql_query("SELECT * from messages where user='12'");
If (!result)
{
//Do something
}
else
{
mysql_query("UPDATE messages set read='yes' where user='12'");
}
Also see, how to check if mysql query return no result(record not found) using php?
EDIT: Your question is unclear as to what you are asking, but it seems to say how can you do what you want with an if statement, not do both in one query, which, if that is the case, I do not know what that question means.
EDIT: After thinking, try this,
IF EXISTS (SELECT * from messages where user='12')
THEN
UPDATE messages set read='yes' where user='12'
ELSE
SELECT * from messages where user='12'
(or do an insert)
Cue taken from,
SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error
There might be a way to do this with stored procedures, but in general, no, retrieval and updating are distinct operations in SQL.
If what you are concerned about is making sure that only the messages you read are updated (in the case that new messages are added to the system between the select and update calls), then you will need to specify the specific message ids to update in the where clause of your update statement.
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.
I am trying to update a record in my database and SQL query return successful but my database is not changing.
representative_id = '$login_session'
Is the representative_id column in your table a VARCHAR, or an INT? You're passing a string to MySQL, there. If the column in your DB is stored as an INT, try removing the single quotes around $login_session.
When posting questions relating to database queries, it helps to also include your table schema.
Seems like you're using PDO (hopefully)
When you're using this Data Objects, when a query is executed it will return TRUE, but it doesn't care if it changed something or not, it will return true when there is not a critical MYSQL Error.
What you want to do is to know IF A ROW AS AFFECTED / CHANGED by that query, in that case instead of using;
$PDOObject->query($thequery) == true
you should use:
$result = $PDOObject->query($thequery);
if($result->rowCount() > 0) ...
More info about how to know if a row was affected by a query with PDO
http://php.net/manual/en/pdostatement.rowcount.php
sql query return successful but my database is not changing
Are you sure that there exists at least one record that matches your filter criteria WHERE full_name = '$full_name' AND representative_id = '$login_session'. If no record updating means no any record matching the WHERE condition and so no updates occurring.
I am trying to display the data from 'table' if a key inputted by the user is found in the database. Currently I have it set up so that the database checks if the key exists, like so:
//Select all from table if a key entry that matches the user specified key exists
$sql = 'SELECT * FROM `table` WHERE EXISTS(SELECT * FROM `keys` WHERE `key` = :key)';
//Prepare the SQL query
$query = $db->prepare($sql);
//Substitute the :key placeholder for the $key variable specified by the user
$query->execute(array(':key' => $key));
//While fetched data from the query exists. While $r is true
while($r = $query->fetch(PDO::FETCH_ASSOC)) {
//Debug: Display the data
echo $r['data'] . '<br>';
}
These aren't the only SQL statements in the program that are required. Later, an INSERT query along with possibly another SELECT query need to be made.
Now, to my understanding, using WHERE EXISTS isn't always efficient. However, would it be more efficient to split the query into two separate statements and just have PHP check if any rows are returned when looking for a matching key?
I took a look at a similar question, however it compares multiple statements on a much larger scale, as opposed to a single statement vs a single condition.
#MarkBaker Join doesn't have to be faster than exists statement. Query optymalizer is able to rewrite the query live if it sees better way to accomplish query. Exists statement is more readable than join.
Fetching all the data and making filtering directly in PHP is always bad idea. What if your table grow up to milions of records? MySQL is going to find the best execute plan for you. It will automaticaly cache the query if it is going to improve performance.
In other words, your made everything correctly as far as we can see your code now. For futher analyse show us all of your queries.
I have values which use the GET method to send URL variables to a PHP page using Ajax.
On the page, I have:
$value=$_GET["q"];
$id=$_GET["id"];
$mod=$_GET["mod"];
I started out using the UPDATE SET method to modify values in a mySQL database.
I used: $num_rows= mysql_num_rows($result);
With an If Else statement to either Insert the values (if not there) or Update the column "Attribute"
But this was very inconsistant and often would not UPDATE, and there developed several duplicate values (even though if($num_rows > 0){ (WHERE Object_ID = '".$mod."' AND Type='".$id."') it SHOULD NOT have inserted, but it did.)
So I switched to this:
$sql="SELECT * FROM Attributes WHERE Object_ID = '".$mod."' AND Type='".$id."'";
$result = mysql_query($sql);
mysql_query("DELETE FROM Attributes WHERE Object_ID = '".$mod."' AND Type = '".$id."'");
mysql_query("INSERT INTO Attributes (Object_ID, Type, Attribute)
VALUES ('".$mod."', '".$id."', '".$value."')");
I know, really bad idea. But Even this method doesn't always insert the values correctly.
I know that the variables are getting to the page, because the response would be written in a div using innerHTML, and it always showed up correctly.
How can I ensure that the values are ALWAYS updated/inserted in the database?
Why not run a SELECT COUNT(*) for the condition and check what that returns and based on that run your UPDATE or INSERT?
i am really confused what is wrong with your database operation but the only way to ensure is to send back response from your php script to ajax.
It can be json or simple text informing you that which action was requested and what is performed. Depending on the response you can adjust what you want.
You have to query the table to find out if the id already exists there or not if it exits then write an Update Query i.e.
$update = "update tbl_name set column=value where id = $_GET['id']"
and if the id does not exist then use the insert
$insert = "Insert into ......"
hope this solves your issue. And Further more you have to echo out the response here in either a string format or a some other value which you will get in the success method of $.Ajax.
No need to query the database to see if the data exists already. As long as you have good data, you can delete the row every time. If the row doesn't exist, the DELETE does nothing.
Run these two queries every time, and you will be fine.
mysql_query("DELETE FROM Attributes WHERE Object_ID = '$mod' AND Type='$id'");
mysql_query("INSERT INTO Attributes (Object_ID, Type, Attribute) VALUES ('$mod', '$id', '$value'");
And please at a minimum, before you do anything with $_GET, run those through mysql_real_escape_string first. You should probably be doing more checking just to make sure that the values passed in are valid.
$value=mysql_real_escape_string($_GET["q"]);
$id=mysql_real_escape_string($_GET["id"]);
$mod=mysql_real_escape_string($_GET["mod"]);