Can you tell me what's wrong with this update statement? Not updating my db record in mysql
$updateid = $row[id];
$result2 = mysql_query("UPDATE grades SET processed = 1
where 'id' = '$updateid'") or die(mysql_error());
ColumnNames (as well as TableName) shouldn't be enclosed with single quotes because they are identifiers and not string literals. Wrapping an identifier with single quotes makes it string literals.
UPDATE grades
SET processed = 1
where id = '$updateid'
If you are unsure if the columnName (or TableName) you are using is a reserved keyword, delimit it with backticks and not with single quotes. eg,
UPDATE `grades`
SET `processed` = 1
where `id` = '$updateid'
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
When to use single quotes, double quotes, and backticks in MySQL
You are quoting your column name. If you want to do that (it's not necessary here), you should use backticks:
$result2 = mysql_query("UPDATE grades SET processed = 1
where `id` = '$updateid'") or die(mysql_error());
Apart from that you should make sure that your variable is safe to use in an sql query, preferably using PDO (or mysqli) and prepared statements. If you really want to use the deprecated mysql_* functions, you should use mysql_real_escape_string().
Related
We know that single quotes in PHP is faster than double quotes so $foo = 'lorem ipsum'; is faster than $foo = "lorem ipsum";.
But what about in Mysql query? Does single quotes or double quotes affect the execution speed?
Consider the following different syntaxes. Which one is the fastest one? Or is there yet another syntax which is even faster?
mysqli_query($conn, 'SELECT * FROM `mytable` WHERE `full_name` = "' . $full_name. '"');
mysqli_query($conn, "SELECT * FROM `mytable` WHERE `full_name` = '" . $full_name. "'");
mysqli_query($conn, "SELECT * FROM `mytable` WHERE `full_name` = '$full_name'");
mysqli_query($conn, "SELECT * FROM `mytable` WHERE `full_name` = '{$full_name}'");
== Edit ==
I understand that the structure of database and other factors can also affect the execution speed. But let's assume that we already have a well-structured database and exclude other factors.
You are asking about MySQL when MySQL is not involved.
mysqli_query() takes two parameters, a connection to the DB and a query to execute.
The query is a simple string, that you can build however you want.
What you really asking is "what is the fastest way to construct my query string", which is explained in Speed difference in using inline strings vs concatenation in php5? (short answer: concatenation using single quotes).
Another way to construct your query is using prepared statements, which will be slower for a single query (you need to call two functions), but a lot faster when repeating the same query with different parameters.
Regarding the use of quotes within MySQL itself:
SELECT * FROM aTable WHERE a = 'blah';
vs
SELECT * FROM aTable WHERE a = "blah";
It also has been answered in SO previously, take a look at When to use single quotes, double quotes, and backticks in MySQL (short answer regarding single/double, makes no difference, single quotes is the standard)
SQL Query performance is not dependent on quotation. Double quotes generally is not used in SQL, But quotes can vary from database to database.
SQL Query performance depends on various cases -
Example :
Table size
Joins
Indexing
Aggregations etc
Note : But for huge number of rows, Using double quotation (") takes milliseconds differences.
Execute your Query String to phpMyadmin like -
SELECT * FROM YourTable WHERE title ='SOME TITLE';
SELECT * FROM YourTable WHERE title ="SOME TITLE"; #This Query will take some Milliseconds difference for huge number of rows in Different Database
$tablename = "channel";
mysql_query("INSERT INTO '".$tablename."' (episode_name,episode_title,episode_date)
values ('$videoname','$videotitle','$date')");
In PHP a double quoted string literal will expand scalar variables. So that can be done like this
$sql = "INSERT INTO $tablename (episode_name,episode_title,episode_date)
values ('$videoname','$videotitle','$date')";
I assume you thought that the single quotes were requred around the table name, they are not in fact they are syntactically incorrect.
You may wrap the table name and the columns names in backtick like this
$sql = "INSERT INTO `$tablename` (`episode_name`,`episode_title`,`episode_date`)
values ('$videoname','$videotitle','$date')";
The reason that the Values(....) are wrapped in single quotes is to tell MYSQL that these are text values, so that is not only legal syntax but required syntax if the columns are defined as TEXT/CHAR/VARCHAR datatypes
However I must warn you that
the mysql_ database extension, it
is deprecated (gone for ever in PHP7) Specially if you are just learning PHP, spend your energies learning the PDO database extensions.
Start here its really pretty easy
And
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared statement and parameterized statements
Dont use quotes arround table name or use backtick
mysql_query("INSERT INTO $tablename (episode_name,episode_title,episode_date)
values ('$videoname','$videotitle','$date')");
"INSERT INTO `$tablename` (episode_name,episode_title,episode_date) values ('$videoname','$videotitle','$date')";
OR
"INSERT INTO `".$tablename."` (episode_name,episode_title,episode_date) values ('$videoname','$videotitle','$date')";
Why should we escape double quotes,single quotes creating queries in PHP? are there any particular benefits when doing that? or it is just a good practice?
It is required to make your queries work and secure. Consider the following code:
$name = "O'reilly";
$sql = "INSERT INTO users (name) VALUES ('$name')";
The result SQL would become like this:
INSERT INTO users (name) VALUES('O'reilly');
Which simply doesn't work. It needs to be properly escaped:
INSERT INTO users (name) VALUES('O\'reilly');
The same applies for other special chars.
Prevent SQL injection
Consider this query:
DELETE FROM users WHERE username='$username';
Where $username is obtained from $_POST. If an attacker managed to post string like ' OR 1; -- as the $username then the query becoming this:
DELETE FROM users WHERE username='' OR 1; -- ';
which is valid and the WHERE always evaluates to true and you will have to give good explanation to your angry users.
See also: Best way to prevent SQL Injection in PHP
If you do not escape quotes, The query ends at the place of single quotes. So your query will not be executed successfully!
E.g.
$qry = "SELECT * FROM user WHERE email='test#test.com'";
It works fine but if any one enters email='test'#test.com' then query ends at 'test' only and not find any rows with that one.
So it prevents also a sql injection!
s, to prevent from SQL injection attacks.
To know SQL injection
http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php
http://www.homeandlearn.co.uk/php/php13p5.html
To prevent PHP Sql injection
https://stackoverflow.com/a/60496/781181
I'm trying to wrap my head around writing queries in SQL and I'm having some difficulty understanding this example that I've found.
$q = "INSERT INTO `dbUsers` (`username`,`password`,`email`) "
."VALUES ('".$_POST["username"]."', "
."PASSWORD('".$_POST["password"]."'), "
."'".$_POST["email"]."')";
I guess I'm stumbling over the use of double quotes, single quotes, and the back-ticks. I compared this statement to the example on the W3 website and am just really confused as it seems much more complicated. Could you please explain to me what is going on in the above query? Thank you for your help!
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
The double quotes are used to define the elements that build your $q string. The single quotes identify strings within the SQL query that you are building and the backticks are used to escape object names in MySQL.
The double quotes surround the strings that will be a part of the query string. The dots between each double-quoted section are the concatenation operator. They are joining individual string pieces together.
You'll notice that there is a double-quote and dot before every $_POST[] array variable, and a dot and double-quote after.
e.g. " . $_POST["username"] . "
The first double quote ends the previous string section. The one at the end starts the next string section. Everything between the two dots is the POST variable. The reason the dots are necessary is because of the quotes around "username". In your W3 version they did not use quotes around the $_POST[] array key string (e.g. $_POST[firstname] and not $_POST["firstname"] or $_POST['firstname']) and so they did not need to use dots and quotes.
If you want to keep things simple, don't use the quotes inside of the $_POST[] variables and you won't have to use all those dots and quotes around them.
If you try version 1 without the dots and quotes the php parser will fail and you will see an error.
Backticks ` are to escape MySQL keywords (usually used for table and column names). Single or double quotes are required around any strings which are inserted.
Note that you should call mysql_real_escape_string on any string you're concatenating into a SQL query. Otherwise, it's possible to break out of quotes if $_POST also includes quotes. This can potentially be used to allow the execution of arbitrary SQL commands in what is known as a SQL injection attack.
The `back ticks` are optionally used to quote mysql field names, you will need them if you accidentally use one of mysqls reserved words to name a field - otherwise you don't need them.
When you enter a string into a field you have to 'quote it'.
The whole statement has to be quoted, but not clash with 2) above, hence the use of "double quotes".
Non scalar values such as arrays do not automatically expand, so you have to "drop out" . and . "back in" to PHP to build your string using concatenation sign a dot .
The backticks are a MySQL artifact in case you are using reserved words as your table/field names, and the single quotes delineate string literals in SQL. The double quotes are PHP-specific and separate strings in PHP. So, your query below would look like the following:
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('".$_POST["firstname"]."','".$_POST["lastname"]."','".$_POST["age"]."')";
One thing that the author above is doing is also breaking the PHP string into separate strings, probably to improve readability. MySQL server doesn't care about that.
There's actually a lot of unnecessary stuff in that first query. There are best practices to take into account but it could be re-written as such:
$q = "INSERT INTO dbUsers (username, password, email)
VALUES ('".$_POST["username"]."',
PASSWORD('".$_POST["password"]."'),
'".$_POST["email"]."')";
First thing: INSERT INTO dbUsers:
All this is doing is telling us what table we're inserting our data into.
(username, password, email)
Specifying the columns we're inserting into (order specific)
VALUES ('".$_POST["username"]."', PASSWORD('".$_POST["password"]."'), '".$_POST["email"]."')
Our values to be inserted (dependent on the order of the columns), then a terminating semicolon.
If you re-write this with hard coded values rather than concatenation, it would look like:
VALUES ('myUserName', PASSWORD('myPassword'), 'myEmail')
All of that should be self explanitory. Each value is contained within single quotes (') as they are strings. Then the password value is passed through the MySQL function PASSWORD which hashed the password for security purposes.
The double quotes are part of the PHP code, telling it that the items inside the double quotes are strings. They're not part of the SQL being built.
The single quotes are used to surround values in the resulting SQL. Ie, you're telling the database the value "bob" is used here. For some types of value (integers, boolean, etc) you don't need the single quotes. For many others (varchar, dates, etc), you need the single quotes.
The backticks perform much the same function as single quotes, except they're used around table names, field names, etc... rather than around actual values. They're used when the name in question wouldn't be interpreted by the database correctly there, for example if you had a field named count, since that's a keyword in SQL. As noted elsewhere, the backticks aren't necessary in your example, but many people put them in all the time because it doesn't hurt to have them; as a safety net, kindof.
To give a visible, simpler example
$name = "bob";
$sql = "SELECT * FROM `mytable` WHERE `name` = '" . $name . "'";
This would result in the $sql variable being
SELECT * FROM `mytable` WHERE `name` = 'bob'
As you can see, the double quotes are not part of the string.. they're just used in creating it. In the resulting SQL, the backticks surround the table/field names, and the single quotes surround the actual value bob.
As a complete side note, using the POST values directly in created SQL is dangerous as it allows for SQL injection attacks. The values should be escaped or a parametrized query should be used.
Can someone explain what is the difference between using mysql_real_escape_string on a string or wrapping `` around the column.
For example "insert into table (``column``) values ('$string')"
or
$escapestring = mysql_real_escape_string($string);
"insert into table (column) values ('$escapedstring')"
What is the difference between these two and what should I use? Thanks.
There's a difference between the backtick ` and the single quote '.
The backtick is intended to escape table and field names that may conflict with MySQL reserved words. If I had a field named date and a query like SELECT date FROM mytable I'd need to escape the use of date so that when MySQL parses the query, it will interpret my use of date as a field rather than the datatype date.
The single quote ' is intended for literal values, as in SELECT * FROM mytable WHERE somefield='somevalue'. If somevalue itself contains single quotes, then they need to be escaped to prevent premature closing of the quote literal.
Those two aren't related at all (as far I know anyway)
From the manual : http://php.net/manual/en/function.mysql-real-escape-string.php
Escapes special characters in the
unescaped_string, taking into account
the current character set of the
connection so that it is safe to place
it in a mysql_query().
So essentially what it does is, it will escape characters that are unsafe to go into mysql queries (that might break or malform the query)
So o'reily will become o\'reily