Escaping query values in MySQL Query (node-mysql) - mysql

I am trying to use node-mysql Escaping query values but when I try and insert it into my MySQL query I am getting errors and can't seem to find the problem. I have tried laying out the code in different ways as well, like the one seen in github example I linked.
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 'don\\'t spam!''' at line 1
banReason = Don't spam!
var banr = con.escape(banReason)
let sql
sql = `INSERT INTO modlog (senderid, victimid, duration, releasedate, reason) VALUES ('${message.author.id}', '${user}', '${timeCode}', '${moment().add(timeValue, timeType)}', '${banr}'`
con.query(sql)

To answer the question the correct method is to use ? that can be seen on the node-mysql GitHub
Fixed code:
var values = {senderid: message.author.id, victimid: user, duration: timeCode, releasedate: releaseDate, reason: banReason}
con.query('INSERT INTO modlog SET ?', values, function(err, result) {})
See example from referenced answere

Related

Syntax error in SQL when inserting data via nodejs

I have a simple nodejs code in pipedream that sends the body email to mySQL Database.
i have checked the connection to database and its working.
Here is my code
const mysql = require('mysql2/promise');
const { host, port, username, password, database } = auths.mysql
const connection = await mysql.createConnection({
host,
port,//3306
user:"u648845344_demo",
password,
database,
});
const [rows, fields] = await connection.execute(
"INSERT INTO Testing (Email) VALUES (${JSON.stringify(steps.trigger.event.body.email)})"
);
console.log(rows);
//console.log(${JSON.stringify(steps.trigger.event.body.email)})
Error i am getting
ErrorYou have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near '{JSON.stringify(steps.trigger.event.body.email)})' at line 1 at
PromiseConnection.execute
(/tmp/ee/node_modules/mysql2/promise.js:110:22) at
Object.module.exports (/steps/mysql.js:14:41) at process._tickCallback
(internal/process/next_tick.js:68:7)
i tried getting email on console log but then error i am getting is
TypeError [ERR_INVALID_ARG_TYPE]The first argument must be one of type
string, Buffer, ArrayBuffer, Array, or Array-like Object. Received
type undefined
This is a classic SQL injection bug, and it's easily fixed by using prepared statements:
const [rows, fields] = await connection.execute(
"INSERT INTO Testing (Email) VALUES (?)",
[ steps.trigger.event.body.email ]
);
If you write your queries without data, just placeholders, and use methods like this to add the data to the query via the driver you will not create any SQL injection bugs. These are an extremely serious form of bug because a single one, if discovered, could lead to a catastrophic outcome for you, your project and any business you're working for.
Using JSON.stringify for SQL protection is, and I cannot stress this enough, completely and wildly inappropriate. That escapes JSON and only JSON. You must use SQL-specific escaping functions if that occasion arises, but use prepared statements with placeholder values whenever possible.

spring boot get data from mysql table given by url

I want to create simple app to search some data in specific table.
I've got one database and can connect to it.
Also when I hardcoded table name it works great.
But I want to make url like that:
/demo/{table}/{author}
It should work that i give specific table for eg. 'comedy' and next I set name of author for eg. 'smith'.
My booksRepository:
#Query(value = "SELECT * FROM :table WHERE author = :author",
nativeQuery=true)
public List<Book> findByAuthor(#Param("author") String author, #Param("table") String table);
But it didn't work. I've got 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 ''comedy' WHERE author = 'Smith'' at line 1
It's adding ' to Query. Is there way to delete that? Is it possible or I need to put everything in one table?
Cheers :)
I haven't looked it up, but it seems that the variables in the query SQL can only be used to insert quoted values, not unquoted identifiers like a table name.

Getting an error after using PHP & MySQL code

I get the usual errors ( already tried to read previous questions ) Query failedYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''','',now(),'','This is great! ','', 'published')' at line 1
Thank you for helping!!
Here is my code:
My Code
The page in question is here:enter link description here
Thanks you very much for helping
The problem was on the line 20--> $query .= "VALUES({$post_category_id}. It need to be quotes around '{$post_category_id}'.
I don't know exactly why. the category id is a number , so for that shouldn't be around quotes because is a number.That's how our teacher explained to as.Thanks for your help.
The $connection variable isn't defined anywhere...
I just populated your page with some example data and that was the query I got:
INSERT INTO posts(post_category_id, post_title, post_author,post_date,post_image,post_content,post_tags,post_status) VALUES(,'','',now(),'',' Test','', 'Test')
The problem is near the VALUES keyword: VALUES (, is wrong. You should check first if every input value is populated correctly, eg if $post_category_id is defined with a valid value.

IF condition MySQL not working

I am trying to execute a query into MySQL but it keeps telling me i am using the wrong syntax, I tried searching the MySQL community but I am not getting anything usefull.. most of the answers i find on google are for other databases yet they label them for "MySQL", yet it keeps failing.
This is the statement i am trying to execute:
$statement = "IF (SELECT ttb_id FROM timetable WHERE ttb_week = $i AND ttb_time = $j) THEN
BEGIN
UPDATE types SET typ_name = '$subj'
WHERE typ_name = 'student';
END;
ELSE
BEGIN
INSERT INTO types VALUES (null,`Yo`);
END;
";
error:
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 'IF (SELECT ttb_id FROM timetable WHERE ttb_week = 0 AND ttb_time = 0) THEN ' at line 1
I am using:
PHP Script Language Version 5.2.6
MySQL Database Version 5.0.51b
I have been looking around but to no avail, and the if condition stated on the MySQL dev website are not helping at all..
I am new to this and it is driving me mad! all the different queries i tried failed.. it is never the right syntax.
I found many answers for the problem on stackExchange and other websites but it is always wrong.. also I remember this structure from a VB.net lesson a while ago so maybe this is for MSSQL? then what about MySQL? everyone so far listed similar structure and said it works for MySQL, I took my answer from an answer on this community* labeled for MySQL and he claimed it worked. this is one of many i tried.
I would really appreciate your help
*: Usage of MySQL's "IF EXISTS"
My first thought would be you're not comparing your SELECT return to anything to actually utilize your conditional logic. Are you just looking to see if your query returns values? If it doesn't return a value then you insert a new record in otherwise you update.
Maybe use IS NOT NULL or a check to see count on the select to see how many rows and compare to see if that's greater than 0.
IF (SELECT ttb_id FROM timetable WHERE ttb_week = $i AND ttb_time = $j IS NOT NULL) THEN
IF (SELECT COUNT(*) FROM timetable WHERE ttb_week = $i AND ttb_time = $j) > 0 THEN

Rails 3 MySQL 2 reports an error in what looks to be valid SQL syntax

I am trying to use the following bit of code to help in seeding my database. I need to add data continually over development and do not want to have to completely reseed data every time I add something new to the seeds.rb file. So I added the following function to insert the data if it doesn't already exist.
def AddSetting(group, name, value, desc)
Admin::Setting.create({group: group, name: name, value: value, description: desc}) unless Admin::Setting.find_by_sql("SELECT * FROM admin_settings WHERE group = '#{group}' AND name = '#{name}';").exists?
end
AddSetting('google', 'analytics_id', '', 'The ID of your Google Analytics account.')
AddSetting('general', 'page_title', '', '')
AddSetting('general', 'tag_line', '', '')
This function is included in the db/seeds.rb file. Is this the right way to do this?
However I am getting the following error when I try to run it through rake.
rake aborted!
Mysql2::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 'group = 'google' AND name = 'analytics_id'' at line 1: SELECT * FROM admin_settings WHERE group = 'google' AND name = 'analytics_id';
Tasks: TOP => db:seed
(See full trace by running task with --trace)
Process finished with exit code 1
What is confusing me is that I am generating correct SQL as far as I can tell. In fact my code generates the SQL and I pass that to the find_by_sql function for the model, Rails itself can't be changing the SQL, or is it?
SELECT * FROM admin_settings WHERE group = 'google' AND name = 'analytics_id';
I've written a lot of SQL over the years and I've looked through similar questions here. Maybe I've missed something, but I cannot see it.
"group" is a keyword so you can't use it as-is as an identifier, you have to quote it with backticks (for MySQL at least):
SELECT *
FROM admin_settings
WHERE `group` = 'google'
AND name = 'analytics_id'
Any SQL that Rails/ActiveRecord generates will use the quoted version of the column name so I'd guess that you're generating some SQL (or just a snippet of SQL for the WHERE clause) and neglecting to quote the column names.
I'd recommend against using group as a column name, use something else so that you don't have to worry about sprinkling backticks all over the place in your code.
group is an invalid field name if left unquoted, as it is a SQL keyword. To fix, surround it with backticks in your find_by_sql query, so your DB doesn't attempt to interpret it as the GROUP keyword.