Using PHP PDO with MYSQL
The following works
$customer = "2";
$ammount = "123.50";
$sql = $db->query("INSERT INTO transactions(transaction_customer,transaction_ammount) VALUES ($customer,$ammount)");
The following does not work
$biggy = "Jim";
$chum = "Tester";
$sql = $db->query("insert into customers(customer_firstname,customer_lastname,customer_telephone) values ($biggy,$chum,'7576632423');");
Any ideas why?
Your first example works because you are working with numbers.
You need quotes around the strings in the 2nd SQL statement
$sql = $db->query("insert into customers(customer_firstname,customer_lastname,customer_telephone) values ('$biggy','$chum','7576632423');");
You can avoid pitfalls like this using PHP's PDO and using prepared statements rather than writing SQL by hand. I highly recommend you look into it :)
Strings need to be quoted.
... values ('$biggy','$chum','7576632423');");
You should be using mysql_real_escape_string too, though.
Related
I am started to learn coding start with HTML, CSS, and php. I created a basic form to test my skill. However, I got stuck with this. Can you help me on that?
I know that it is open to SQL injections, I am just trying to improve myself in coding and will use prepared statements and parameterized queries in real life.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$mysql_host = "";
$mysql_username = "";
$mysql_password = "";
$mysql_database = "";
$conn = new mysqli ($mysql_host, $mysql_username, $mysql_password, $mysql_database);
$c_name = $_POST["club_name"];
$c_league = $_POST["league"];
$c_rank = $_POST["ranking"];
$c_prank = $_POST["previous_rank"];
$sql = "INSERT INTO `club_data` (`club_name`, `league`, `ranking`, `previous_rank`)
VALUES ('$c_name', '$c_league, $c_rank, $c_prank);";
mysqli_query($conn, $sql);
if ($conn->query($sql) === TRUE) {
echo "kayit islendi";
}
else {
echo "Error". $sql ."<br>". $conn->error;
}
$conn->close();
}
?>
Everytime I used the form I got this error.
ErrorINSERT INTO... etc.
You are missing quotes around your insert values, here's the fixed sql:
$sql = "INSERT INTO `club_data` (`club_name`, `league`, `ranking`, `previous_rank`)
VALUES ('$c_name', '$c_league', '$c_rank', '$c_prank');"
You were missing quotes around each value!
HOWEVER, this is an ill advised way of making database queries in production. Either use mysqli_real_escape_string to sanitize your strings(each of your variables will need this treatment) or use prepared statements.
Alternatively, and the way you should always use your DB is via the PDO wrapper. In this case you would use: PDO::quote. PDO offers a unified interface to the most popular databases there are. Here you can read more about PDO: http://php.net/manual/en/book.pdo.php
Coders prefer prepared statements to sanitizing their input. However this incurs extra communication with the mysql server vs writing a bit more code in php. Prepared statements are more involved then normal queries as they are cached on the SQL server and preprocessed waiting for data to be used, also having a miriad of question marks makes the code very hard to read especially if you start working in production and have a miriad of columns to fill. Here you can read more about the prepared statements:
https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html
Main takeaway:
never, EVER, EVER save unsanitized data to the DB!!Use mysqli_real_escape_string or PDO::quote or prepared statements, depending on situation.
use prepared statements for what they have been created for not just as a wholesale sanitizer tool, use them when you have to execute the same query repeatedly. Especially if this query is not an insert in which case I suggest you do mass insert like so:INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9); read more here: https://dev.mysql.com/doc/refman/5.7/en/insert.html This has a caveat in that the maximum size of the sql with inserted values should never be larger then max_allowed_packet config.
You should use prepared statements. Not only does it prevent SQL injection attacks, it also avoids the pesky quoting issues you are currently facing
$sql = "INSERT INTO `club_data` (`club_name`, `league`, `ranking`, `previous_rank`)
VALUES (?, ?, ?, ?);";
$result = $conn->prepare($sql);
$result->bind_param('ssss', $c_name, $c_league, $c_rank, $c_prank);
echo $result->execute() === true ? 'kayit islendi' : 'Error'.$conn->error;
I need some help here!
I have a form on a site admin page, the owner fills in his projects and the get added to a mysql db, but sometimes the data contains single or double quotes so it won't add to the db.
I tried using addslashes but it still wont work.
Heres my code which Ive tried
$atitle = addslashes($_REQUEST['atitle']);
$acontent = addslashes($_REQUEST['acontent']);
$query = "INSERT INTO projects VALUES (NULL, '$atitle', '$acontent', '$remote_file', '$remote_file1', '$remote_file2')";
$result = mysql_query($query);
if(!$result){
$error = 'An error occured: '. mysql_error().'<br />';
$error.= 'Query was: '.$query;
echo $error;
die($message);
}
Can anyone help me with this?
mysql_query is part of an outdated php library that isn't supported anymore. The more reliable method of interacting with a database is mysqli. Using mysqli, you'll be able to use Prepared Statements. Prepared Statements are a way to validate input and to mitigate problems like this (your input having quotation ticks/marks). Take a look at this example:
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("INSERT INTO projects VALUES (NULL, '?', '?', '?', '?','?')");
$stmt->bind_param('s', $atitle); // s means string in the first param
$stmt->bind_param('s', $acontent); // s means string in the first param
... // same for all other parameters in your query
$stmt->execute();
More on this: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
I heavily recommend using mysqli. It is current and supported. Prepared Statements are the best way to defend against SQL injections and also catching trip-ups like this. It will sanitize the input for you and account for quotation symbols.
you can try stripslashes() to un-quotes a quoted string. More details are available on the PHP documentation website here.
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);
}
I'm not sure why this has stumped me. I have the following code
$website = "http://www.google.com";
$name = "Person";
if(!empty($website) {
$name = "[url=$website]$name[/url]";
}
Then i try to insert that into mysql. I tried adding mysql_real_escape_string to both $website and $name (after the if statement), thinking the "/url" might also cause problems.
$name = mysql_real_escape_string($name);
Still no luck though. Any advice? What am I missing? It's giving me this error
"Parse error: syntax error, unexpected '/', expecting T_STRING or T_VARIABLE or T_NUM_STRING"
try
if(!empty($website)) {
$name = "[url={$website}]{$name}[/url]";
}
then use,
mysql_real_escape_string ($name);
This is a PHP syntax problem.
The parser thinks $name[ is the start of a array reference you have to add curly bracelets to tell the parser where the variable name starts and end:
"[url={$website}]{$name}[/url]"
There wont be any problem at all. When reading from database you should then put stripslashes() around your value.
e.g.
$query = "SELECT field FROM table";
$row = mysql_fetch_array(mysql_query($query));
echo(stripslashes($row['field']));
And your output will be the same like YOUR input.
Make sure you're quoting values you send into a query, like so:
$sql = "INSERT INTO table (column) VALUES ('$value')";
Whatever is in $value gets passed into the query. If you leave out the quotes, bad things may happen even if you use mysql_real_escape_string(). Inside strings, forward slashes do not have any special meaning in MySQL, and so mysql_real_escape_string() leaves them intact. This is not a bug, but the documented, correct behaviour. Basically, you need to quote all values in your query.
However, the best solution IMHO is to use PDO and its parametrized queries instead of the mysql_XXX API. It's a bit more complicated (not much though), and it allows you to pass parameters into a query through an associative array, doing all the escaping and quoting you need for you.
Are you putting quotes around the value you want to insert? This will work
INSERT INTO table_name (column_name)
VALUES ('[url=$website]http://www.google.com[/url]')
This will fail
INSERT INTO table_name (column_name)
VALUES ([url=$website]http://www.google.com[/url])
So you might have in you php
$query = "INSERT INTO table_name (column_name) VALUES ('$name')";
// DO MYSQL_QUERY
here my code-
$things = serialize($_POST['things']);
echo $things;
require 'database.php';
$q = "INSERT INTO tblslider(src) values($things)";
mysql_query($q, $link);
if($result)
{
echo "Slider saved successfully.";
}
Output-
a:4:{i:0;s:10:"651603.jpg";i:1;s:11:"7184512.jpg";i:2;s:11:"3659637.jpg";i:3;s:10:"569839.jpg";}v
it means I am getting the record properly but why it it not getting saved in db??
You forgot quotes around $things:
$q = "INSERT INTO tblslider(src) values('" . mysql_real_escape_string($things) . "')";
The mysql_real_escape_string() is really the least you should ever do!
Also as #sanders mentions, you should always output your complete query (via print_r() or var_dump()) as a first step in debugging.
I prefer to build queries like this to enhance readability:
$q = sprintf(
'INSERT INTO tblslider(src) VALUES ("%s")',
mysql_real_escape_string($things)
);
That is, whenever I absolutely have to build and escape them myself. You should really have a look at PDO.
EDIT
Comments in this thread suggests that OP actually wants to insert 651603.jpg,7184512.jpg,3659637.jpg,569839.jpg into the database. In that case implode() could be used (provided that $_POST['things'] only contains items to insert!):
$q = sprintf(
'INSERT INTO tblslider(src) VALUES ("%s")',
mysql_real_escape_string(implode(',', $_POST['things']))
);
Note, that I'm using $_POST['things'] directly here. No serialize(). (I did, however, not realize this erro until just now.)
This question is quite old, but I feel like it's time for a little necromancy. The accepted answer by #jensgram is not wrong, but saying mysql_real_escape_string is the least you could do implies there is a much better solution. Well there is.
PHP Data Objects
PDOs. These bad boys provide an abstraction layer for your database access, so it works with a lot of other databases not just MySQL, and can improve performance when the same query is run many times. Nut this is not why you need them.
Security
Escaping stuff is hard. Either it is obscure how to do it in a specific context or you just forget to do it. The worst thing is that you will not get any errors from forgetting it, and just move on like nothing happened. And you just contributed to the sorry state internet security is in.
With using PDOs properly (e.g. no string concatenation) however will ensure that you will not mess up properly escaping stuff while building DB queries.
You will want to read this: (The only proper) PDO tutorial.
Basically you can prepare an sql statement BEFORE replacing ANY parameters in it. The SQL syntax will be fixed and cannot be broken by bad/no escaping or maliciously forged requests.
So how to do this
At first you need a connection, just like in the regular mysql driver.
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
As you can see there are settings, error modes, fetch modes. It worths reading what each setting does but for now just leave it as it is. At the end of it all, you have the $pdo variable you can use.
$query = "INSERT INTO tblslider(src) VALUES (?)";
$stmt = $pdo->prepare($query);
At this point we got our statement. Nothing came from external sources yet, it is an INSERT statement.
$things = serialize($_POST['things'])
$stmt->execute([ $things ]); //execute
There are other ways to bind the ?-s to parameters, also you can use named parameters too for clarity, but this suffices for now.
That's it: no fancy escaping but no possibility for SQL injection either.
Normally, I will serialize then base64_encode to eliminate surprises and "standardize" the input. For example:
$things = base64_encode(serialize($_POST['things']));
$insert_query = "INSERT INTO...";
Then, when you want to grab it, simply reverse the process.
$query_result = mysql_query("SELECT FROM ...");
$row = mysql_fetch_assoc($query_result);
$retrieved_value = unserialize(base64_decode($row['src']);
You are writing a string to the database, so don't forget to add quotes to your query:
$q = "INSERT INTO tblslider(src) values('$things')";
Also make sure to filter the string to avoid SQL-Injection Attacks.
place an var_dump($q) before mysql_query(...)
You can then examine your query.