This question already has answers here:
How can I write SQL for a table that shares the same name as a protected keyword in MySql? [duplicate]
(3 answers)
Closed 9 years ago.
I get a error message saying:
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='12345' AND id='98765' LIMIT 1' at line 1
My code is:
$key = '12345';
$id = '98765';
include realpath('./inc/config.php');
$query = mysql_query("SELECT * FROM users WHERE key='{$key}' AND id='{$id}' LIMIT 1", $config) or die(mysql_error());
$result = mysql_fetch_assoc($query);
Now can anyone tell me whats wrong in this?
key is a reserved word, you need to properly quote it with backticks if you want to use it as a field name.
SELECT * FROM users WHERE `key`='{$key}' AND id='{$id}' LIMIT 1
SELECT * FROM users WHERE `key`='{$key}' AND id='{$id}' LIMIT 1
key is a reserved word
Your key and id are obviously numeric. Although adding quotes wouldn't hurt, you definitely don't need them. You edon't need brackets in any query period.
Try this:
$query = mysql_query("SELECT * FROM users WHERE key=$key AND id=$id LIMIT 1", $config) or die(mysql_error());
$result = mysql_fetch_assoc($query);
If that doesn't work just run this using PHPMyAdmin or whatever you use to run queries on your db.
SELECT * FROM users WHERE key=12345 AND id=98765
I also don't see why you would need LIMIT clause. It wouldn't break anything but if your id is actually row id it should give you a unique record.
Related
This question already has answers here:
How to insert values in a PHP array to a MySQL table?
(2 answers)
Closed 5 years ago.
I'm using PHP session variable to track character ID's between two tables, characters and character_data_store.
The session ID definitely has the correct ID as I have had to print its value before it goes into the mySQL query.
For testing I selected a user I knew had a rapsheet and used
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.`key` = 'RapSheet'
AND character_data_store.character_id = '216'";
Obviously I can't use this for all users as I need to confirm the right one has been selected so thats where the session variable comes in.
I've tried using:
$correctPlayer = $_SESSION['selpid'];
echo $correctPlayer; #confirm it's the right id and then remove
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.'key' = 'RapSheet'
AND character_data_store.character_id = '$correctPlayer'";
I did some searching on SO and I found that int's need to have double quotes around them not single quotes, I tried that and had no luck but someone else suggested putting the session ID in exactly which I tried next:
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.'key' = 'RapSheet'
AND character_data_store.character_id = {$_SESSION['selpid']}";
Each time I do this I get mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given which SO tells me is because this operation results to false, I assume because it's not accepting the playerID from selpid or $correctPlayer?
It definitely works with the testing user where the playerID is inserted directly into the query. But I can't think of a way to do that since I need to match the playerID from table "characters" where the search is done against their first and last name and then pull the rapsheet data against the same playerID in table "character_data_store".
How do I use a variable in the WHERE condition of a MySQL query using a php variable?
You have obvious error in your code. You are missing quotes in {$_SESSION['selpid']} and you are using quotes in column name. Your query should be
$usersql = "SELECT * FROM character_data_store WHERE character_data_store.`key` = 'RapSheet' AND character_data_store.character_id = '{$_SESSION['selpid']}'";
You should not use quotes in column name, instead use backquotes(`) if you really need. I recommend prepared statements.
There are multiple ways to do this. A naive way to do this would be-
$usersql = "SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ".$correctPlayer;
But to avoid sql injections I would recommend you use bindparam function to bind paramaters in a statement.
$sql="SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ?";
if($stmt = $dbh->prepare($sql)){
$stmt->bindParam(1, $correctPlayer, PDO::PARAM_STR);
$ql = $stmt->execute() or die("ERROR: " . implode(":", $dbh->errorInfo()));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$result['data'] = $row;
This question already has answers here:
PHP Variable in Select Statement
(7 answers)
Closed 7 years ago.
I have the following problem:
I am trying to select a result from a MySQL database table, depending on the category value:
$sql = mysql_query("SELECT * FROM products WHERE category='garniture' ORDER BY date_added DESC LIMIT 2");
The problem is that I don't want to use a static value for category (like 'garniture'), but I want this to be determined by a variable value (let's say that variable is $category). How can I manage this?
Without getting into the fact that you should not be using the MySQL Library anymore, use MySQLi or PDO instead, you would insert a variable in that string as such:
$sql = mysql_query("SELECT * FROM products WHERE category='$category' ORDER BY date_added DESC LIMIT 2");
Or if you find it easier to read:
$sql = mysql_query("SELECT * FROM products WHERE category='" . $category . "' ORDER BY date_added DESC LIMIT 2");
$sql = mysql_query("SELECT * FROM products WHERE category='$category' ORDER BY date_added DESC LIMIT 2");
Just put the variable where you want it in the string.
The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.
See the PHP manual about string interpolation.
This question already has answers here:
MySQL query not working while using php variable in where clause
(3 answers)
Closed 8 years ago.
I am new to php so hopefully someone could point out where i am going wrong
I have written a php code to fetch certain records from an MySQL database
I am running the query as
$result = mysql_query("SELECT * FROM Messages where Id='idLo'")
or die(mysql_error());
i get no results
but when i hard code like
$result = mysql_query("SELECT * FROM Messages where Id='4'")
or die(mysql_error());
It returns all the data
What am i misisng
i am collecting idLo as a get parameter
$idLo = $_GET['id'];
Your code needs to change to
$result = mysql_query("SELECT * FROM Messages where Id='$idLo'") or die(mysql_error());
From
$result = mysql_query("SELECT * FROM Messages where Id='idLo'") or die(mysql_error());
There is basic thing that in php every variable has dollar( $ ) sign that we need to use every time while using it.
Try this:
$result = mysql_query("SELECT * FROM Messages where Id='$idLo'");
you forgot $ in front of idLo in your query.
$result = mysql_query("SELECT * FROM Messages where Id='".$idLo."'");
should do it
It appears that you haven't included the "$" to signify that idlo is a variable:
where Id='idLo'
should be
where Id='$idLo'
Also, you might want to have a look into using PDO or Mysqli for accessing your mysql database through PHP.
you should user mysqli pr PDO by now. A bit better:
$result = $connection->query("SELECT * FROM Messages where Id='$id'");
also, check if Id is really with capital letters and add a dollar sign to the variable name.
$idLo = $_GET['id'];
$result = mysql_query("SELECT * FROM Messages where Id='$idLo'") or die(mysql_error());
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I looked mostly everywhere on Stackoverflow for adding multiple WHERE instances but none of them seem to work.
My Select query:
$result = mysql_query("SELECT * FROM $tableName WHERE user = $user AND column = 1"); //query
I tried IN and some other ways but I dont know why it wont get the column. If I take out the user column it works, but I want it to also restrict to the column as well..
Any help will be appreciated!
column is reserved word in mysql. You have to use ` around that kind of column_name and use ' single quotes around string data '$user'
SELECT * FROM $tableName WHERE user = '$user' AND `column` = 1
You need to wrap the username in single-quotes & as mentioned by Yogesh column is a reserved keyword in MySQL. Try this:
user = '$user' AND `column` = 1
So the whole statement becomes:
$result = mysql_query("SELECT * FROM $tableName WHERE user = '$user' AND `column` = 1");
Also, you should be using mysqli or PDO with prepared statements instead.
Rewrite your query. Use the below code:
$result = mysql_query("SELECT * FROM `".$tableName."` WHERE user = '".$user."' AND `column` = 1");
And here I am missing that what is column in query is it name of column?
And you need to give the value in single quota and table name in ` till mark.
try this one:
$sql = 'SELECT * FROM $tableName WHERE user = "'.$user.'" AND `column` = 1';
I have a table with 4 record.
Records: 1) arup Sarma
2) Mitali Sarma
3) Nisha
4) haren Sarma
And I used the below SQL statement to get records from a search box.
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%$q' LIMIT 5";
But this retrieve all records from the table. Even if I type a non-existence word (eg.: hgasd or anything), it shows all the 4 record above. Where is the problem ? plz any advice..
This is my full code:
$q = ucwords(addslashes($_POST['q']));
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%".$q."' LIMIT 5";
$rsd = mysql_query($sql);
Your query is fine. Your problem is that $q does not have any value or you are appending the value incorrectly to your query, so you are effectively doing:
"SELECT id,name FROM ".user_table." WHERE name LIKE '%' LIMIT 5";
Use the following code to
A - Prevent SQL-injection
B - Prevent like with an empty $q
//$q = ucwords(addslashes($_POST['q']));
//Addslashes does not work to prevent SQL-injection!
$q = mysql_real_escape_string($_POST['q']);
if (isset($q)) {
$sql = "SELECT id,name FROM user_table WHERE name LIKE '%$q'
ORDER BY id DESC
LIMIT 5 OFFSET 0";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
echo "id: ".htmlentities($row['id']);
echo "name: ".htmlentities($row['name']);
}
} else { //$q is empty, handle the error }
A few comments on the code.
If you are not using PDO, but mysql instead, only mysql_real_escape_string will protect you from SQL-injection, nothing else will.
Always surround any $vars you inject into the code with single ' quotes. If you don't the escaping will not work and syntax error will hit you.
You can test an var with isset to see if it's filled.
Why are you concatenating the tablename? Just put the name of the table in the string as usual.
If you only select a few rows, you really need an order by clause so the outcome will not be random, here I've order the newest id, assuming id is an auto_increment field, newer id's will represent newer users.
If you echo data from the database, you need to escape that using htmlentities to prevent XSS security holes.
In mysql, like operator use '$' regex to represent end of any string.. and '%' is for beginning.. so any string will fall under this regex, that's why it returms all records.
Please refer to http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html once. Hope, this will help you.