mysqli_query inputs via variable - php

I'm trying to add information to a MySQL table using the following PHP code. (The input the name and text from an HTML5 basic web form.) Probably a syntax issue?
<?php
include "dbinfo.php"; //contains mysqli_connect information (the $mysqli variable)
//inputs
$name = $_GET["name"];
$text = $_GET["text"];
$sqlqr = 'INSERT INTO `ncool`.`coolbits_table` (`name`, `text`, `date`) VALUES ("$name", "$text", CURRENT_TIMESTAMP);'; //the query. I'm pretty sure that the problem is a syntax one, and is here somewhere.
mysqli_query($mysqli,$sqlqr); //function where the magic happens.
?>
No error is thrown. A blank screen results, and a row with "$name" and "$text" is added to the MySQL table.

First of all: you should use mysqli prepared statements to prevent SQL injection attacks. It is not safe to use user input within a query without proper escaping. Prepared statements are useful to prevent this.
Second: you should learn how string quoting works in PHP, single quoted strings and double quoted strings are different
I would recommend to read the PHP documentation about string quoting.

This is how your code should look (with added SQL Injection protection):
<?php
include "dbinfo.php"; //contains mysqli_connect information (the $mysqli variable)
//inputs
$name = mysqli_real_escape_string($_GET['name']);
$text = mysqli_real_escape_string($_GET['text']);
$sqlqr = "INSERT INTO `ncool`.`coolbits_table` (`name`, `text`, `date`) VALUES ('" . $name . "', '" . $text . "', CURRENT_TIMESTAMP);";
mysqli_query($mysqli,$sqlqr); //function where the magic happens.
?>
Take a look at what I've done. Firstly I've escaped the user input you're retrieving into the $name and $text variables (this is pretty much a must for security reasons) and as others have suggested you should preferably be using prepared statements.
The problem is that you weren't surrounding string values with single quotes ('), which is a requirement of the SQL syntax.
I hope this helps to answer your question.

Related

' <--- in mysql text don't get inserted in database

Hello i'm a beginner so please at least try to give me a hint,a example.
English isn't my main language so please endure it.
If somebody type " Hello my name is J'hon ' the text don't insert in database, but if he type 'Hello my name is jhon' it does. I think it is something about '
Ok so i'm having the problem that if someone types
'Hello my name is J[color=#FF0000]'[/color]hon J'onz. ' is not inserted in the database..
This is the script:
mysqli_query($DB_H, "INSERT INTO tickets (name, continutscurt, continut,type,status) VALUES ('".$_SESSION['username']."', '".$_POST['titlu']."', '".$_POST['continut']."', $numar, 0)");
You should really use prepared statements when dealing with any kind of user-input. If you for any weird reason isn't using prepared statements, take a look at the function mysqli::real_escape_string. This will deal with special characters, such as ', which may break the SQL.
With using prepared statements, your code would look like
if ($stmt = $DB_H->prepare("INSERT INTO tickets (`name`, continutscurt, continut, `type`, `status`) VALUES (?, ?, ?, ?, ?)")) {
$stmt->bind_param("ssssi", $_SESSION['username'], $_POST['titlu'], $_POST['continut'], $numar, 0);
$stmt->execute();
$stmt->close();
} else {
echo mysqli_error($DB_H);
}
If you however want to use mysqli::real_escape_string, you'll need to bind the SESSIONs and POSTs to a variable where in you insert instead, like this (you can also do it directly in the query, but this makes for cleaner code).
$username = mysqli_real_escape_string ($DB_H, $_SESSION['username']);
$titlu = mysqli_real_escape_string ($DB_H, $_POST['titlu']);
$continut = mysqli_real_escape_string ($DB_H, $_POST['continut']);
$numar = mysqli_real_escape_string ($DB_H, $numar);
if (!mysqli_query($DB_H, "INSERT INTO tickets (`name`, continutscurt, continut, `type`, `status`) VALUES ('$username', '$titlu', '$continut', '$numar', 0")) {
echo mysqli_error($DB_H);
}
I also put backticks ` around name, status and type, as these are keywords in SQL. This isn't strictly necessary, but it's good practice with words that are listed as either reserved words or keywords, more info on this list of keywords.
You shouldn't take for granted that your queries are successful, so I added an if-block around them. Errors shouldn't be displayed unless in production/development.
References:
http://php.net/manual/en/mysqli.real-escape-string.php
http://php.net/manual/en/mysqli.prepare.php
How can I prevent SQL injection in PHP?
https://dev.mysql.com/doc/refman/5.7/en/keywords.html
The issue is SQL Injection.
You have potentially unsafe values being included within the SQL text.
To see this, break up the code a little bit.
$sql = "INSERT INTO tickets ...'" . $val . "' ... ";
echo $sql;
The echo is there just as a way to see what's going on, for you to examine the contents of the string containing the SQL text. And then take that string over to another client, and test it. And you will see what the the problem is.
... VALUES ( ..., 'J'onz. ', ...
isn't valid. That single quote is ending the string, so the string is just 'J', and the next part, MySQL is going to try to interpret as part of the SQL, not the string value. (This is a nefarious vulnerability. Cleverly constructed strings and wreak havoc on your application and your database.)
One approach to fixing that is to sanitize the values, so they can be safely included.
... VALUES ( ..., 'J\'onz. ', ...
^^
... VALUES ( ..., 'J''onz. ', ...
^^
As a simple demonstration try these queries:
SELECT 'J\'onz. '
SELECT 'J''onz. '
SELECT 'J'onz. '
(The first two will return the string you expect, and the third will cause an error.)
The take away is that potentially unsafe values that are going to included in the text of a SQL statement need to be properly escaped. Fortunately, the MySQL client library includes mysqli_real_escape_string function. Variables that may potentially contain a single quote character can be run through that function, and the return from the function can be included in the SQL text.
$sql = "INSERT INTO tickets ...'"
. mysqli_real_escape_string($DB_H,$val)
. "' ... ";
Again, echo out the $sql and you can see that a single quote has been escaped, either by preceding it with a backslash character, or replacing it with two sinqle quotes.
There's a much better pattern than "escaping" strings. And that's to use prepared statements with bind placeholders.
The SQL text can be a static string:
$sql = 'INSERT INTO mytable (mycol) VALUES ( ? )'
And then you msyqli_prepare the statement.
And then supply values for the placeholders with a call to mysqli_bind_param.
And then call mysqli_execute.
With this pattern, we don't need to mess with running the "escape string" function to sanitize the inputs.

MySQL Query not inserted when PHP variable contains single quotes

This query not inserted when variable $subject has single quotes . Is there any possible solution available ?
mysql_query("INSERT INTO table (to_email_id,subject) values('$to','$subject');");
Consider using Parameterized Queries using PDO for example.
Alternately, enclose your variables in brackets { }.
Edit:
I missed that your variable $subject contains single quotes. This means you have to escape them. (See the myriad of other answers and mysql_real_escape_string() about this.) But as you can see, single quotes inside the variable is exactly how injection attacks work. Escaping them helps prevent such problems as well as allow your query to store the expected data.
No answer about injection attacks is complete without referencing Bobby Tables.
Escape your parameters.
$to = mysql_real_escape_string($to);
$subject = mysql_real_escape_string($subject);
mysql_query("INSERT INTO table (to_email_id, subject) values('$to', '$subject');");
Manual: mysql_real_escape_string()
Also, please read about SQL injection attacks.
Your query will be returning a 1064 error which is a syntax error within your query. This is happening because the variables, specifically $subject in the case of the question is altering the format of your enclosed string. For example, let's say we have
$subject = "fire's hotter than it looks";
When this is evaluated in your query your query string will be
INSERT INTO table (to_email_id,subject)
VALUES('the value of the to variable','fire's hotter than it looks');
If you look at the second item in the values, which was once $subject, you'll notice you now have an uneven number of apostrophes meaning that the end of your query '); is an open string.
As commented above use a function such as mysql_real_escape_string() to add the missing slashes.
Quick note: adding slashes to characters such as " and ' (\", \'). tells mysql to interpret these as string characters instead of query string delimiters.
You need to use mysql_real_escape_string() on your values $to and $subject
Also if you weren't doing this before you are open to sql injection
USE
mysql_real_escape_string
Your query has a great "hole" -> SQL injection. You should read more about this here: http://en.wikipedia.org/wiki/SQL_injection and also here http://php.net/manual/en/function.mysql-real-escape-string.php
To make a short answer you must "escape" values passed to mysql. Best way to do it is with using mysql_real_escape_string function.
$query = sprintf("mysql_query("INSERT INTO table (to_email_id,subject) values('%s', '%s');", mysql_real_escape_string($to),mysql_real_escape_string($subject));
mysql_query($query);
I hope this will help you.
if you are using
(all book's are available) as $subject and you are trying to insert in to mysql
use this
$disc_str = addslashes($subject);
"INSERT INTO table name (subject) value('$disc_str')";
it works for me in Textarea with tinymce also
Solution is very simple. Just add below method before storing your data into php variable
$connection = mysqli_connect($host,$dbuser,$dbpass,$dbname);
$to= mysqli_real_escape_string($connection, $old_email);
$subject= mysqli_real_escape_string($connection, $old_subject)
$query = "INSERT INTO table (to_email_id,subject) values('$to','$subject');";

Mysql + php with special characters like '(Apostrophe) and " (Quotation mark)

I have been struggling with a small problem for a while. It's been there for years but it's just been an irritating problem and not a serious one, and I have just worked around it. But now I want to find out if anyone can help me. I have done some google'ing but no success.
If I do a form post from a html textarea in a php file like this:
<form action="http://action.com" method="post">
<textarea name="text">google's site</textarea>
</form>
and of course there is a submit button and so on.
The value is the problem: google's site The value of the textarea have both "(Quotation mark) and '(Apostrophe).
To save this in a mysql_database I do this:
$result = mysql_query("INSERT INTO `table` (`row1`) VALUES ('".$_POST['text']."') ") or die(mysql_error());
And now I get the mysql error:
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 's site'' at line 1
Your sql string will be:
INSERT INTO `table` (`row1`) VALUES ('google's site')
Which is not a valid statement. As Nanne wrote, escape the string at least with mysql_real_escape_string : http://php.net/manual/en/function.mysql-real-escape-string.php
And read about sql injection
http://en.wikipedia.org/wiki/SQL_injection
Think a bit: if someone posts this: $_POST['text'] with value: ');delete from table;....
Your can say good bye to your data :)
Always filter/escape input!
EDIT: As of PHP 5.5.0 mysql_real_escape_string and the mysql extension are deprecated. Please use mysqli extension and mysqli::escape_string function instead
Always at least use mysql_real_escape_string when adding user-provided values into the Database. You should look into binding parameters or mysqli so your query would become:
INSERT INTO `table` (`row1`) VALUES (?)
And ? would be replaced by the actual value after sanitizing the input.
In your case use:
$result = mysql_query("INSERT INTO `table` (`row1`) VALUES ('".mysql_real_escape_string($_POST['text'])."') ") or die(mysql_error());
Read up on SQL Injection. It's worth doing right ASAP!
Escape the string :D
http://php.net/manual/en/function.mysql-real-escape-string.php
you can use addslashes() function. It Quote string with slashes. so, it will be very useful to you when you are adding any apostrophe in your field.
$result = mysql_query("INSERT INTO `table` (`row1`) VALUES ('".addslashes($_POST['text'])."') ") or die(mysql_error());
instead of using the old mysql* functions, use PDO and write parameterized queries - http://php.net/pdo
I was also Struggling about characters when I was updating data in mysql.
But I finally came to a better answer, Here is:
$lastname = "$_POST["lastname"]"; //lastname is : O'Brian, Bran'storm
And When you are going to update your database, the system will not update it unless you use the MySQL REAL Escape String.
Here:
$lastname = mysql_real_escape_string($_POST["lastname"]); // This Works Always.
Then you query will update certainly.
Example: mysql_query("UPDATE client SET lastname = '$lastname' where clientID = '%"); //This will update your data and provide you with security.
For More Information, please check MYSQL_REAL_ESCAPE_STRING
Hope This Helps
Just use prepared statements and you wouldn't have to worry about escaping or sql injection.
$con = <"Your database connection">;
$input = "What's up?";
$stmt = $con->prepare("insert into `tablename` (`field`)values(?)");
$stmt->bind_param("s",$input);
$stmt->execute();
If you are using php version > 5.5.0 then you have to use like this
$con = new mysqli("localhost", "your_user_name", "your_password", "your_db_name");
if ($con->query("INSERT into myCity (Name) VALUES ('".$con->real_escape_string($city)."')")) {
printf("%d Row inserted.\n", $con->affected_rows);
}

Can I do SQL injection to this code?

I'm still learning about SQL injection, but always the best way for me was using examples, so this is part of my code:
$sql = "INSERT INTO `comments` (`id`, `idpost`, `comment`, `datetime`, `author`, `active`)
VALUES (NULL, '" . addslashes($_POST['idcomment']) . "', '" .
addslashes($_POST['comment']) . "', NOW(), '" .
addslashes($_POST['name']) . "', '1');";
mysql_query($sql);
Knowing that all the POST vars are entered by the user, can you show me how can i make an injection to this script? so i can understand more about this vulnerability. Thanks!
my database server is MySQL.
Don't use addslashes(), always use mysql_real_escape_string(). There are known edge cases where addslashes() is not enough.
If starting something new from scratch, best use a database wrapper that supports prepared statements like PDO or mysqli.
Most of the other answers seem to have missed the point of this question entirely.
That said, based on your example above (and despite your code not following the best practice use of mysql_real_escape_string()) it is beyond my ability to inject anything truly detrimental when you make use of addslashes().
However, if you were to omit it, a user could enter a string into the name field that looks something like:
some name'; DROP TABLE comments; --
The goal is to end the current statement, and then execute your own. -- is a comment and is used to make sure nothing that would normally come after the injected string is processed.
However (again), it is my understanding that MySQL by default automatically closes the DB connection at the end of a single statement's execution. So even if I did get so far as to try and drop a table, MySQL would cause that second statement to fail.
But this isn't the only type of SQL injection, I would suggest reading up some more on the topic. My research turned up this document from dev.mysql.com which is pretty good: http://dev.mysql.com/tech-resources/articles/guide-to-php-security-ch3.pdf
Edit, another thought:
Depending on what happens to the data once it goes to the database, I may not want to inject any SQL at all. I may want to inject some HTML/JavaScript that gets run when you post the data back out to a webpage in a Cross-Site Scripting (XSS) attack. Which is also something to be aware of.
As said before, for strings, use mysql_real_escape_string() instead of addslashes() but for integers, use intval().
/* little code cleanup */
$idcomment = intval($_POST['idcomment']);
$comment = mysql_real_escape_string($_POST['comment']);
$name = mysql_real_escape_string($_POST['name']);
$sql = "INSERT INTO comments (idpost, comment, datetime, author, active)
VALUES ($idcomment, '$comment', NOW(), '$name', 1)";
mysql_query($sql);
Addslashes handles only quotes.
But there are some more important cases here:
Be careful on whether you use double or single quotes when creating the string to be escaped:
$test = 'This is one line\r\nand this is another\r\nand this line has\ta tab';
echo $test;
echo "\r\n\r\n";
echo addslashes($test);
$test = "This is one line\r\nand this is another\r\nand this line has\ta tab";
echo $test;
echo "\r\n\r\n";
echo addslashes($test);
Another one:
In particular, MySQL wants \n, \r and \x1a escaped which addslashes does NOT do. Therefore relying on addslashes is not a good idea at all and may make your code vulnerable to security risks.
And one more:
Be very careful when using addslashes and stripslashes in combination with regular expression that will be stored in a MySQL database. Especially when the regular expression contain escape characters!
To store a regular expression with escape characters in a MySQL database you use addslashes. For example:
$l_reg_exp = addslashes( �[\x00-\x1F]� );
After this the variable $l_reg_exp will contain: [\\x00-\\x1F].
When you store this regular expression in a MySQL database, the regular expression in the database becomes [\x00-\x1F].
When you retrieve the regular expression from the MySQL database and apply the PHP function stripslashes(), the single backslashes will be gone!
The regular expression will become [x00-x1F] and your regular expression might not work!
Remember, that the magic may happen in:
addslashes which may miss something
before adding to database
after retrieving from database
Your example is just an excerpt. The real problem might not be visible here yet.
(based on comments from php.net which are very often more valuable than the manual itself )

Inserting data in oracle database using php

The following code is generating this
Warning: oci_execute() [function.oci-execute]:
ORA-00911: invalid character in F:\wamp\www\SEarch Engine\done.php on line 17
the code is...
<?php
include_once('config.php');
$db = oci_new_connect(ORAUSER,ORAPASS,"localhost/XE");
$url_name=$_POST['textfield'];
$keyword_name=$_POST['textarea'];
$cat_news=$_POST['checkbox'];
$cat_sports=$_POST['checkbox2'];
$anchor_text=$_POST['textfield2'];
$description=$_POST['textarea2'];
$sql1="insert into URL(Url_ID,Url_Name,Anchor_Text,Description)
VALUES( 9,".'{$url_name}'.",".'{$anchor_text}'.",".'{$description}'.")";
$result=oci_parse($db,$sql1);
oci_execute($result);
?>
Never insert user input directly into SQL. Use oci_bind_by_name() to prepare a secure statement. As a side effect, that will also fix the error you're getting (which is a quoting typo). The code would look like
$url_name = $_POST['textfield'];
$anchor_text = $_POST['textfield2'];
$description = $_POST['textfield3'];
$sql = 'INSERT INTO URL(Url_ID,Url_Name,Anchor_Text,Description) '.
'VALUES(9, :url, :anchor, :description)';
$compiled = oci_parse($db, $sql);
oci_bind_by_name($compiled, ':url', $url_name);
oci_bind_by_name($compiled, ':anchor', $anchor_text);
oci_bind_by_name($compiled, ':description', $description);
oci_execute($compiled);
You've got a few problems here. First, variables aren't interpolated into strings enclosed in single quotes. Try this simple script to see what I mean:
$a = 'hi';
print 'Value: $a'; // prints 'Value: $a'
vs.
$a = 'hi';
print "Value: $a"; // prints 'Value: hi'
Secondly, you'll need to escape the variables before using them to construct an SQL query. A single "'" character in any of the POST variables will break your query, giving you an invalid syntax error from Oracle.
Lastly, and perhaps most importantly, I hope this is just example code? You're using unfiltered user input to construct an SQL query which leaves you open to SQL injection attacks. Escaping the variables will at least prevent the worst kind of attacks, but you should still do some validation. Never use 'tainted' data to construct queries.
It's rather hard to say without seeing what the generated SQL looks like, what charset you are posting in and what charset the database is using.
Splicing unfiltered user content into an SQL statement and sending it to the DB is a recipe for disaster. While other DB APIs in PHP have an escape function, IIRC this is not available for Oracle - you should use data binding.
C.
It's because you have un-quoted quote characters in the query string. Try this instead:
$sql1="insert into URL(Url_ID,Url_Name,Anchor_Text,Description)
VALUES( 9,\".'{$url_name}'.\",\".'{$anchor_text}'.\",\".'{$description}'.\")";
You need single quotes around the varchar fields that you are inserting (which I presume are url_name, anchor_text, and description). The single quote that you currently have just make those values a String but in Oracle, varchar fields need to have single quotes around them. Try this:
$sql1="insert into URL(Url_ID,Url_Name,Anchor_Text,Description) VALUES( 9,'".'{$url_name}'."','".'{$anchor_text}'."','".'{$description}'."')";
I don't have PHP anywhere to test it, but that should create the single quotes around your values.
Because really the sql you will eventually be executing on the database would look like this:
insert into URL
(
Url_ID,
Url_Name,
Anchor_Text,
Description
)
VALUES
(
9,
'My Name',
'My Text',
'My Description'
)
The main article Binding Variables in Oracle and PHP appears to be down but here is the Google Cache Version that goes into detail about how to bind variables in PHP. You definitely want to be doing this for 1) performance and 2) security from SQL injection.
Also, my PHP is a bit rusty but looks like you could also do your original query statement like this:
$sql1="insert into URL(Url_ID,Url_Name,Anchor_Text,Description) values ( 9, '$url_name', '$anchor_text', '$description')";
Edit
Also, you need to escape any single quotes that may be present in the data you receive from your form variables. In an Oracle sql string you need to convert single quotes to 2 single quotes to escape them. See the section here titled "How can I insert strings containing quotes?"
If you are still in starting developing, I want to suggest to use AdoDB instead of oci_ functions directly.
Your code above can be rewritten using AdoDB like this:
<?php
include_once('config.php');
$url_name=$_POST['textfield'];
$keyword_name=$_POST['textarea'];
$cat_news=$_POST['checkbox'];
$cat_sports=$_POST['checkbox2'];
$anchor_text=$_POST['textfield2'];
$description=$_POST['textarea2'];
//do db connection
$adodb =& ADONewConnection("oci8://ORAUSER:ORAPASS#127.0.0.1/XE");
if ( ! $adodb )
{
die("Cannot connect to database!");
}
//set mode
$adodb->SetFetchMode(ADODB_FETCH_BOTH);
//data for insert
$tablename = 'URL';
$data['Url_ID'] = 9;
$data['Url_Name'] = $url_name;
$data['Anchor_Text'] = $anchor_text;
$data['Description'] = $description;
$result = $adodb->AutoExecute($tablename, $data, 'INSERT');
if ( ! $result )
{
die($adodb->ErrorMsg());
return FALSE;
}
//reaching this line meaning that insert successful
In my code above, you just need to make an associative array, with the column name as key, and then assign the value for the correct column. Data sanitation is handled by AdoDB automatically, so you not have to do it manually for each column.
AdoDB is multi-database library, so you can change the databas enginge with a minimal code change in your application.

Categories