What is wrong with my mysqli query? [duplicate] - php

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 7 years ago.
I am sorry if I sound noob but I need some help here. I cant figure out with this query:
$query = "SELECT * FROM msgs WHERE read = 1 AND userid='{$uId}' AND
orderid='{$oId}'; ";
When I do a var_dump on the query result i get bool(false) but when I do the same without the read = 1 part it returns results correctly so I guess the problem is with the read = 1 part. Please help, the read field type is tinyint(1).

You need to use back-ticks in your query because you used reserved keyword read:-
$query = "SELECT * FROM `msgs` WHERE `read` = 1 AND `userid`='{$uId}' AND `orderid`='{$oId}'";
Note:- read is reserved keyword here, i added around others because its not easy to remember all reserved keywords so using back-ticks around column name is better approach.
Link for depth knowledge given by #chris85 :- https://dev.mysql.com/doc/refman/5.5/en/keywords.html

Related

pagination in search page with search text starting with single quote in php [duplicate]

This question already has answers here:
How get post value in pagination
(2 answers)
Closed 8 years ago.
I am working on pagination on search result.I referred below link and I am not able to pass value when search text starts with single quote..
How get post value in pagination.
Can you please help me..
thanks
This is because the single quote is embedded into the literal string $sql. It halts the query, and this is dangerous because a hacker can do what is called SQL Injection -> https://www.acunetix.com/websitesecurity/sql-injection/ .
Anyway, the mysql extension has been deprecated, meaning it is no longer supported and maintained. You have two easy options: mysqli or PDO. I personally recommend using PDO -> http://cz1.php.net/PDO . It will be easy to convert your code.
With PDO you can bind your input to certain fields:
$sql="Select count(*) from FIMTRN_Memorial where FirstName like :search";
$sql = $database->prepare($sql);
$sql->execute(array(":search" => "%".$_SESSION['searchchar']."%"));
$result = $sql->fetchAll(PDO::FETCH_ASSOC);
I hope I could help!
UPDATE:
With the above parameterized query, your search string cannot contain a percentage sign, as this will act as a wild-card character.
UPDATE 2:
I don't know if you noticed that $_GET{'page'} is meant to be $_GET['page'] in the previous answer.

PHP mysql_query - update using all variables [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Can a number used to name a sql column
I am trying to figure out what is wrong with this code
$query = "UPDATE $table SET '$_GET[qty]'=$_GET[newprice] WHERE 'id'='1'";
this is what $query looks like - UPDATE retail_12x18 SET '25'=100 WHERE 'id'='1'
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 ''25'=100 WHERE 'id'='1'' at line 1
I have put backticks ' every which way and cant get it to go through, always the same error message.
use backtick around your field name:
UPDATE table SET `25` = '{thevalue}', `100` = '{thevalue}', `200` = '{thevalue}' WHERE wherefield = '{wherevalue}'
See here (look for backtick word): http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
It's a bit hard to know for sure, without seeing the table definition, but:
[1] It might be the column types. For instance this bit:
type=" .$_GET['type'];
is trying to set the value of the "type" column without using quotes. It will fail if the "type" column is type like varchar, for example.
[2] You need to use backtics if you're going to have numeric column names
[3] It really must be said that the main thing that's wrong with your code is that you are putting un-escaped $_GET values into your SQL query. Anyone could mount an SQL injection attack by putting SQL into the URL of the page. Very bad practice.
http://en.wikipedia.org/wiki/SQL_injection

PHP Mysql select from variable problem [duplicate]

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 have tried so many different soloutions but cannot get this to work
Here is my code:
$to = $_POST['to'];
$query = "SELECT to FROM to WHERE to='$to' "
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)){
I get a whole load of different errors every time i modify it. At the moment I'm getting
You have an error in your SQL syntax near to='Name'
When I modify it to fix this I get
mysql_fetch_array() not valid
It seems when using variables it messes up
can anyone help?
Thanks!
to is a reserved word in mySQL.
You would have to wrap each mention of the table or column name into backticks
SELECT `to` from `to`
but it would be vastly better to use a different name.
To is a Reserved keyword try escaping it by using "``" symbol
Check this Link
Reserved Keywords MYSQL
Consider changing the names of your field and table (Edit: Definitely change the names or at least escape them.) Also, all you are doing is selecting the variable you already have.

PHP/MySQL Insert [duplicate]

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.
Ok I have been using PHP + MySQL for a while so I consider myself proficient. I have made my fair share of syntactical mistakes in the past but this is honestly pissing me off:
http://img251.imageshack.us/img251/3760/fubar.png
If anyone can tell me why this simple statement isn't working I would be greatly appreciative.
Actually I do see 1 error..."Option" is a reserved word. wrap it in backtics : `Option` or better yet, change the column name to something that's not a reserved word.
Use backticks for 'option'.
INSERT INTO poll (`Option`) VALUES ('Stuff')
Looking at the code you're trying to insert what comes from $_POST['survey'], so your insert should look like this:
$vote = $_POST['survey'];
// connect to db
mysql_query(sprintf(
"INSERT INTO poll (`Option`) VALUES ('%s')",
mysql_real_escape_string($vote)
);
Also note that "option" is a reserved keyword and needs to be inside backticks.

PHP/MYSQL Trouble Selecting by Primary Key [duplicate]

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.
So I have a primary key column called key. I'm trying to select the row with key = 1 via this code:
$query ="SELECT * FROM Bowlers WHERE key = '1'";
$result = mysql_query($query) or die(mysql_error());
For some reason, I'm getting this result:
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 = '1'' at line 1
The mysql statement works for using other keys, ie WHERE name = 'djs22'.
Any ideas?
key is a reserved word, try putting ticks around it:
$query ="SELECT * FROM `Bowlers` WHERE `key` = '1'";
$result = mysql_query($query) or die(mysql_error());
To see all the reserved words, go here and scroll down:
http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html
'key' is a reserved keyword, put backtick quotes around it:
"SELECT * FROM Bowlers WHERE `key` = '1'"
Without checking, it's likely that "key" is a reserved word in MySQL.
Try wrapping it in backticks
$query ="SELECT * FROM Bowlers WHERE `key` = '1'";
You should write the column name key in quotes
$query ="SELECT * FROM Bowlers WHERE `key` = '1'";
Otherwise it is a keyword
I run into that all the time. MySQL has a crap load of reserved words. And when you come across one, the mysql error function is not even nice enough to let you know what is wrong.
The only thing you can do is change the column name. I accidentally used "date, to and from" the other day. Was pulling my hair out when it dawned on me, DuHH!!! those are DB reserved.
You can wrap all kind of quotes around it, it does not matter when it references a column name. Reserved is reserved!
It is common practice to to do a couple of things.
1) When making tables: Split resource type with resource name using underscore. Example: xref_userMessages
This would mean it is a cross reference table for User messages.
2) Other examples of table names: msg_Messages | sys_Settings | cli_Logins
So any other table made related to messages would be called msg_??? , not only does this keep them grouped together in phpMyadmin but makes remembering the names easier too.
3) When Making columns: Never use a reserved. Thus causing key columns to always be 6 didgets. Example: admkey | usrkey | msgkey | clikey grpkey
Obviously Admin Key | User Key | Message Key | Client Key | Group Key
So this means "msg_Messages" keys are "msgkey" and the xref table would be xref_Messages and its keys are xref_msgkey. Following this logic you not only know what to name everything without even thinking about it, but you never run into any reserved words doing it.
4) Examples of Column names: dateInsert dateStart timeCreate admName admAddress admPhone admCell
Just like above there is a logic to it. Placing purpose/owner and noun/item together makes the name and again avoids reserved words.
Last Example:
Table: users_Admins users_Clients
Key: admkey usrkey
Table: msg_Messages
Columns: msgkey admkey usrkey msgRead msgMessage msgTitle
Just in this short example I avoided 2 reserved words. Key and Read
So in short, your problem is not reading a primary key. It is a problem with column names.
MySQL is seeing your code as having a syntax that has commands out of place. SELECT read ... or SELECT key ... it doesnt matter if you put quotes around it or not. MySQL is basically seeing ...
SELECT (SELECT,WHERE,FROM) FROM select,from,where
WHERE SELECT = WHERE & FROM = SELECT. hehehehehehehe
Putting a different kind of quote around this will not change the confusion level you just sent to MySQL.
Mixing my mistake and your mistake together looks like this...
SELECT key,from,to,date FROM my_table WHERE key='1';
// Same as...
SELECT SELECT,SELECT,SELECT,SELECT FROM my_table WHERE SELECT='1';
The first one you can't really tell by looking at it there is anything wrong with it. The second one it is obvious that it is not right and won't work. However, according to MySQL they are the SAME THING.
MySQL receives this syntax as so... SELECT? You told me to SELECT 5 times, never told me what to even select. You get the FROM right, but then you ended with a left hook telling to select something else, not only did you not tell me what to select again but you threw in an NULL='1'; what the heck is that all about?
This is why when you make these kinds of errors the error function doesn't even report what the heck happened. There were so many errors it can't throw you an error number so it just stops.
So this means your syntax is like this
SELECT * FROM Bowlers WHERE SELECT = '1';
Sometimes I get frustrated and say, "I wish MySQL was smarter than this!!!" But then I realize i would have to trade the key words in for a lesser valued database. Each one of those reserved words represents a word that is doing a whole lot more work on the database side for me. When I first started to learn programming I had to write my own text input field sub routines, so I appreciate all the neat things MySQL does for me.

Categories