Checking if variables match table row in SQL - mysql

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

Related

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.

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

How to allow users to edit a post using the sql UPDATE statement?

I am trying to let users edit the content that they post. The content is seperated into two sections the title and the text. It also has a category but I don't want to let them edit that. So here is the code that is suppose to update any changes to the title:
$sql = "UPDATE
topics
SET topic_subject = " . mysql_real_escape_string($_POST['topic_subject']) . "
WHERE
topic_id = " . mysql_real_escape_string($_GET['id']);
The code that updates the content has the same format.
I get the id from the url of the page and once they click submit on the editing page the form calls the page that contains this code. It gives me this error:
An error occurred while inserting your data. Please try again later.
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 'WHERE topic_id =' at line 4
I am not an expert in SQL and don't know what the problem could be. Thanks in advance.
You're missing single quotes around your string value:
$subject = mysql_real_escape_string($_POST['topic_subject']);
$topic_id = (is_numeric($_GET['id']) ? $_GET['id'] : 'NULL');
$sql = "
UPDATE topics
SET topic_subject = '$subject'
WHERE topic_id = $topic_id
";
My code also assumes topic_id is an int column, so I'm checking if the value is numeric instead of escaping it.

Syntax Error for around LIMIT

I'm working on a training course for PHP and I think the mysql syntax is outdated. This is the function
function get_subject_by_id($subject_id) {
global $connection;
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE id=" . $subject_id ." ";
$query .= "LIMIT 1";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
if ($subject = mysql_fetch_array($result_set)) {
return $subject;
} else {
return NULL;
}
}
and I'm getting back this error:
Database query failed: 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 'LIMIT 1' at line 1
I'm not sure what I'm doing wrong here. Any help from someone who knows what might have changed in the syntax would be greatly appreciated.
$query = "SELECT *
FROM subjects
WHERE id = $subject_id
LIMIT 1";
Query fails because $subject_id is empty.
SELECT * FROM subjects WHERE id= LIMIT 1
apparently the $subject_id is causing the trouble, check if the value is passed correctly.
Two wild guesses:
You did not quote / escape $subject_id which contains a string or something non-integer (such as FALSE, NULL or the empty string).
Even if this is not the cause, it makes your script vulnerable to SQL injection.
You are using a Mac for coding and have erroneously inserted a non-breakable space