update mysql db through form in php - php

I am getting this 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 ' address='xxxxx', city='sssssssss', pincode='333333333', state='Assam', count' at line 1
Thanks in advance.
http://dpaste.com/hold/181959/

your WHERE clause is wrong, you don't write WHERE a=1, b=2, c=3 you want WHERE a=1 AND b=2 AND c=3
additionally your logic is flawed, because your WHERE clause would usually be something more like WHERE id = x (at the moment you're updating a row in a table, where the row data is already the same as that which you're updating it to - if that makes any sense? :) )
furthermore, learn to escape your sql strings properly or you leave yourself vulnerable to sql injection

As well as the problem explained by oedo, you've also got severe SQL injection problems. You need to use mysql_real_escape_string to encode strings for insertion into an SQL statement, not htmlspecialchars. Or use parameterised queries.
htmlspecialchars() is for HTML-encoding text just before you output it into an HTML page. You should not HTML-encode strings for storage in the database.

Firstly, don't you have some kind of unique identifier for your users? Maybe a customer-id of some kind? You could use that to identify the customer in the WHERE clause to make your SQL more clear.
Secondly, do you expect that your user to write all the company EXACTLY like it is in the database? Because that is what you expect from them with your current design.

You need to identify the record by using an ID, not the field values. If you look to a lot of websites, usually they send the ID to identify a record. Like edit.php?id=1284, or view.php?id=1284, etc.
In short you will have a form that you fill up with the values that are in the database for that record ID. If you edit it, you write a edit query like:
$UpdateQuery = "UPDATE customer SET name = '" . $name . "', address = '" . $address . "' ....... WHERE id = " . intval($_GET['id']);
The reason I add intval is because that will only allow numeric values to pass through. As mentoined by bobince, watch out for SQL injections and let mysql_real_escape_string pass through all of your string values you enter in the query too.

Related

Use PHP UPDATE with SET as a variable set to another variable?

Im wondering if something like this is possible?
$joinguild = "UPDATE guild SET '.$rank.'='.$receiver.' WHERE name ='"$dupecheckinfo["guild"]"'";
Im trying to SET '.$rank.'='.$receiver.', but I dont know if I can use a variable where $rank is. Is there a proper way to write this. Is it even possible? If not how would you approach it? Thanks!
Here is my SQL table im working with
Edit: See how my table has Rank1 Rank2 Rank3 etc. Well I am passing the rank value that I want to set so for example
$rank = $_POST["rank"];
$joinguild = "UPDATE guild SET '.$rank.'='.$username.' WHERE name ='"$dupecheckinfo["guild"]"'";
Your question in not clear but you have some problems in your PHP statement. I think you are trying to create your SQL UPDATE query using PHP variables.
Try this:
$joinguild = "UPDATE guild SET $rank='$receiver' WHERE name='" . $dupecheckinfo["guild"] . "'";
Here $rank should have valid column name in your table. Also read about SQL injection.
Your question is quite unclear but to update records from a table you can use this line of code:
$sql=mysqli_query($conn, "UPDATE `table` SET option1='$op1', option2='$op2', option3='$op3', option4='$op4' where id='$id'");
If this is unclear please let me know.
Yes, you can use variables for table and field names in your queries. However, you should avoid it whenever possible, because it generally leads to SQL injection vulnerabilities. Instead of building queries with string concatenation, use prepared statements with bound parameters. See this page and this post for some good examples.
Unfortunately, the bind mechanism works only for values and not for table names or field names, so it's best to try avoiding variable table/field names. If you find that you absolutely must, the best approach would be to ensure that the contents of the variable matches with a pre-set whitelist of allowed table/field names.

PHP: Understand SQL Injection

I'm working on old website and I found this error in log files:
Invalid SQL: SELECT COUNT(*) AS color_count FROM colors WHERE id IN (on,on) ;
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
'on,on) ' at line 1
The code php is like that :
$query = "SELECT COUNT(*) AS color_count FROM colors WHERE id IN ";
$ids = implode("','", $_GET['id_color']);
$query .= "('".$ids."') ";
I resolved this error by adding mysql_real_escape_string.
But I want to understand how an SQL injection can modify the query and remove the simple quotes ' from the query?
SQL injection can only add characters, it cannot remove characters from your SQL string. In other words, it's not "SQL suction". :-)
I can think of these possibilities:
The error in the log occurred on a date in the past, before your code did quoting. Perhaps it was originally designed to handle only integers, which aren't required to be quoted.
I recommend noting the date/time of the error in the log, then retrieve the version of code from your source control corresponding to that date.
The error was generated by a similar SQL query in another part of your code, where the code fails to quote the values.
I recommend searching all of your code for similar SQL queries.
Your code (or your framework) strips single-quotes out of the SQL string. I can't guess why it would do this, but in theory it's a possibility.
SQL injection is a danger (among other cases) anywhere you allow user input to be put directly into the statement. This is why bound statements are more secure and preferred.
The gist of it is, if I can tack on input to the end of your statement, there's nothing to stop me from adding a semicolon to end your current statement, and then a new statement in the same variable. So my string could be:
"11;Drop colors if exists cascade" which a naive execute would execute two statements, one of which completes as you expect, then the malicious one which deletes your table.
Now, a checkbox isn't likely to be a victim of injection, but it should always be a concern.
Do some more research on SQL injection, and really understand it. Then you can start building and modifying code to better combat it.
http://en.wikipedia.org/wiki/SQL_injection
It can be ' or '1'='1 if you want to break single quotes (http://en.wikipedia.org/wiki/SQL_injection).

PHP mysql_real_escape_string is not working as expected

I have a weird problem.
I have a table which has a title field.
I am inserting values into this title field using mysql_real_escape_string. Inserting is working fine for values with single quotes.
Some other place I am doing a select using title filed in the where clause as below
SELECT * FROM table WHERE title=mysql_real_escape_string(Girish's Photo);
This query is returning empty result set even when I inserted Girish's Photo.
---- Editing to put some code
$photo_title=mysql_real_escape_string($_POST[photo_title]);<br/>
$sql = "INSERT INTO photos values($id,'$photo_title');<br/>
using this from a form I have inserted Girish's Photo into photo_title. It worked fine.
...
..
..
Then at some other place in PHP
$title="Girish's Photo";
$sql = "SELECT photo_id,photo_title FROM photos WHERE photo_title ='" . mysql_real_escape_string($title)."'" ;
But this query is returning empty result set.
Using phpMyAdmin, if I try to run the above query .. the result is empty. If I browse the table I see value Girish\'s Photo
Now if I run the query on phpMyAdmin replacing where clause with where photo_title='Girish\''s Photo' I am getting the record.
$data = "Girish's Photo";
$query = "SELECT * FROM table WHERE title='".mysql_real_escape_string($data)."'";
mysql_real_escape_string() is a PHP-function, which should be used as follow:
"SELECT * FROM table WHERE title='".mysql_real_escape_string("Girish's Photo")."'";
However, this is bad practice.
Okay so you're going to want to use PDO for all queries. Primarily for the following reasons:
mysql_* is being deprecated.
It's not safe from SQL Injection.
PDO is capable of accessing numerous database engines making it much more flexible without changing the API.
Please take a look at this post to get a look at how to issue a SELECT using PDO.
Parameterized SELECT queries via PDO?
I had a similar problem recently which I solved by using htmlentites() instead of mysql_real_escape_string() check it out in the manual or w3 schools
EDIT: this is a valid answer because he's using mysql_real_escape_string() in the wrong context in the first place. if you read the question, he's escaping a FILENAME and therefore he's not at risk of injection. If you're going to downvote at least say why..
The value in your database should not contain backslashes. That's why your query doesn't match. Girish's Photo does not match Girish\'s Photo. Sounds like you are a victim of magic quotes. Read the manual and get rid of them.

mysql escape getsqlvaluestring AccID

In various mysql queries, the end part of the query string is:
" WHERE UserID = " . $AccID
where
$AccID = $_SESSION['UID'];
and UserID is the respecting bigint column in the specific table of the db.
So my question is : do I need to escape the $AccID like this GetSQLValueString($AccID, "text") just to be on the safe side, or there is no need to, since it's not taken from a user input ?
p.s. $_SESSION['UID'] is set during the login procedure, after a successful authentication
Yes, you should escape it. You should not database-escape it when you put it into $_SESSION (you might want to use it for other purposes), but before inserting into the query.
Your best bet would be though to use parameterized SQL instead of always escaping and building your queries through string concatenation. Get familiar with PDO. For a better world.

Best Way to Secure SQL Query in PHP

If I am running a query on a MySQL database using PHP as in the following:
$query="SELECT * FROM tablename";
What is the best way to secure this from things like SQL Injections? I've heard about some escape methods, but won't it leave slashes in the query?
The query you have shown in the question doesn't use user supplied values so there is no case of SQL Injection but in a general case:-
Firstly, you must validate all the user input(usernames,emails etc.) before using it in a query. For ex:- If you have allowed only alphanumeric characters in a username, then you must check whether the input is actually alphanumeric or not before proceeding to form a database query and you must also check the size of all the inputs.
After that, in my opinion Prepared Statements is the best choice for preventing SQL injection.
Problem with mysql_real_escape_string():-
As mysql_real_escape_string() escapes characters according to default charset, so it is better than addslashes() function and it properly sanitizes SQL injections arising out of abuse of multibyte character sets, but in another article here, a workaround-scenario is shown that explains that injection can still be done.
Solution:-
So the proper and better way of preventing SQL injection is to use prepared statements. It is a technique in which SQL statements are precompiled before the insertion of the user-input (parameters) and are treated as reusable SQL templates. So, it separates the user input from actual SQL-Code and the SQL-parser never parses the user input.
Apart from security, it also optimizes the SQL query for speed. It helps in cases where you need to run same query multiple times with different user inputs.
You can refer to PHP manual for implementation details.
You shouldn't be doing a select * and should only get the fields you need.
You need to escape text that can be inputted by the user really or using data that is derived from such.
You need to use the mysql_real_escape_string().
first advice, never select *, only select the fields that are necessary, and if all of them are necessary, select individually, so when the project is continued by other developers, they would know whats going on more quicker. secondly, to secure a query use mysql_real_escape_string(); function and if HTML is being passed use htmlentities(); function
SQL Injection can be done, when you make something like this
$query="SELECT * FROM tablename WHERE Name LIKE '" . $_GET["name"] . "'";
Attacker can simply put SQL Injection in get parameter name - eg something like "' OR 1 OR '' = '"
Make sure every get or post parameter is passed thru mysql_real_escape_string or at least addslashes + intval .
$query="SELECT * FROM tablename WHERE Name LIKE '" . mysql_real_escape_string( $_GET["name"] ) . "'";
from your query i see that there is not security issue.
but, lets say that you want to involve a GET parameter in your query.
the worng way
$query="SELECT * FROM tablename WHERE id = ".$_GET['id']
here, you have a chance that some one will change the query.
so what you can do is use mysql_real_escape_string
the right way
$query="SELECT * FROM tablename WHERE id = '".mysql_real_escape_string($_GET['id'])."'";
this way you are protecting the parameter that has being sent by the user.
BUT
you should always verify each parameter coming from the user, and on top of that you secure it by the common way as shown above
I have used this code kindly see is it the right code and not injection able now
As far as I came to know is : injection code can be injected if we run the insert query?
kindly correct me i am not much educated programmer
$rs=mysql_query("Select * from subcat where CATID='".mysql_real_escape_string($_GET['cat'])."' order by ID ASC");
while($row=mysql_fetch_array($rs))
{
echo '<td align="left" style="text-decoration:none;padding-left:1px; ">'.$row['HEADING'].'';
echo '<td align="CENTER" style="text-decoration:none;padding-left:1px">BUY NOW';
echo '<td align="CENTER" style="text-decoration:none;padding-left:50px">Rs.'.$row['PRICE'].'';
echo '<tr><td colspan=5 style="border-bottom:1px #232323 solid;">';
}

Categories