Is this MySql Query Statement correct? - php

I would like to know whether this MySql statement will be executed correctly,
"SELECT sum(price) FROM products WHERE productid IN (SELECT productid FROM shoppingcart WHERE sessionid=".$this->$sessionid.")"
And if not please give me pointers as to where I am wrong.
Thanks

I'm sure you meant
$this->sessionid
not
$this->$sessionid
(the second one returns value of property, which name is stored in sessionid, thus, when $sessionid is 'abcdef', it tries to return value of $this->abcdef property).
Also, enclose in ' AND escape all parameters.
"SELECT sum(price) FROM products WHERE productid IN (SELECT productid FROM shoppingcart WHERE sessionid='".mysql_escape_string($this->sessionid)."')";

i am using sql server but i think error over here is
single quote ' is required for session id
"SELECT sum(price) FROM products WHERE productid IN (SELECT productid
FROM shoppingcart WHERE sessionid='".$this->$sessionid."')"

Seems fine to me.

As #praynay said, I believe you need quotes around the session id.
Also, be very, very sure $this->sessionid will not have a quote character in itself, or that you escape it properly before passing it to MySQL. (Or better yet, use a parameterized query.)

Related

update with max value of the column is not working in mysql

I have tried to set the max value for the particular column but that is not working for me. I do not know where i'm going wrong.
UPDATE `upload_video`
SET order_id ='select max(order_id)+1
FROM upload_video'
WHERE `video_id` = 22
This is my query i run the select max(order_id)+1 from upload_video query separately which is giving the result. But if i use this query in update query, the query is executing without error. But the order_id is not updating properly. please help me
Your query is almost correct in standard SQL, you only need to use brackets () instead of apostrophe ':
SET order_id = (SELECT MAX(...) ...)
but MySQL doesn't allow you to update a table while selecting from the same table, a workaround is to use a subquery that calculates the value that you need, and to join your subquery with the table you need to update:
UPDATE
upload_video JOIN (SELECT COALESCE(MAX(order_id),0)+1 max_id
FROM upload_video) s
SET
upload_video.order_id=s.max_id
WHERE
video_id=22
Please see fiddle here.
You have a typo in the statement, you used UPADTE instead of UPDATE.
One problem is, don't quote the subquery. You have used single quotes, which means the expression select max(order_id)+1... was interpreted as a text literal (a varchar). But you clearly don't want that (I guess order_id is a number). What you want instead is to evaluate the subquery. However, if you try:
UPDATE `upload_video`
SET order_id =(select max(order_id)+1
FROM upload_video)
WHERE `video_id` = 22
then MySQL doesn't allow it (I didn't know about that). Other databases such as PostgreSQL allow it. So you might need two statements:
select #id = coalesce(max(order_id), 0) + 1 FROM upload_video;
UPDATE `upload_video` SET order_id = #id WHERE `video_id` = 22;
Please note this works in MySQL but not in other databases.
Try this:
UPDATE `upload_video`
SET order_id =(select COALESCE(max(U2.order_id),0)+1
FROM upload_video U2)
WHERE `video_id` = 22
Peraphs this query goes in error because MySql doesn't want to use the same table in UPDATE and in subquery.
If your case please write two queries.
The first get the maximum value, the second does update

SQL query: Can't order by column called "order"?

I am pulling a column in an existing script into my template files, and everything is working great.
The only problem is, that this script has a column called order, and every row then has a number in that column to show which should be at the top etc. If I set my query to "ORDER BY name" for example, everything works fine, but when I use "ORDER BY order", then I get a SQL error.
Can I not have a column called order? I can't change column name, because it's part of the script.
Is there a way around it?
This is the line in my SQL query:
SELECT * FROM categories WHERE hide = 0 ORDER BY order
order is a keyword in SQL. So if you wish to use a keyword as a name, use backtick characters around it:
SELECT * FROM categories WHERE hide = 0 ORDER BY `order`
Try that :)
If you are working with Postgres just use "column_name", e.g:
SELECT "order" FROM table_name WHERE "order" > 10 ORDER BY "order";
AS orderis a SQL keyword, you should escape it properly as an field identifier by using backticks:
SELECT ... FROM ... ORDER by `order`
Try using backticks:
SELECT * FROM `categories` WHERE `hide` = 0 ORDER BY `order`
ORDER is a reserved word in SQL. You can use a reserved word as a column name but you must surround it in backticks when referencing it. It's good practice to surround all your column names in backticks so you don't run into this issue.
Try using back ticks around the column name, that should do it.
From the manual:
A reserved word can be used as an identifier if you quote it.
So you can use it like this:
SELECT * FROM categories WHERE hide = 0 ORDER BY `order`
Worked for me with brackets. SELECT T.* FROM dbo.test AS T ORDER BY [T].[ORDER]

SQL injection even when the variable is escaped [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 2 years ago.
The sql injection will work only when my query looks like below sample
SELECT * FROM login WHERE id = $my_id_va;
Assume if my query is
SELECT * FROM login WHERE id = $my_id_va ORDER BY id DESC
Than I will get following error
#1064 - 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 by id desc' at line 1
So, this 1 or 1=1; SHOW TABLES will not work, correct?
My site was hacked successively many times.
I want one quick answer: When my query looks like the following one, what ways or which types of query can they use to hack my site?
SELECT * FROM login WHERE id = $my_id_va ORDER BY id DESC
What are the ways to execute the show table in the following query
SELECT * FROM login WHERE id = $my_id_va ORDER BY id DESC
I am also using escaping function to handle the query string values, like mysql_real_escape_string($my_id_va). Yes, obviously this for single related hack, but not sure.
Added some more
SELECT EventActuallyCharged, EventDate FROM tblevent WHERE EventDate between '2011-07-21 or 1=1; SHOW TABLES --' and '2011-07-31' ORDER BY EventDate DESC
but show table not worked
If you are using PHP5, use parametarized query, use PDO.
Int cast
If id is a number, you can int-cast your variable as well. Integers are safe to use:
$x = (int)$yourInputVar;
$s = "select * from Table where id = $x";
mysql_real_escape_string
If you want to pass a string, you can, and should, use mysql_real_escape_string, but this function escapes only those characters that are inside the string. You will still need to add quotes around the string, so:
$x = mysql_real_escape_string('hello');
$s = "select * from Table where id = $x";
.. will result in the query: select * from Table where id = hello. This is obiously not a valid query, since hello should be in quotes.
Change the query to:
$x = mysql_real_escape_string('hello');
$s = "select * from Table where id = '$x'";
.. and everything works fine. You add the quotes around, and mysql_real_escape_string takes care of special characters inside the string, if any.
Parameters
Another solution is to use parameterized queries. This can by done using MySQLi or PDO. The advantage is that you only tell your database where a variable should be inserted, and the database takes care of the escaping yourself.
It also may add a performance benefit, because these queries could be cached without their parameters, make a more efficient use of the query cache. This doesn't really work yet in current versions of MySQL, though.
You are right that 1 or 1=1; SHOW TABLES will give a syntax error but this will work:
1 or 1=1 --
The -- comments out the rest of the query.
In your case the value is an integer so instead of using mysql_real_escape_string you can use intval.
If you set $my_id_va to:
1 or 1=1; SHOW TABLES --
The -- will comment out the rest of the command, effectively terminating it.
I'm not sure what effect mysql_real_escape_string will have on the query. What you should be doing is parameterized queries.
1. First query somehow secured
$sql = sprintf('SELECT * FROM login WHERE id = %d ORDER BY id DESC', mysql_real_escape_string($my_id_va));
2. Second query somehow secured
$sql = sprintf("SELECT EventActuallyCharged, EventDate FROM tblevent WHERE EventDate BETWEEN '%s' AND '%s' ORDER BY EventDate DESC",
mysql_real_escape_string($start_date),
mysql_real_escape_string($end_date));
Read the docs about sprintf if you don't understand it.
However, as others have said, it would be very very secure if you would use parameterized queries with a class such as PDO or MySQLi.

simple mysql select and insert not working

I have no idea why this isn't working. I've taken code from a previous project that works fine. I just want to select specific columns. Here's what im trying...
$result = mysql_query("SELECT when, where, name FROM tablename ORDER BY count DESC LIMIT 0, 20");
//I dont really know how to debug php well, so this is all I have to go by to know if its not working.
if (!$result)
{
echo "<p>Page load has failed please try again</p>";
}
if I select all like this it works fine:
$result = mysql_query("SELECT * FROM tablename ORDER BY count DESC LIMIT 0, 20");
If im doing an insert, that doesn't work either...
$query = "INSERT INTO tablename (when, where, name) VALUES ('$when' , '$where' , '$name');";
mysql_query($query);
I'm sure the spelling is correct i've looked at it several times, and even if I put
echo $row["name"]; and the others ect while using the select all * they appear...
It just seems like its happening when im selecting individual columns.
I have other tables, with other sites using the same exact code and its working fine.
How can i fix this? or at least how can i debug the php to get some better error messages?
edit:
I'm sure the values going in are good, its just simple helloworld string
I've tried including count in the select incase that needed to be there for the sort, but that didnt make it work.
The word where is a reserved word (the WHERE clause of SELECT, UPDATE and DELETE queries). So is when. count is a built-in function name but can be used as an identifier, though you shouldn't.
If you use it as an identifier, you must always enclose it in `backticks` in the query. I recommend not using parts of the query language as column names.
http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html
WHERE, WHEN and COUNT are reserved MySQL words (http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html). Use backticks like this.
$result = mysql_query("SELECT `where`, `when`, name FROM tablename ORDER BY `count` DESC LIMIT 0, 20");
where is a reserved sql word, use tablename.where to select the correct column.

PHP & Mysqli - Multiple querys in one?

I need to get the ID (a column) from the last row inserted, in a table. I'm wondering if there's any way to somehow embed that in another query, to avoid having two different querys? It seems much simpler, and i believe i've seen it somewhere before.
Something like this:
$query = "INSERT INTO a_table (x, y) VALUES ((SELECT id FROM another_table ORDER BY id DESC), 'y...')";
Any ideas how to do that?
Thanks.
If you're looking to get the newest record created by your script, you should never do it this way in the first place. What if another instance of your script created a record at the same time?
mySQL's LAST_INSERT_ID() will return the last ID created over this specific connection. However, you must call it immediately after your insert statement.
If getting the highest ID is literally what you want, GSto's answer will work for you.
INSERT INTO a_table (x, y) VALUES (SELECT max(id), 'y...' FROM another_table);
Yes, MySQL has an INSERT .. SELECT statement:
example:
INSERT INTO a_table (x,y) SELECT id,'y' FROM another_table ORDER BY id DESC
although keep in mind, unless you have an auto_incrementing ID field, the order by clause is pointless here.

Categories