$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')";
Related
I am trying to insert a data from a form which has about 1990 characters into mysql. How ever the insert is not working. when i var_damp the content of the variable is shows the correct content. When i set it to an empty string the insert works. I have done my research and still can't get ti to work. I am not trying to upload a file. This characters are from a textarea in my form.
Below is the insert code:
if (isset($_POST['val'])) {
$score = $_POST['val'];
$course = $_POST['course'];
$mysqli->query("INSERT INTO `evaluate` (`id`, `course`, `score`) VALUES (Null, '$course', '$score')");
Note: is score column has type TEXT in the database.
This is a common problem because most introductions to mysqli don't cover it right away even when it should be the first thing you learn. Inserting into any database, especially SQL, requires carefully escaping the values you're supplying. The way these are escaped varies depending on the platform, but the good news is that mysqli can handle it for you.
The key is using prepared statements:
$stmt = $mysqli->prepare("INSERT INTO evaluate (course, score) VALUES (?,?)");
$stmt->bind_param('ss', $_POST['course'], $_POST['val']);
$stmt->execute();
Now it's best to enable exceptions so that any errors are not ignored. Once in a while we all make little mistakes that can be a giant pain to track down if there isn't any warning about them. Exceptions make a lot of noise.
If you're just getting started with PHP and databases, you might want to evaluate using PDO which is significantly better than mysqli for a number of reasons, or a higher level database layer like Doctrine or
Propel which make using the database a lot more pleasant.
I have a single quote (') in the text and not escaping it meant that the SQL statement was been interpreted wrongly
The correct way to go, and you must always do this, is:
$score = $mysqli->real_escape_string($_POST['val']);
$course = $mysqli->real_escape_string($_POST['course']);
$mysqli->query("INSERT INTOevaluate(id,course,score)VALUES (Null, '$course', '$score')");
I'm trying to insert form values into the tables and column spots in SQL queries, in hopes of PHP passing it's value to MySQL.
like this:
$sql= "SELECT * FROM '{$table}' WHERE '{$catagory}' = '{$value}'";
So is there a way I can do something like this without getting a syntax error?
First of all, let me make my disclaimer that you should never use raw input data from a form to determine databases, tables, or columns in your queries. It's bad news. Create some sort of mapping that does not expose your database schema to end users and restricts the values to only what you want and cannot be changed by developer tools in the browser or a bot trying to hack your site.
If you want to do it with mysql you will need to do to escape the form data with mysqli_real_escape_string to prevent SQL injection. I use sprintf to make it cleaner but it's not required.
$sql = sprintf(
"SELECT * FROM `%s` WHERE `%s` ='%s'",
mysqli_real_escape_string($table),
mysqli_real_escape_string($column),
mysqli_real_escape_string($value)
);
Please note the backticks (`) around the table and column names. There are not apostrophes a.k.a. single quotes ('). It's the proper way to encapsulate databases, tables, and columns in MySQL queries. It will help prevent issues with special characters in the names.
Yes, just like this...
$sql= "SELECT * FROM $table WHERE $category ='$value'";
Just make sure the whole string is within double quotes " "
I do this all the time, but I use prepared statements...you should as well
Did you try like this
$sql= "SELECT * FROM $table WHERE $catagory = '$value'";
or if you trying to select from form input fields you can try like this
$sql= "SELECT * FROM $_POST[table] WHERE $_POST[category] = '$_POST[value]'";
just please be aware that this second example is not secure way to inserting input fields values into query since someone can SQL inject your query, so you know.
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().
I have a query that looks at a list of files inside a folder and enters the names of everything into a database so I can control the sort when showing the images.
Now I had an image today which had a name of image123('2).jpg. The single quote caused my query from crashing so how can I get around this? To make things simpler I have made example scenario
I have list of 4 variables which have the following strings
$myVAR1 -- "MyName IS Leo";
$myVAR2 -- "MyName IS 'Tiger";
I am running a SQL query to enter them into a database
$sql = "INSERT INTO `names` (`StringID`, `StringValue`) VALUES (NULL, ' $myVAR1');";
$sql2 = "INSERT INTO `names` (`StringID`, `StringValue`) VALUES (NULL, ' $myVAR2');";
So how can I detect that the single quote is inside the string $myVar2 and how can I ignore it when entrying into the database?
You need to escape your data. Use prepared queries with PDO so you don't have to worry about this.
You are currently wide open to SQL injection.
At a minimum, use mysql_real_escape_string(), assuming you are using the standard MySQL library in PHP. It takes care of quotes, among many other things, escaping them properly so they will be inserted into your database.
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.