SQL Error in INSERT and UPDATE - mysql

I have fought with this the last two hours and my head hurts..
I get this error:
You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near '' at line 7
This is my table http://i.imgur.com/5KzxxbR.png
This is my query:
if(!is_int($_POST['x']) || !is_int($_POST['x'])) break;
$q = mysql_query("
INSERT INTO `bit-board`
(value, type, x, y)
VALUES(
'".$_POST['post-it']."',
'post-it',
'".$_POST['x']."',
'".$_POST['y']."'
)"
);
echo mysql_error() ? mysql_error:mysql_insert_id();
And the second one:
if(!is_int(intval($_POST['x'])) || !is_int(intval($_POST['x'])) || !is_int(intval($_POST['id']))) break;
$q = mysql_query("
UPDATE `bit-board`
SET
value = '".$_POST['post-it']."',
type = 'post-it',
x = '".$_POST['x']."',
y = '".$_POST['y']."'
WHERE id = '".$_POST[id]."'
");
Thanks

X and Y are floats, so don't put quotes around a numeric value.
Also check the comment from #a_horse_with_no_name about quoting the table name.
$q = mysql_query("
INSERT INTO `bit-board`
(value, type, x, y)
VALUES(
'".$_POST['post-it']."',
'post-it',
".$_POST['x'].",
".$_POST['y']."
)"
);
(Not tested)

Related

use sql SELECT nodejs

I tried to use the select sql option in node js sql plugins.
But I get a error with this syntax :
con.query( 'SELECT token FROM utilisateursinvitation WHERE nomwork = ? AND
Rejoint = ? EXCEPT SELECT token FROM utilisateursinvitation WHERE nomwork
= ? AND Rejoint = ? AND nomdugroupe = ? ',
[nomwork,tatazueyzyu,"nomdugroupe"], function (error, results, fields) {
and the error :
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'EXCEPT SELECT token FROM utilisateursinvitation WHERE nomwork = 'nomdugroupe' ' at line 1
Because I don't know the correct syntax.
Can you help me ? THanks!
EXCEPT is not MySQL syntax.
Instead, you can use NOT IN or NOT EXISTS:
SELECT ui.token
FROM ui.utilisateursinvitation ui
WHERE ui.nomwork = ? AND ui.Rejoint = ? AND
NOT EXISTS (SELECT
FROM utilisateursinvitation ui2
WHERE ui2.token = ui.token AND
ui2.nomwork = ? AND ui2.Rejoint = ? AND
nomdugroupe = ?
);
Or, if you are trying to fine tokens that have nomwork and Rejoint as the input values, but not a particular nomdugroupe:
SELECT ui.token
FROM ui.utilisateursinvitation ui
WHERE ui.nomwork = ? AND ui.Rejoint = ?
GROUP BY ui.token
HAVING SUM(nomdugroupe = ?) > 0;

Dynamic regular expressions in MySQL based on the contents of a table

Is it possible to do this in MySQL?
select * from keyword
where keyword NOT REGEX concat('\b', concat_ws('\b|\b', (select distinct(keyword) from negative_keyword)), '\b')
limit 3;
It currently gives this error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'REGEX concat_ws('|', (select distinct(keyword) from negative_keyword)) limit 3' at line 1
The concat_ws by itself gives this error:
ERROR 1242 (21000): Subquery returns more than 1 row
I have to match whole words, not just substrings or exact matches. For example, negative keyword 'cat' should match 'black cat', but not 'catatonic'.
SELECT *
FROM x
WHERE NOT EXISTS
( SELECT *
FROM negative_keywords nk
WHERE nk.keyword = x.keyword
);
In the mean time, I had to filter them in code (PHP).
# filter negative keywords
$negatives = NegativeKeyword::find()->select('keyword')->distinct('keyword')->column();
$negatives = array_map(function($v) { return '/\b'.preg_quote($v).'\b/';}, $negatives); # escape regular expression, search whole words only
$kw = array_filter($kw, function($v) use ($negatives) {
foreach ($negatives as $n) {
if (preg_match($n, $v['keyword'])) { // strpos($v['keyword'], $n) !== false)
// echo "filtering $v[keyword]\n";
return false; // match found, filter word, break early
}
}
return true; // good to keep
});

insert date into a MySQL Database

I'm writing a script to insert data about books into a database.
This is the code that inserts the data
$errors=array();
foreach(array('title','author','publisher','pub_date','isbn','Format','genre','category','bookcase','shelf','user_id') as $key=>$val){
$_REQUEST[$key] = mysqli_real_escape_string($ptah,trim($_REQUEST[$val])) ;
};
$title = $_REQUEST['title'] ; $title = strip_tags($title);
$author = $_REQUEST['author'] ; $author = strip_tags($author);
$publisher = $_REQUEST['publisher'] ; $publisher = strip_tags($publisher);
$pub_date = $_REQUEST['pub_date'] ; $pub_date = strip_tags($pub_date);
$isbn = $_REQUEST['isbn'] ; $isbn = strip_tags($isbn);
$format = $_REQUEST['Format'] ; $format = strip_tags($format);
$genre = $_REQUEST['genre'] ; $genre = strip_tags($genre);
$category = $_REQUEST['category'] ; $category = strip_tags($category);
$bookcase = $_REQUEST['bookcase'] ; $bookcase = strip_tags($bookcase);
$shelf = $_REQUEST['shelf'] ; $shelf = strip_tags($shelf);
$username = $_REQUEST['user_id'] ; $username = strip_tags($username);
# On success, register user
if (empty($errors))
# Insert the user into the database
{
$insert_sql = "INSERT INTO library (title, author, publisher, pub_date, isbn, format, genre, category, bookcase, shelf, time_entered, by) VALUES ( '$title', '$author', '$publisher', '$pub_date', '$isbn', '$format', '$genre', '$category', '$bookcase', '$shelf', NOW(), '$username' )";
mysqli_query($ptah,$insert_sql) or die(mysqli_error($ptah));
mysqli_close($ptah);
exit();
};
?>
On submission, I get the following error.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'by) VALUES ( 'Gently Does It', 'Hunter Alan', 'Robinson', '2010', '1234567890', ' at line 1
This misses out format, genre, category, bookcase, shelf, date entered and by whom completely.
Interestingly, the amount of data to be submitted will vary with the length of individual pieces,
for instance
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'by) VALUES ( 'The Hundred Year Old Man Who Climbed Out of a Window And Disappear' at line 1
doesn't even finish the title whereas
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'by) VALUES ( 'a', 'b', 'c', '1234', '1', 'Paperback', 'Fiction', 'Fantasy', 'a1'' at line 1
makes it as far as bookcase.
I'm stumped. Could anyone help please.
BY is a reserved word in MySQL so you should escape it with backticks ` in case you need to use it as a field name .
<...> , time_entered, `by`) <...>
BY is a reserved word in MySQL. In order to use it as an identifier in a query you need to enclose it with backticks:
... time_entered, `by`) VALUES (...
It's generally good practice to always enclose identifiers (column names, table names, etc.) with backticks anyway. It's more explicit to the query engine.

working perl ascript now says .DBD::mysql::db do failed: You have an error in your SQL syntax;

I got this perl script and it used to work fine till recently.
i am getting this error message.
DBD::mysql::db do failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' '')
ON DUPLICATE KEY UPDATE value=''' at line 2 at import_productfeatures.pl line 71.
DBD::mysql::db do failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL serve r version for the right syntax to use near ' '')
ON DUPLICATE KEY UPDATE value=''' at line 2 at import_productfeatures.pl line 71.
foreach my $feature (#features) {
my $cat_featureid = $feature->{CategoryFeature_ID};
my $value = $feature->{Presentation_Value};
my $sql = "INSERT INTO products_features (product_id, feature_id, value)
VALUES (".$prodid.", ".$cat_featureid.", ".$dbh->quote($value).")
ON DUPLICATE KEY UPDATE value=".$dbh->quote($value);
$dbh->do($sql);
}
You should use placeholders, instead of putting the values directly into the string:
my $sql = "INSERT INTO products_features (product_id, feature_id, value)
VALUES (?,?,?)
ON DUPLICATE KEY UPDATE value=?";
my $sth = $dbh->prepare($sql);
foreach my $feature (#features) {
my $cat_featureid = $feature->{CategoryFeature_ID};
my $value = $feature->{Presentation_Value};
$sth->execute($prodid,$cat_featureid,$value,$value);
}
$sth->finish();
DBI will handle the correct escaping for you.
Print out the value of $sql so you can see the SQL statement that you are building. Then you can see what the syntax problem is, or post it here so we can diagnose it.
However, even more than that, you should be using parametrized queries, not building SQL statements with untrusted external data. You are leaving yourself open to SQL injection. Please see http://bobby-tables.com/perl.html for examples on how to do it properly.
I think u missed single quote.
change
my $sql = "INSERT INTO products_features (product_id, feature_id, value)
VALUES (".$prodid.", ".$cat_featureid.", ".$dbh->quote($value).")
ON DUPLICATE KEY UPDATE value=".$dbh->quote($value);
to
my $sql = "INSERT INTO products_features (product_id, feature_id, value)
VALUES (".$prodid.", ".$cat_featureid.", '".$dbh->quote($value)."')
ON DUPLICATE KEY UPDATE value='".$dbh->quote($value."'");

ON DUPLICATE KEY not working correctly

I am running the following query, but getting an error. I think it is coming from the ON DUPLICATE KEY part, but I'm not 100% sure what the correct syntax is to use there.
<?php
$form_id = $form->data['form_id'];
$cfid = $form->data['cf_id'];
$datesent = $form->data['datesent'];
$query = mysql_query("
INSERT INTO `email_history` (
`cf_id` ,
`$form_id`
)
VALUES (
'$cfid', '$datesent'
)
ON DUPLICATE KEY
UPDATE INTO
`email_history` (
`$form_id`
)
VALUES (
'$datesent'
);
") or die(mysql_error());
?>
EDIT
Using the following I am getting this error :
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 10
<?php
$form_id = $form->data['form_id'];
$cfid = $form->data['cf_id'];
$datesent = $form->data['datesent'];
$query = mysql_query("
INSERT INTO `email_history` (
`cf_id` ,
`$form_id`
)
VALUES (
'$cfid', '$datesent'
)
ON DUPLICATE KEY
UPDATE `$form_id` = `$datesent`
);
") or die(mysql_error());
?>
The correct syntax of ON DUPLICATE KEY is something a long the lines described below.
Please note that it's just an example snippet, though it should be clear why your provided snippet fails to execute.
INSERT INTO tbl (
col1, col2, ... , colN
) VALUES (
#val1, #val2, ..., #valN
) ON DUPLICATE KEY UPDATE
col3 = VALUES(col3), col4 = #val4
Documentation
MySQL 5.0 Reference Manual :: 12.2.5.3 INSERT ... ON DUPLICATE KEY UPDATE Syntax
How would that look in my code?
$form_id = $form->data['form_id'];
$cfid = $form->data['cf_id'];
$datesent = $form->data['datesent'];
$query = mysql_query (<<<EOT
INSERT INTO `email_history` (`cf_id`, `$form_id`)
VALUES ('$cfid', '$datesent')
ON DUPLICATE KEY UPDATE `$form_id` = VALUES(`$form_id`)
EOT
) or die (mysql_error ());
What does VALUES($form_id) do?
It will yield the value of what was originally passed as the value for column named $form_id.
What is the use of <<<EOT?
In the previous snippet we are using a HEREDOC to have a string span multiple lines in an easy manner. You can read more about it in the documentation for heredocs.