Update Select Query - php

$query = "INSERT INTO article (article_title, article_credits, article_excerpt,
article_body, article_img_list, article_img_main,
article_published, article_date, article_modified, article_author) ".
"SELECT '".$db->escape($post['title'])."', '".json_encode($credits)."','".$db->escape($post['excerpt']).
"','".$db->escape($post['article'])."','".$db->escape($articleImageListName)."
','".$db->escape($articleImageMainName)."
','".$published."',
'".date("Y-m-d H:i:s", strtotime($post['date']))."',
'".date('Y-m-d H:i:s')."', email ".
"FROM users WHERE id = ".$id"";
The above query inserts data into my database and selects email from users.
How can I convert this to an UPDATE query?

Add ON DUPLICATE UPDATE and take care that there is something that is unique and can't be changed like an article_ID that exists in the old and in the new article
BTW: I would recommend using prepared statements

Use REPLACE INTO instead of INSERT INTO.
For UPDATE ... ON DUPLICATE you have write a lot of overhead assignments in the end.

Related

insert records from one table to another

Hi I am trying to add records from one table to another, once i have added a 'user' record, the table that is being selected contains rows of available security options, and the table that is being inserted to is the child table for the user, detailing security options.
I cam across this code in an earlier post, which i am sure works nicely, however i am trying to modify it so that the values from statement, includes two parts, one from the select query and one which is the key from the master record.#
This is the original code I found from this site:
INSERT INTO def (catid, title, page, publish)
SELECT catid, title, 'page','yes' from `abc`
And this is what I am trying to do with it:
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) values ('".$keys["UserPk"]."', SELECT ModulePk from Global_Modules)";
CustomQuery($sql);
And this is the error I am getting:
INSERT INTO Link_UserSecurity (UserFk, ModuleFk) values ('4', SELECT
ModulePk from Global_Modules)
See screenshot for further detail
Obviously I am not concating the from statement properly, but would appreciate any help?
You can insert the $keys["UserPk"] variable as if it were a constant in the SQL:
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) SELECT '{$keys["UserPk"]}', ModulePk from Global_Modules";
Do note that $keys["UserPk"] must be escaped before adding it into the query. In PDO, it would look like this:
$keys["UserPk"] = $pdo->quote($keys["UserPk"]);
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) SELECT '{$keys["UserPk"]}', ModulePk from Global_Modules";
Could be a problem related to the double quotes sequence
"INSERT INTO Link_UserSecurity (UserFk, ModuleFk)
values ('". $keys['UserPk']. "', SELECT ModulePk from Global_Modules)";
but you could use also a select insert
"INSERT INTO Link_UserSecurity (UserFk, ModuleFk)
SELECT '" . $keys['UserPk']. "' , ModulePk from Global_Modules)";
Adding only new and unique records from one table to another. Limiting is a good idea to prevent it from timeout. It can be run several times until all the records copied.
First, select the latest record ID from the table to be copied:
SET #lastcopied =
(SELECT
IF(MAX(a.exp_inotech_id)>0, MAX(a.exp_inotech_id), 0) AS lastcopied
FROM
kll_export_to a
WHERE exp_tezgah = 'A2015-0056');
Then, select and add the records to the destination table:
INSERT INTO kll_export_to
(SELECT * FROM
kll_export_from f
GROUP BY f.exp_inotech_id
HAVING COUNT(f.exp_inotech_id) = 1 AND exp_tezgah = 'A2015-0056' AND f.exp_inotech_id > #lastcopied
ORDER BY exp_inotech_id
LIMIT 1000);

insert a record or if exist then update in mysql doesnt work

i want that if a record doesnt exist i add it otherwise update it... but it doesnt work, whats the wrong with this code:
<?php
$user_id=$_POST['user_id'];
$user_email="user_email";
$last_stage=$_POST['last_stage'];
$score=$_POST['score'];
$note=$_POST['note'];
$con=mysqli_connect("localhost","ferfer","Drfrj","ferfw");
$result = mysqli_query($con,"SELECT user_email FROM rating WHERE user_email='".$user_email."'");
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
//echo "exist";
mysqli_query($con,"UPDATE rating SET user_id=".$user_id.", user_email='".$user_email."', last_stage=".$last_stage.", score=".$score.", note='".$note."' WHERE user_email='".$user_email."'";
mysqli_close($con);
}else{
//echo "does not exist";
mysqli_query($con,"INSERT INTO rating(user_id, user_email, last_stage, score, note)VALUES (".$user_id.",'".$user_email."',".$last_stage.",".$score.",'".$note."') ");
mysqli_close($con);
}
?>
You can actually do it in a single query since MySQL has implemented INSERT ... ON DUPLICATE KEY UPDATE which basically INSERTs a record if it does not exists otherwise UPDATEs it.
The first thing you need to do is to add a UNIQUE column on the table. In your example I see that user_email is the column you are searching for existence. If this is not unique, you need to alter the table for UNIQUE constraint
ALTER TABLE rating ADD CONSTRAINT tb_uq UNIQUE(user_email)
after it has been implement, build a query like this,
INSERT INTO rating(user_id, user_email, last_stage, score, note)
VALUES($user_id, '$user_email', last_stage, score, '$note')
ON DUPLICATE KEY UPDATE
user_id = $user_id,
last_stage = $last_stage,
score = $score,
note= '$note'
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
$user_email="user_email";
should be changed to
$user_email=$_POST['user_email'];
And missing ( simbol, as #Yogesh Suthar said. You should also consider escaping characters in strings, using i.e. mysql_real_escape_string function.
you forgot ) here
mysqli_query($con,"UPDATE rating SET user_id=".$user_id.", user_email='".$user_email."', last_stage=".$last_stage.", score=".$score.", note='".$note."'
WHERE user_email='".$user_email."'");
^ // here
Better way is to use
REPLACE INTO `rating` (user_id,user_email,last_stage,score,note)
VALUES(#user_id,#user_email,#last_stage,#score,#note) WHERE user_email=#email
use also binding and prepared statements to make it more secure. Your code is very insecure because you have nor escape functions neither casting.
Example of using binding with PHP. $dbh is PDO object.
$stmt = $dbh->prepare("REPLACE INTO `rating` (user_id,user_email,last_stage,score,note)
VALUES(#user_id,#user_email,#last_stage,#score,#note) WHERE user_email=#email");
$stmt->bindParam('#name', (int)$user_id);
$stmt->bindParam('#user_email', $user_email);
$stmt->bindParam('#last_stage', $last_stage);
$stmt->bindParam('#score', $score);
$stmt->bindParam('#note', $note);
more on http://pl1.php.net/pdo
with binding you don't have to escape strings because it goes straight into the database layer without it having to be crudely spliced into the SQL statement.
The MySQL REPLACE statement works like the INSERT statement with the additional rules:
If the record which you want to insert does not exist, the MySQL REPLACE inserts a new record.
If the record which you want to insert already exists, MySQL REPLACE deletes the old record first and then insert a new record.
$user_email="user_email"; should be $user_email=$_POST["user_email"];

Select from table, and insert data to another - Multiply data -SQL

I have a button that will delete all users that fits into this query:
DELETE FROM users WHERE lastlogin < ".time()." - ".$sdata['activitylimit']."*3600
Although, I have to take some parts of each users data, and put it into another table ("username" and "email")
How can I take the users username AND email from the table users, and insert it into my table "reserved_data"?
The table reserved_data looks like this:
id (just the id)
data (the email or username value)
type (what type of data is it((username/email)))
You can't do that directly, thanks to the table layout of the reserved_data table. Why do you do that? Why haven't you got a deleted_users table, containing their username and email? That way you could do this:
$q1 = "INSERT INTO deleted_users (username, email) SELECT username, email FROM users WHERE lastlogin < (".time()." - ".$sdata['activitylimit']." * 3600)";
$q2 = "DELETE FROM users WHERE lastlogin < (".time()." - ".$sdata['activitylimit']." * 3600)";
If you won't change the table, use something like this:
$toDelete = mysql_query("SELECT username, email FROM users WHERE lastlogin < (".time()." - ".$sdata['activitylimit']." * 3600)");
while($user = mysql_fetch_assoc($toDelete))
{
mysql_query("INSERT INTO reserved_data (`data`, `type`) VALUES ('" . $user['username'] . ", 'username'");
mysql_query("INSERT INTO reserved_data (`data`, `type`) VALUES ('" . $user['email'] . ", 'email'");
}
// Now perform the delete
mysql_query("DELETE FROM users WHERE lastlogin < (".time()." - ".$sdata['activitylimit']." * 3600)");
You see the latter requires more code and is generally a bad idea. You lose the relation between a username and its email address.
Besides, you might want to use transactions, since it's possible for one to not be included in the first query but be included in the second query. You then lose this user's data.
And perhaps you can fix all your problems by simply adding an (in)active column to your users table. One rarely wants to really delete data.
Also you can use on delete trigger to log data to reserved_data table. Just move your reserved_data insert to trigger
I would not recommend approach with deletion mark. You don't need it there is no requirement to restore deleted users and it brings quite much new problems.

How to check to see if a key exists before trying to insert it into a database?

I'm pulling data from a calendar feed and each event in the calendar has a unique $EventID string. I'm using PHP.
I have a SQL database with an Event_ID column. These IDs are strings. I need to be able to compare my $EventID against the Event_ID column and put in in the database if it's not there.
I have a primary key set up to auto increment in the database, and I was thinking I can set up a loop to increment through those and compare each to the $EventID, but I'm wondering if there is a better way-maybe a PHP function I don't know about?
I've got a whole lot of code, but basically I've got:
<?php
$EventID = $event->id; //This is the event ID
mysql_query("INSERT INTO myTable
(Event_ID, Date_added, Date_edited)
VALUES
('$EventID', '$dateAdded', '$lastEdited')");
?>
So how do I set up a conditional to check all the Event_IDs that are already in the database against the $EventID?
$query = "SELECT * FROM `myTable` WHERE `Event_ID`='$EventID' ";
$result = mysql_query($query);
if (!mysql_num_rows($result))
// INSERT QUERY
Check if the Event ID is present, If not insert it
You could just skip the "Select" query and do an "INSERT IGNORE" instead:
mysql_query("INSERT IGNORE INTO myTable
(Event_ID, Date_added, Date_edited)
VALUES
('$EventID', '$dateAdded', '$lastEdited')");
this will leave existing Event_id's, and just add new records if required.

insert sql statement into mysql database like common string?

I wrote a logger function and it inserts "insert and update queries" to database. altough I apply "mysql_real_escape_string" to the sql stament, I cannot insert it to the database.
any suggestion please?
INSERT INTO kayit (ip, user_id, query) VALUES ('127.0.0.1', 1 UPDATE faal_ekonkod SET bedel = 12000 WHERE id = 1)
In SQL, strings must be quoted. You are also missing a comma. Try this:
INSERT INTO kayit (ip, user_id, query) VALUES ('127.0.0.1', 1, 'UPDATE faal_ekonkod SET bedel = 12000 WHERE id = 1')
i have also problems with this function, then i use the addslashes() function, its not an answer but a solution.
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));

Categories