Mysql on duplicate update not working? - mysql

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),...

Related

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') ");
}
^_^

SQL UPDATE Not Updating

After uploading a csv file, I am trying to insert its contents into my database table. I have this query:
$connect = mysql_connect("localhost","root","");
mysql_select_db("dbtest",$connect);
//get the file
$handle = fopen($filename,"r");
do {
if (isset($data[0])) {
$data0 = mysql_real_escape_string($data[0]); //rcode
$data1 = mysql_real_escape_string($data[1]); //pcode
$data2 = mysql_real_escape_string($data[2]); //mcode
$data3 = mysql_real_escape_string($data[3]); //bcode
$data4 = mysql_real_escape_string($data[4]); //ecode
$data5 = mysql_real_escape_string($data[5]); //filetype
$data6 = mysql_real_escape_string($data[6]); //rec_count
$data7 = mysql_real_escape_string($data[7]); //gen_count
$data8 = mysql_real_escape_string($data[8]); //qc_count
$data9 = mysql_real_escape_string($data[9]); //be_count
$data10 = mysql_real_escape_string($data[10]); //trn_count
$query = "INSERT INTO tbltest(rcode,pcode,mcode,bcode,ecode,filetype,rec_count,
gen_count,qc_count,be_count,trn_count) VALUES ('$data0','$data1','$data2',
'$data3', '$data4', '$data5', '$data6', '$data7', '$data8', '$data9', '$data10')
ON DUPLICATE KEY UPDATE rec_count=values(rec_count),gen_count=values(gen_count),
qc_count=values(qc_count), be_count=values(be_count), trn_count=values(trn_count)";
mysql_query ($query,$connect) ;
}
} while ($data = fgetcsv($handle,1000,"|"));
And it's working neatly but then as the database was re-structured, I just then need to update the database table as rcode to filetype has values already and I just need to insert values of rec_count to trn_count. So my first query INSERT INTO ... ON DUPLICATE KEY UPDATE has been change to UPDATE only. And so I did this:
$query = "UPDATE tbltest SET (rec_count='$data6', gen_count = '$data7',
qc_count = '$data8', be_count = '$data9', trn_count= '$data10') WHERE
(rcode = '$data0', pcode = '$data1', mcode = '$data2', bcode = '$data3',
ecode = '$data4', filetype = '$data5')";
My problem now is that, my UPDATE seems to be not working as it doesn't update the database table. Bu when I did this;
$query = "UPDATE tbltest SET rcode = '5'";
The database is being updated. When I tried echo $query;, the echo responds the correct data (from the csv). I just cannot figure why it doesn't insert these data into the database. Kindly help. Thanks
Your SQL syntax is incorrect. The statement should read something like
UPDATE tbltest
SET rec_count='...', gen_count = '...', ...
WHERE rcode = '...' AND pcode = '...' AND ...
See MySQL UPDATE syntax.

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.";}
}

Column 'id' in field list is ambiguous

I am getting the follwing error, Column 'id' in field list is ambiguous. how can i uniquely grab the correct ID from this statment
function data () {
if($at = mysql_real_escape_string(#$_GET['id'])){$at = mysql_real_escape_string(#$_GET['id']);
$arg = func_get_args();
unset($arg[0]);
$fields = '`'.implode('`,`', $arg).'`';
$query = mysql_query("SELECT $fields FROM `list` LEFT JOIN fruits ON location.id =
fruits.fid
LEFT JOIN store ON store.id = location.catid WHERE location.link = '$at'")or die(mysql_error());
$query_result = mysql_fetch_assoc($query);
$query_row = mysql_num_rows($query);
if($query_row==0){
return false;
}else{
foreach ($arg as $field){
$arg[$field] = $query_result[$field];
}return $arg;
}
}
}
$fields = '`list`.'.implode('`, `list`.`', $arg).'`';
But I strongly recommend Doctrine!
Seems to be a problem in your mysql query. Specifying the name of the table along with the name of your field would be the easiest solution I guess:
$fields = 'tablename'.$fields;
Turns that it is easier to just change the name of one the id in the table.

Insert on first request; update on all subsequent requests

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