MySQL UPDATE, IF, INSERT INTO statement - mysql

I am trying to follow the following blog and use an UPDATE, IF, INSERT INTO statement seeing that it will no go over my data twice.
Please note it is for php.
The statement that I have is as follows
$query = "UPDATE
" . $this->table_name2 . "
SET
batch = :batch,
created = :created
WHERE
id = :id
IF row_count() = 0
INSERT INTO " . $this->table_name2 . "
SET
id=:id,
batch=:batch,
created=:created";
But my return value always comes back as false, and I do not know where the problem is.
If I try the first half of the statement it updates the information:
$query = "UPDATE
" . $this->table_name2 . "
SET
batch = :batch,
created = :created
WHERE
id = :id
And if I try the second half of the statement it INSERTS the information:
INSERT INTO " . $this->table_name2 . "
SET
id=:id,
batch=:batch,
created=:created";
I do not find any help after allot of searching so far, and I feel that somehow my IF statement may not be correct, but I do not even get info on the IF row_count() = 0 in the docs.

The IF statement is available in stored procedures only.
If id is the primary key (or unique) this should work for you:
INSERT INTO " . $this->table_name2 . "
SET
id = :id,
batch = :batch,
created = :created
ON DUPLICATE KEY UPDATE
batch = :batch,
created = :created
This will execute the INSERT statement only, of the ID does not exits yet. If it already exists, it will execute the UPDATE part.

Related

MySQL update changes affect rest of the data

I have a mysql update here and when the user make changes to one selection category it would duplicate that selection to the rest of the other selection too. Below is a sample scenario where only the 1st CD category was change and it's reflecting the same for the rest. How do I get "nmc_category.catDesc ='$pCDCategory" to only update that entry only ?
Sample:
$sql = "UPDATE nmc_cd "
. "JOIN nmc_category ON (nmc_cd.catID = nmc_category.catID) "
. "JOIN nmc_publisher ON (nmc_cd.pubID = nmc_publisher.pubID) "
. "SET nmc_cd.CDTitle='$pCDTitle',nmc_cd.CDYear='$pCDYear',nmc_cd.CDPrice='$pCDPrice',nmc_category.catDesc ='$pCDCategory', nmc_publisher.pubName = '$pCDPubName' , nmc_cd.pubID ='$pCDPubID', nmc_publisher.pubID='$pCDPubID' "
. "WHERE nmc_cd.CDID='$pCDID'";
nmc_cd table:
nmc_category table:
use this command
SET SQL_SAFE_UPDATES=0;

Use where clause in insert on duplicate key update

As I know I can't use a where clause inside a Insert statement but in here what I want to do is I want to insert a new row if same kind of row not exist else I need to update that row. so I need to use where clause to do that. this is my query but it is not working because of where clause. can someone help me on this.
Thank You.
"INSERT INTO "
. "`leaves_count` "
. "(`leave_cat_id`, `leave_days_count`, `emp_number`) "
. "VALUES ('$req_lv_cat', $req_lv_day_count, '$empNmbr') "
. "ON DUPLICATE KEY UPDATE "
. "leave_days_count = leave_days_count + ($req_lv_day_count) "
. "WHERE "
. "(leave_cat_id = '$req_lv_cat' AND emp_number = '$empNmbr')"
Please use merge statement. It will do "If exist UPDATE else INSERT".
MERGE <hint> INTO <table_name>
USING <table_view_or_query>
ON (<condition>)
WHEN MATCHED THEN <update_clause>
WHEN NOT MATCHED THEN <insert_clause>;
Here i am posting example i hope it will help to you
INSERT INTO table (id,a,b,c,d,e,f,g)
VALUES (1,2,3,4,5,6,7,8)
ON DUPLICATE KEY
UPDATE a=a, b=b, c=c, d=d, e=e, f=f, g=g;

Checking if value is not in the table ..help..please (Mysql + C)

My purpose is to warn the user whenever he/she insert a value which is not in the table.
Table :
For_Sconti | Cat_Sconti | Sconto
7148 A1 451.00
Someone cleverly suggested to use mysql_affected_rows() function.
Since it can be used when an update statement is issued, I tried to understand how it works but to no avail.
Here's the code I use:
memset(query, 0, 200);
strcat(query, "UPDATE Sconti SET ");
strcat(query, "Sconto = '");
strcat(query, nuovo_sconto);
strcat(query, "' WHERE For_Sconti ='");
strcat(query, For_Sconti);
strcat(query, "' AND Cat_Sconti='");
strcat(query, Cat_Sconti);
strcat(query, "';");
if ( (mysql_affected_rows()) == 0 )
printf("Warning you tried to modify non existent record\n" );
This is the error message I get:
2.0.c: In function ‘modifica_sconto’:
2.0.c:330: error: too few arguments to function ‘mysql_affected_rows’
Can someone help get out of trouble?
Any help will be highly appreciated.
You have generated the update statement, but you are not executing it. You need to execute your update statement using mysql_query()
You need to pass your mysql connection handle structure (MYSQL *) as a parameter to mysql_affected_rows()
char *stmt = "UPDATE products SET cost=cost*1.25
WHERE group=10";
mysql_query(&mysql,stmt);
printf("%ld products updated", (long) mysql_affected_rows(&mysql));
References :
http://dev.mysql.com/doc/refman/5.0/en/mysql-affected-rows.html

MySql adding column name with last_insert_id()

I'm trying to add a new mysql column in a table, using an insert_id from an insert of another table. This is the sentence that i use...
string sqlInsert = "INSERT INTO test (IdPico, Nombre, TextoBienvenida, FechaCreacion) VALUES (1, 'nombretest', 'aslkñdfa lsñdk asjd asldkf añlsj f', '2011-07-13 10:22:53'); ";
sqlInsert += "SET #IDTESTCREATED := CONCAT('Test', LAST_INSERT_ID(); ";
sqlInsert += "ALTER TABLE Usuarios ADD COLUMN #IDTESTCREATED BIT DEFAULT 0; ";
I using ASP.NET 4.0 and MySql connection, and server responds with 'Fatal error encountered during command execution. '
Could anybody help me?
Well ... I answer myself.
After making a deep search, I have not found how to add a column dynamically by a variable in mysql.
At end I had to make two querys, first to insert the test and get the id, and second to update the users table.
Since the insertion and retrieval of id are in the same query, no problems of persistent connections and concurrent updates.
string sqlInsert = "INSERT INTO Test (<fields>) VALUES (<values>);";
sqlInsert += "SELECT LAST_INSERT_ID() AS IdTestInserted; ";
string idnewtest = <result of insert query>;
string sqlAlter = "ALTER TABLE Users ADD COLUMN Test" + idnewtest + " BIT DEFAULT 0; ";
I regret not having found the answer, but at least I achieved my goal.
Thank you all for your help!

generating MD5 idHash directly in MySQL statement

In my table I have an userID that is auto-incremented. In the same row I have an idHash. Is it possible to generate the idHash (simply an MD5 sum) from it directly with the same INSERT statement so that I don't have to SELECT the id, and then UPDATE the idHash again?
Problem is: I do not know the userID before it is being generated (auto-incremented) by MySQL.
Thanks
Frank
PS: I'm using PHP.
PPS: This question is all about a SINGLE INSERT. I know that I can use PHP or other languages to manually select the data and then update it.
I don't believe you can do it within a single INSERT statement.
What you probably could do is use an INSERT trigger, that both determines the new ID, hashes it, and then updates the record.
One solution I can recommend is using the last insert ID instead of re-querying the table. Here is a simplified example:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "INSERT INTO users VALUES (....)";
$mysqli->query($query);
$newUserID = $mysqli->insert_id;
$query = "UPDATE users SET idHash = MD5(userID) WHERE userID = $newUserID";
$mysqli->query($query);
/* close connection */
$mysqli->close();
?>
AFAIK there's no "secure" way for doing this in the same query if you're using auto_increment.
However, if rows are never deleted in your table, you can use this little trick :
insert into mytable (col1, col2, col3, idhash)
values ('', '', '', md5(select max(id) from mytable))
I don't understand why you need to hash the id though, why not use the id directly ?
This seems to work for me:
CREATE TABLE tbl (id INT PRIMARY KEY AUTO_INCREMENT, idHash TEXT);
INSERT INTO tbl (idHash) VALUES (MD5(LAST_INSERT_ID() + 1));
SELECT *, MD5(id) FROM tbl;
Note this will only work on single-row inserts as LAST_INSERT_ID returns the insert ID of the first row inserted.
Performing MD5(column_name) on an auto_increment value does not work as the value has not been generated yet, so it is essentially calling MD5(0).
PHP snippet
<?
$tablename = "tablename";
$next_increment = 0;
$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = mysql_query($qShowStatus) or die ( "Query failed: " . mysql_error() . "<br/>" . $qShowStatus );
$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];
echo "next increment number: [$next_increment]";
?>
This will get you the next auto-increment and then you can use this in your insert.
Note: This is not perfect (Your method is imperfect as you will effectively have 2 primary keys)
From: http://blog.jamiedoris.com/geek/560/