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.
Related
for($count = 0; $count < count($_POST["item_sub_category"]); $count++)
{
$data = array(
':item_sub_category_id'
=> SELECT r_name FROM Repair where r_id = $_POST["item_sub_category"][$count]
);
$query = "INSERT INTO Repairlog (description,visitID) VALUES (:item_sub_category_id,'1')";
$statement = $connect->prepare($query);
$statement->execute($data);
}
As far as concerns, your code won't work. The SQL query that you are passing as a parameter will simply be interpreted as a string.
You could avoid the need for a loop by taking advantage of the INSERT INTO ... SELECT ... syntax. The idea is to generate an IN clause that contains all values that are in the array, and then run a single query to insert all records at once.
Consider:
$in = str_repeat('?,', count($_POST["item_sub_category"]) - 1) . '?';
$query = "INSERT INTO Repairlog (description,visitID) SELECT r_name, 1 FROM Repair WHERE r_id IN ($in)";
$statement = $connect->prepare($query);
$statement->execute($_POST["item_sub_category"]);
Note: it is likely that visitID is an integer and not a string; if so, then it is better not to surround the value with single quotes (I removed them in the above code).
TLDR; No.
Your question can be re-framed as: Can I write SQL code in php. The answer is NO. You can write the SQL code within a String type variable (or parameter) in php.
This is a general rule for any programming language, you cannot have multiple languages within the same file, as the language parser will not be able understand which syntax is that.
In order to embed a different language in another language, you need some kind of separator that will define when the new language or special type will start and when it will end.
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()
}
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to prevent SQL Injection in PHP
What is the best way to escape strings when making a query?
mysql_real_escape_string() seems good but I do not exactly know how to use it in properly.
Does this code do the job properly?
<?php
/* Let's say that the user types "'#""#''"\{(})#&/\€ in a textfield */
$newStr = mysql_real_escape_string($str);
$query = "INSERT INTO table username VALUES ($str)";
mysql_query($query);
?>
EDIT:
Now I have this code:
$email = $_POST['email'];
$displayName = $_POST['displayName'];
$pass = $_POST['pass1'];
$email = mysqli_real_escape_string($link, $email);
$displayName = mysqli_real_escape_string($link, $displayName);
$pass = mysqli_real_escape_string($link, $pass);
$insert = "INSERT INTO profiles (email, displayName, password)
VALUES ('$email', '$displayName', md5('$pass'))";
mysqli_query($link, $insert)
or die(mysqli_error($link));
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 '!"#!#^!"#!"#!"#^'''''' at line 1
If the user enters:
'**!"#!#^!"#!"*#!"#^''''
The best way is not to escape the string at all, but instead use a parameterized query, which does it for you behind the scenes.
Using mysql_real_escape_string like that will work, but you need to:
Add quotes around the value.
Use the result $newStr, not the original value $str.
Change the tablename to a name that isn't a reserved keyword.
Add parentheses around the column list.
Try this:
$query = "INSERT INTO yourtable (username) VALUES ('$newStr')";
I also suggest that you check the result of mysql_query($query) and if there is an error, you can examine the error message:
if (!mysql_query($query))
{
trigger_error(mysql_error());
}
You should also consider using one of the newer interfaces to MySQL. The old mysql_* functions are deprecated and should not be used in new code.
I am trying to query some tables in my database using a simple dropdown in which the name of the tables are listed. the query has only one record result showing the name and age of the youngest institute registered in the database!
$table = $_GET['table'];
$query = "select max('$table'.est_year) as 'establish_year' from '$table' ";
I need to send the name of the table as variable to the querier php file. no matter the method is GET or POST in both ways when I put the variable name in the query statement, it gives the 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 '.order) as 'last' from 'customers'' "
You are wrapping the table name in single quotes, which is not valid SQL (that's the syntax for strings, not table names). You should either not wrap the name at all or else wrap it in backticks (on the american keyboard layout, that's the key above TAB).
You should also not quote the alias established_year:
select max(`$table`.est_year) as establish_year from `$table`
Also, your code is vulnerable to SQL injection. Fix this immediately!
Update (sql injection defense):
In this case the most appropriate action would likely be to validate the table name against a whitelist:
if (!in_array($table, array('allowed_table_1', '...'))) {
die("Invalid table name");
}
single quote ('), in mysql, it represents string value.
SELECT *, 'table' FROM `table`;
Demo
So your query should be
$table = $_GET['table'];
$query = "select max($table.est_year) as 'establish_year' from $table ";
Also read old post, phpmyadmin sql apostrophe not working.
Also your code is vulnerable to SQL Injection. You can use something like this
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$firstName = clean($_POST['firstName']);
$lastName = clean($_POST['lastName']);
.
.
.
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;