Insert on first request; update on all subsequent requests - mysql

I'm inserting a row into a MySQL database table. On the first insertion I want a new row to be added, but after that I just want that row to be updated. Here's how I'm doing it. An Ajax request calls the following php file:
<?php
include "base.php";
$bookID = $_POST['bookID'];
$shelfID = $_POST['shelfID'];
$userID = $_SESSION['user_id'];
$query = mysql_query("SELECT shelfID FROM shelves WHERE userID = '$userID' AND shelfID = '$shelfID' AND bookID = '$bookID'");
if (mysql_num_rows($query) == 0) {
$insert = "INSERT INTO shelves (bookID,shelfID,userID) VALUES ('$bookID','$shelfID','$userID')";
mysql_query($insert) or die(mysql_error());
} elseif (mysql_num_rows($query) == 1) { //ie row already exists
$update = "UPDATE shelves SET shelfID = '$shelfID' WHERE userID = '$userID' AND bookID = '$bookID'";
mysql_query($update) or die(mysql_error());
}
?>
As it stands it adds a new row every time.

You should consider using PDO for data access. There is a discussion on what you need to do here: PDO Insert on Duplicate Key Update
I'd flag this as duplicate, but that question is specifically discussing PDO.

You can use the INSERT ... ON DUPLICATE KEY UPDATE syntax. As long as you have a unique index on the data set (i.e. userid + shelfid + bookid) you are inserting, it will do an update instead.
http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html

Related

Mysql on duplicate update not working?

movie_title is a unique column. I want to update columns on duplicate. There are no errors in the query.
foreach($array['data'] as $row) {
$movie_title = $row[0];
$time_published = date("Y-m-d H:i:s",strtotime($row[2]));
$language = $row[3];
$views = $row[4];
$active = $row[6];
$type = $row[7];
$checked = $row[8];
$category = $row[9];
$rating = $row[10];
$subtitle = $row[12];
$visitor_views = $row[18];
if($visitor_views!=0) {
$view_array[] = $visitor_views;
}
$movie_title = explode("-",$movie_title);
$movie_title = trim($movie_title[0]);
$wpdb->query($wpdb->prepare("INSERT INTO movies (movie_title,time_published,language,views,visitor_views,active,type,checked,category,rating,subtitle) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) ON DUPLICATE KEY UPDATE active=active,category=category,views=views,visitor_views=visitor_views,checked=checked,subtitle=subtitle,rating=rating,type=type,language=language",
$movie_title,$time_published,$language,$views,$visitor_views,$active,$type,$checked,$category,$rating,$subtitle));
}
This is how the query looks
INSERT INTO movies (movie_title,time_published,language,views,visitor_views,active,
type,checked,category,rating,subtitle)
VALUES
('Bodyguard','2016-12-17 06:54:26','1','2091','15',
'1','0','0','Feature Film ','3.66','Bodyguard.vtt')
ON DUPLICATE KEY UPDATE
active=active,category=category,views=views,visitor_views=visitor_views,
checked=checked,subtitle=subtitle,rating=rating,type=type,language=language
Why aren't any of the columns being updated?
Not sure if this solves the issues but perhaps it should be something like this:
ON DUPLICATE KEY UPDATE active = VALUES(active), category = VALUES(category)..
You need to use col_name = VALUES(col_name), otherwise you are just saying "set x = x".
...
ON DUPLICATE KEY UPDATE
active=VALUES(active),category=VALUES(category),views=VALUES(views),...

How to update array of records if not exist insert, without id?

i tried to do like this:
INSERT INTO hlr_client_country
(perform_hlr, client_id, mcc, dial_code)
VALUES
(1,2,202,30),(1,2,204,31)
ON DUPLICATE KEY UPDATE
id = 'id',
client_id = 'client_id',
mcc = 'mcc'
but query always inserts new and new records.
I want to update first and if record not exists insert one
Help please
try this code
$result = mysql_query("SELECT * FROM table WHERE title_1 ='$title_1' ");
if( mysql_num_rows($result) > 0) {
mysql_query("UPDATE table SET column = '$value' WHERE title_1 = '$title_1' ");
}
else
{
mysql_query("INSERT INTO table (title_1) VALUES ('$title_1') ");
}
^_^

How to decrement the sequence on an column with auto increment as a constraint, when records are deleted

create table quiz(E_Id INT NOT NULL AUTO_INCREMENT PRIMAR KEY, E_name VARCHAR(255), E_Salary INT)
now whenever i insert data intop table, auto increment works as expected.
Now when i delete the record the sequence of number doesnot get decrement.
Suppose I have a records with Id 1, 2, 3, 4, 5. When i delete the 2 and 3 rd records, the sequence continues from the number 6. I want that if a records is deleted it numbering should get decrement automatically
There is no way for auto-decrementing. But you can use other simple methods.
DROP the field you are auto_incrementing.
ALTER the table to ADD the field again with the same attributes.
Then the list of auto-incrementing will reset.
NOTE: Take care when you are DROPing the table. It may drop your entire data.
Update all ids that are above the one been deleted by decrementing by 1 (-1) (if there are 3 id's in auto_increment column and you delete id 2, id 3 will be set to be id = 2) and then "alter table set auto_increment = 1 to update auto_increment counter.
code(including deletion of image file from website folder:
$allGood = false;
if(isset($_GET['id']) != ""){
$item = $_GET['id'];
$query = "SELECT * FROM products WHERE id = ?";
if($getImgPath = $sqlConnection->prepare($query)){
$getImgPath->bind_param("i",$item);
$getImgPath->execute();
$result = $getImgPath->get_result();
$row = $result->fetch_array();
$deletedItemId = $row['id'];
if(isset($row['image']) != ""){
$imgPath = "../../../../".$row['image'];
if(unlink($imgPath)){
$query = "DELETE FROM products WHERE id = ?";
if($delete = $sqlConnection->prepare($query)){
$delete->bind_param("i",$item);
if($delete->execute()){
$query = "SELECT * FROM products";
if($getIds = $sqlConnection->query($query)){
while($row = $getIds->fetch_array()){
if($row['id']>$deletedItemId){
$newId = $row['id']-1;
$query = "UPDATE products SET id=? WHERE id=?";
if($updateIds = $sqlConnection->prepare($query)){
$updateIds->bind_param("ii",$newId,$row['id']);
if($updateIds->execute()){
$allGood = true;
}
}
} else {$allGood = true;}
}
}
}
}
}
}
}
}
if($allGood == true){
$query = "ALTER TABLE products AUTO_INCREMENT = 1";
if($sqlConnection->query($query)){
echo "success!";
}else{echo "error.";}
}

Insert new column, increment all rows

Is this possible using only mysql:
Insert a new column and example - "pos".
Every row in the table has to have unique,incresing value of "pos" like - 1,2,3,4,5.
In php this would be an easy job:
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
$counter = 0;
while($row = mysql_fetch_array($result)){
mysql_query( "UPDATE example SET pos = ".++$counter." WHERE id = ".$row['id']." );
}
As already suggested, the most efficient solution is to use auto incremental on pos.
Alternatively if your use case do not permit you, then try similar:
"UPDATE example SET pos = ((select max(pos) from example) +1) WHERE id
= ".$row['id']."
yes you can do it like that
UPDATE example SET pos = pos+1 WHERE id = ".$row['id']."
Give your pos mysql field the auto_increment attribute - this will index it, make it unique, and increment by 1 on each insert

Resource Id #22 inserted into database field

I'm having a problem with running this function. When it runs, it does exactly what I want, except that within my like_requests table the request_id is not the mysql query result linked to the variable $select but Resource Id #22. I thought that resource id's appear when you are trying to echo out a result, but I'm not using echo. What's wrong with the code?
function update_likes($band_requested, $new_likes, $session_user_id) {
$select = mysql_query("SELECT `primary_id` FROM `requests` WHERE
`user_requester_id` = '$session_user_id' AND `person_requested` =
'$band_requested'");
$sql_2 = "INSERT INTO `like_requests` (user_id, request_id) VALUES
('$session_user_id', '$select')";
mysql_query($sql_2);
}
$band_requested = 'rally done';
$new_likes = 239;
$the_session_user_id = 3;
update_likes($band_requested, $new_likes, $the_session_user_id);
UPDATE WITH CORRECTED ANSWER
Here is the code corrected with help from David.
function update_likes($band_requested, $new_likes, $session_user_id)
{
$select = mysql_query("SELECT `primary_id` FROM `requests` WHERE `user_requester_id` =
'$session_user_id' AND `person_requested` = '$band_requested'");
$row = mysql_fetch_row($select);
$request_id = $row[0];
$sql_2 = "INSERT INTO `like_requests` (user_id, request_id) VALUES ('$session_user_id',
'$request_id')";
mysql_query($sql_2);
}
mysql_query returns a resource (http://php.net/manual/en/function.mysql-query.php) not just a scalar value. You'd need to use a function like mysql_fetch_row() to get the, presumably, one row you want, assign that row to a variable $row, then retrieve the primary_id with array syntax like $row['primary_id']. By the way, apparently mysql_query is being eased out and we should use the MySQLi API with the mysqli_query() method.