SQL query dosnt know variables - mysql

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']);
.
.
.

Related

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' ...

Unknown column in 'where clause

I've read almost every single thread around the net about the Unknown column 'dfsd' in 'where clause
the dfsd is the string that I entered through a html form using the post method..
the php file(where the forms data are being sent) just checks if the line above is an existing user name.
function authCheck($usr,$psw){
print $usr;
mysql_real_escape_string($usr);
$sql = "select usrNameMarket from marketusr where usrNameMarket=$usr";
$result = mysql_query($sql) or die(mysql_error());
$records=mysql_num_rows($result); //elenxw gia eggrafes
if($records){
$queryData=mysql_fetch_array($result);
if($queryData['usrNameMarket']==$usr){
$usrNameChk="ok";
}
else{
$usrNameChk=null;
}
}
else{
$usrNameChk=null;
}
rest of the file ....
I get the error from MySQL telling me the column doesn't exist (although the value has been passed correctly, that's why I used the print function just to double check it)...
I add the single quotes:
$sql = "select usrNameMarket from marketusr where usrNameMarket='$usr'";
Then I get a syntax error when mysql_query executes...
Then I tried
$sql = "select usrNameMarket from marketusr where usrNameMarket='".$usr."'";
Still I get the same syntax error.
I don't know what is wrong I've tried everything...
Is it possible that I get that error because of the database structure or scheme or the data type of that field(which is varchar)?
Use marketusr.usrNameMarket instead of just usrNameMarket
try with:
$sql = "select usrNameMarket from marketusr where usrNameMarket='$usr'";

PHP/MySQL - Best use and practice of escaping strings [duplicate]

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.

CodeIgniter Active Record, basic update give error

I'm new to CodeIgniter and I get an error I cannot understand.
This is the code that give the error:
$data = array('adr' => $address);
$this->db->where('id', $id);
$this->db->update('domains', $data);
The error is:
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 '://www.example.com WHERE id = '10'' at line 1
This is the query:
UPDATE `domains` SET `adr` = http://www.example.com WHERE `id` = '10'
If I change this to
UPDATE `domains` SET `adr` = 'http://www.example.com' WHERE `id` = '10'
it works. Why is CodeIgniter creating this erroneous query?
Try escaping the single quotes in the $address variable before you call the update method.
Generally the CodeIgniter will automatically surround the value of $address with a single quote. I do not know why did you get this error message?
Curious, see if it works when you escape the string use $this->db->escape()
$data = array('adr' => $this->db->escape($address));
$this->db->where('id', $id);
$this->db->update('domains', $data);
I have the same problem and codeigniter do not add single qoutes to where clause.
When you enter integer value, sql do not give error but when you put string value (as a variable) to where clause, it gives error. But when you add single quotes to query and run it on phpmyadmin, it works.
So the solution is adding (string) statement to your variable: as in this (string)$id
I wrote before to add single quotes to variable as '$id', but this will not going to work (I'm new to codeigniter&php, thanks to commenter Mitchell McKenna, I checked out what I wrote before)