MySQL Syntax Error - Extra eyes? - mysql

Can someone run their eyes over this statement? I keep getting a syntax error and I'm stumped as to what is wrong.
mysql_query("INSERT INTO emails (to, from, subject, content, ip) VALUES('$email_to', '$email_from', '$subject', '$content', '$ip' ) ")
Thanks!
EDIT: 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 ''to', 'from', subject, content, ip) VALUES('[MY EMAIL ADDRESS]', 'l', 'hi', ' at line 1
EDIT 2:
I have sanitized.
$email_to = mysql_real_escape_string($_POST['email_to']);
$email_from = mysql_real_escape_string($_POST['email_from']);
$subject = mysql_real_escape_string($_POST['subject']);
$content = mysql_real_escape_string($_POST['content']);

Try this:
mysql_query(
"INSERT INTO emails (`to`, `from`, subject, content, ip)
VALUES('$email_to', '$email_from', '$subject', '$content', '$ip' )")
I think the error raises because from is a reserved word... backticks should solve this problem.
Remember you MUST always sanitize user input to avoid SQL injection!!

Perhaps escape the 'from' field, as from is a keyword;

Related

PARSE_ERROR MySQL

These lines give me the parse error, ı checked my syntax many times but it seems alright to me. I don't understand why does it give this error
code:
INSERT INTO club_request(RequestID,"Besiktas")
SELECT RequestID
FROM Request
WHERE RequestName = "New goalkeeper";
error:
ER_PARSE_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 '"Besiktas") SELECT RequestID FROM Request WHERE RequestName = "New goalkeeper"' at line 1
INSERT INTO club_request(RequestID, ClubName)
SELECT RequestID, ClubName
FROM Request, Club
WHERE RequestName = "New goalkeeper" AND ClubName = "Besiktas";
lately I have turned it into this and now it works as I wanted, can't we insert partial value from select clause and partial value as a string ?

Unknown SQL syntax error for ScalikeJDBC with SQL interpolation

To avoid DRY, I'm attempting to create an sql INSERT statement with variable column names and the data to fill those columns via ScalikeJDBC's sql interpolation:
case class MySQLInsertMessage(tableName:String, columns:List[String], values:List[String])
def depositMessage(msg: MySQLInsertMessage): Unit = {
NamedDB('MySQLMsgDepositor) localTx { implicit session =>
val sqlStmt = sql"INSERT INTO ${msg.tableName} (${msg.columns}) VALUES (${msg.values})"
println("The sql statement is: " + sqlStmt.statement)
println("The parameters are: " + sqlStmt.parameters)
sqlStmt.update().apply()
}
}
And when I call this with:
depositMessage(MySQLInsertMessage("My_Table", List("key", "email"), List("42", "user#email.com")))
the resulting console printout is:
The sql statement is: INSERT INTO ? (?, ?) VALUES (?, ?)
The
parameters are: List(My_Table, key, email, 42, user#email.com)
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 ''My_Table'
('key', 'email') VALUES ('42', 'user#emai' at line 1
java.sql.SQLSyntaxErrorException: 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 ''My_Table' ('key', 'email') VALUES
('42', 'user#emai' at line 1
I've tried wrapping the sql"..." as such instead:sql"""...""", but that doesn't seem to make a difference. I can execute the expected statement just fine in my MySQL workbench GUI. Any idea what my syntax error is?
Stemming from the hint from #scaisEdge, it seems ScalikeJDBC, when using its syntax, will always place single quotes around any parameterized values. And judging from here - https://github.com/scalikejdbc/scalikejdbc/issues/320 - this is a known issue.
With a MySQL INSERT statement (or others), your table name or column values may not have single quotes around them, though they are allowed to have backticks.
You can use their SQLSyntax.createUnsafely(str:String) method, or, if I wanted to do this as I was doing above, instead of using sql"...", I could use the old way of SQL(s"INSERT INTO ${msg.tableName} (${msg.columns.mkString(",")})")
Note - I believe both of these leave you open to injection attacks. Since, for me, this is a local API and you'd have to have the DB's username and password regardless to use it, I'm going with the createUnsafely way of doing things, with a little regex "cleaner" for a little inelegant piece of mind:
def depositMessage(msg: MySQLInsertMessage): Unit = {
NamedDB('MySQLMsgDepositor) localTx { implicit session =>
val unsafeSQLRegex = "[`'\"]".r
val table = SQLSyntax.createUnsafely(s"`${unsafeSQLRegex.replaceAllIn(msg.tableName, "")}`")
val columns = SQLSyntax.createUnsafely(msg.columns.map(value => unsafeSQLRegex.replaceAllIn(value, "")).mkString("`", "`, `", "`"))
val sqlStmt = sql"INSERT INTO $table ($columns) VALUES (${msg.values})".update().apply()
}
}
}

Checking if variables match table row in SQL

I have tried a million different solutions and cannot seem to figure this one out. I am (right now) just trying to pull all instances from the DB that the email and key match and display them but I keep getting
"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 'Key = abaa937f092451741dfe172e51f68f69 AND Email= test#test.com'"
Not sure where I am going wrong but it is likely a simple solution.
//check if the key is in the database
$check_key = mysqli_query($con, "SELECT * FROM confirm WHERE Key = '$key' AND Email= '$email'")
or die(mysqli_error($con));
while($row = mysqli_fetch_array($check_key)) {
echo $row['Email'] . " " . $row['Key'];
echo "<br>";
}
key is a reserved word in MySQL. Either use backticks to escape it or use another name.
SELECT * FROM confirm
WHERE `Key` = '$key' ...

MYSQL: inserting error

MYSQL Problem inserting Certain type of Text
when i try to insert this for example:
INSERT INTO `Attacks_key`
(`Event_Key` ,`Variable` ,`Value` ,`Impact` ,`Tags`)
VALUES
('111', 'REQUEST', ' mysql_real_escape ', '222', 'xss, csrf, id, rfe, lfi');
its inserted But when I try to insert this :
INSERT INTO `Attacks_key`
(`Event_Key` ,`Variable` ,`Value` ,`Impact` ,`Tags`)
VALUES
('111', 'REQUEST', 'mysql_real_escape_string($_POST['username']); ', '222', 'xss, csrf, id, rfe, lfi');
MYSQL display this message :
#1064 - 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 'username']); ', '222', 'xss, csrf, id, rfe, lfi')' at line 1
and this is my php code
$user="root";
$password="*";
$database="*";
mysql_connect(localhost,$user,$password);
#mysql_select_db($database) or die( "Unable to select database");
$sql = "SELECT `Key_id` FROM `Event` ORDER BY `Key_id` DESC LIMIT 1";
$result =mysql_query($sql);
$row = mysql_fetch_assoc($result);
$EventKey= $row['Key_id'];
$query="INSERT INTO `PHPLOGS`.`Attacks_key` (`Event_Key` ,`Variable` ,`Value` ,`Impact` ,`Tags`) VALUES ('$EventKey', '$getname', '$getvalue', '$getimpec', '$gettags');";
mysql_query($query);
mysql_close();
and the input 'mysql_real_escape_string($_POST['username']); from the user
Can someone help
thanks
Try
$query = sprintf("INSERT INTO Attacks_key (Event_Key ,Variable ,Value ,Impact ,Tags) VALUES ('111', 'REQUEST', '%s', '222', 'xss, csrf, id, rfe, lfi');",
mysql_real_escape_string($_POST['username']));
There's a conflict of ' in that part of the statement with 'username'
Have a look at mysql_real_escape_string
If you're inserting mysql_real_escape_string($_POST['username']); literally, then escape the single quotes.
INSERT INTO `Attacks_key`
(`Event_Key` ,`Variable` ,`Value` ,`Impact` ,`Tags`)
VALUES
('111', 'REQUEST', 'mysql_real_escape_string($_POST[\'username\']); ', '222', 'xss, csrf, id, rfe, lfi');
As you should really really switch to PDO instead of the deprecated mysql_ functions you could use PDO::quote
PDO::quote() places quotes around the input string (if required) and
escapes special characters within the input string, using a quoting
style appropriate to the underlying driver.
However, the preferred way of doing queries is by using prepared queries, and in that case you wouldn't have the quote escaping problem anyways. Again quoting from the php manual page for PDO:;quote
If you are using this function to build SQL statements, you are
strongly recommended to use PDO::prepare() to prepare SQL statements
with bound parameters instead of using PDO::quote() to interpolate
user input into an SQL statement. Prepared statements with bound
parameters are not only more portable, more convenient, immune to SQL
injection, but are often much faster to execute than interpolated
queries, as both the server and client side can cache a compiled form
of the query.
If for whatever reason PDO isn't an option, there's mysqli_real_escape_string with a similar functionalty.

SQL syntax; Error

I am trying to add this query to database and I can't get it to work. Any help will be appreciated. I am trying to learn mysql I saw a website has a reservation system and I just wanted to learn how to create one.. but 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 ''reservation'( service_type, passengers, sedans, s' at line 1
$query = "INSERT INTO 'example'(
service_type,
passengers,
sedans,
suv,
limo,
pass_name,
pass_phone,
pass_email,
book_name,
book_phone,
pickup_type,
pickup_point,
pickup_airline,
pickup_flightno,
pick_airportlocation,
pick_address,
reservation_datetime,
drop_type,
drop_airline,
drop_flightno,
drop_address,
stop_1,
stop_2,
stop_3,
stop_4,
stop_5,
stop_6,
stop_7,
stop_8,
stop_9,
stop_10,
additional_info,
payment_type,
pickup_latitude,
pickup_longitude,
drop_latitude,
drop_longitude,
created
) VALUES (
'$service_type',
'$passengers',
'$sedans',
'$suv',
'$limo',
'$pass_name',
'$pass_phone',
'$pass_email',
'$book_name',
'$book_phone',
'$pickup_type',
'$pickup_point',
'$pickup_airline',
'$pickup_flightno',
'$pick_airportlocation',
'$pick_address',
'$reservation_datetime',
'$drop_type',
'$drop_airline',
'$drop_flightno',
'$drop_address',
'$stop_1',
'$stop_2',
'$stop_3',
'$stop_4',
'$stop_5',
'$stop_6',
'$stop_7',
'$stop_8',
'$stop_9',
'$stop_10',
'$additional_info',
'$payment_type',
'$pickup_latitude',
'$pickup_longitude',
'$drop_latitude',
'$drop_longitude',
'$created')";
Your table name needs to be enclosed in backticks `, not single quotes ':
INSERT INTO `example`
If you have variables that are strings you need to quote them in the insert statement. This is a very common mistake that people do.