Unknown column in 'where clause - mysql

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'";

Related

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.

SQL query dosnt know variables

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

mysql error unknown column in field list

Hey I'm tring the following sql query :
$sql = mysql_query("INSERT INTO feeds (FileLocation,Title,feeddate,nameofuploader,type)
VALUES('".mysql_real_escape_string($putItAt)."','".mysql_real_escape_string($_POST['title'])." ',now(),". $_SESSION['name'] .",'file')")
but its giving me the error:
Unknown column 'Ankit2' in 'field list'
where Ankit2 is the value to be inserted
Any way around this?
You forgot to put single quotes around the $_SESSION variable!
$sql = mysql_query("INSERT INTO feeds (FileLocation,Title,feeddate,nameofuploader,type)
VALUES('".mysql_real_escape_string($putItAt)."','".mysql_real_escape_string($_POST['title'])." ',now(),'". $_SESSION['name'] ."','file')")
Is the sql string right? Please try this to check your sql string:
$sql_str = "INSERT INTO feeds (FileLocation,Title,feeddate,nameofuploader,type) VALUES('".mysql_real_escape_string($putItAt)."','".mysql_real_escape_string($_POST['title'])." ',now(),". $_SESSION['name'] .",'file')";
print $sql_str;
to check the sql_st

How could a query fail to insert data into mysql that is retrieved from WEB?

I need to insert some data into mysql. I am not sure if I need to check the inputs OR format/strip them before they could be inserted into database fields as results returned from web may contain characters that mysql do not accept(I think). I have trouble with inserting tweets into mysql table. The type of field is varchar. This is insert statement in php script:
$json = $_POST['msg_top'];
$msg = json_decode($json);
foreach($msg->entry as $status)
{
$t = $status->content;
$query = "INSERT INTO msg2(id,msg,msg_id,depth) VALUES ('','$t','ID','3')";
mysql_query($query);
if(!mysql_query($query, $dbh))
{die('error:' .mysql_error());}
}
Yes, it's very important to escape all values before using them in an SQL command.
$json = $_POST['msg_top'];
$msg = json_decode($json);
foreach($msg->entry as $status) {
$t = mysql_real_escape_string($status->content);
$query = "INSERT INTO msg2(id,msg,msg_id,depth) VALUES ('','$t','ID','3')";
mysql_query($query);
if( !mysql_query($query, $dbh) ) {
die('error:' .mysql_error());
}
}
Also, other possible issues with your query:
If the id field is auto_increment'ing, you don't need it in the field or value list.
I may be missing something, but why are you using the string 'ID' for the msg_id field?
As for help troubleshooting this, I'd recommend just appending all of the $query strings to a log file for later inspection. Then, if problems aren't readily apparent, you can just manually try to run the command on the database (ie: maybe via PhpMyAdmin) and check out any error codes from there.

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)