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

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

Related

MySQL UPDATE, IF, INSERT INTO statement

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.

Why is this SQL statement being read incorrectly?

Why is this SQL Statement
$array = $wpdb->get_results('SELECT * FROM wp_before_after WHERE patient = '.$patientName );
Generating this error?
WordPress database error: [Unknown column 'sarah' in 'where clause']
SELECT * FROM wp_before_after WHERE patient = sarah-jordon
It's like it's swapping round 'patient' and 'sarah-jordon', and thinking sarah-jordon is a column in the database.
You are missing quotes around your value.
$array = $wpdb->get_results('SELECT * FROM wp_before_after WHERE patient = "'.$patientName . '"');
But it will be more robust if you use a parameterized query.
Edit
I checked quickly in wordpress reference, and they have a prepare method
While A.D.'s answer is correct...
$array = $wpdb->get_results('SELECT * FROM wp_before_after WHERE patient = "'.$patientName . '"');
... and makes mention that the OP example is not really robust/secure (vulnerable to SQL injections) I thought it would be worthwhile to post an example that is secure using the prepare statement:
// Usage: $wpdb->prepare( 'query' [, value_parameter, value_parameter ... ] );
// Example:
$patient_name = .$patientName;
$patient = $wpdb->get_var(
$wpdb->prepare( "SELECT * FROM wp_before_after WHERE patient = %d", $patient_name ));
Documentation can be found here
The reason for using prepare is it prevents SQL Injection Attacks on queries that take parameters. For example, in the OP example, if someone were to enter..
sarah; DROP TABLE wp_before_after
or maybe less insidiously:
sarah OR 1=1
.. into the Patient Name field, that SQL would be executed and presumably drop your wp_before_after table or return all of the records in your patient table.
The prepare method SQL escapes the values prior to executing the query -- and that prevents your variables/parameters from being potentially read as SQL. It's basically saying "hey, make sure you read these as values, not part of the query."
As a general rule of thumb, you want to use prepare in all circumstances where a query takes user input as a parameter. You do not want to use prepare in circumstances where no user input is needed -- for example, getting all patients with a first name starting with 's'.

How Insert if not exists with parameters?

When trying to perform the following instructions I get an error: SQLError: 'Error #3115: SQL Error.', details:'near 'WHERE': syntax error', operation:'execute', detailID:'2003'. Any thoughts? Thanks!
dbStatement.text = "INSERT INTO person (idPerson,image) VALUES (:idPerson,:image) " +
"WHERE NOT EXISTS (SELECT idPerson FROM person WHERE idPerson=:idPerson)";
dbStatement.parameters[":idPerson"] = person.idPerson;
dbStatement.parameters[":image"] = person.image;
dbStatement.execute();
You're probably looking for INSERT OR REPLACE person ( ... ) VALUES( ... ).

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/