MySQL query broken - php

Ok its late and I am not catching why this is broken. So here goes.. the error is as follows
syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING
or T_VARIABLE or T_NUM_STRING
typically I would assume its a mising ; ' " or similar, I've checked I have found nothing missing from the surrounding code.
Now despite the possible "injection" factors which I don't care about currently someone please tell me whats wrong with this one line.
mysql_query("INSERT INTO files_posted (ID, when, email, randomkey, count, fileID) VALUES (NULL, $when, $email, $fakeHash, '0', mysql_real_escape_string($_POST['fileID']))") or die(mysql_error());

Besides using a quoted subscript on an embedded (interpolated) variable, you are likely missing some quotes (around values) in the query.
Try this:
mysql_query("INSERT INTO files_posted (ID, when, email, randomkey, count, fileID) VALUES (NULL, '".mysql_real_escape_string($when)."', '".mysql_real_escape_string($email)."', '".mysql_real_escape_string($fakeHash)."', '0', '".mysql_real_escape_string($_POST['fileID'])."')") or die(mysql_error());
If the $_POST['fileID'] is always expected to be an integer, then it does not need to be wrapped in a mysql_real_escape_string call and it would actually be safer (against SQL injection) and possibly more efficient to just cast it to an int:
mysql_query("INSERT INTO files_posted (ID, when, email, randomkey, count, fileID) VALUES (NULL, '".mysql_real_escape_string($when)."', '".mysql_real_escape_string($email)."', '".mysql_real_escape_string($fakeHash)."', '0', ".((int)$_POST['fileID']).')') or die(mysql_error());

One of your variables contains an apostrophe:
$when, $email, $fakeHash
That's my guess. You should use mysql_real_escape_string() for all of those.

Make sure you enclose all text field values in (single or double) quotes (and make sure they are escaped). The quotes are required to make sure MySQL treats the text as strings and not as something else.
Alternatively, use PDO, and you don't have to worry about that.

Related

Inputting an apostrophe in my search box throws up an error [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
I have a perplexing issue that I can't seem to comprehend...
I have two SQL statements:
The first enters information from a form into the database.
The second takes data from the database entered above, sends an email, and then logs the details of the transaction
The problem is that it appears that a single quote is triggering a MySQL error on the second entry only! The first instance works without issue, but the second instance triggers the mysql_error().
Does the data from a form get handled differently from the data captured in a form?
Query 1 - This works without issue (and without escaping the single quote)
$result = mysql_query("INSERT INTO job_log
(order_id, supplier_id, category_id, service_id, qty_ordered, customer_id, user_id, salesperson_ref, booking_ref, booking_name, address, suburb, postcode, state_id, region_id, email, phone, phone2, mobile, delivery_date, stock_taken, special_instructions, cost_price, cost_price_gst, sell_price, sell_price_gst, ext_sell_price, retail_customer, created, modified, log_status_id)
VALUES
('$order_id', '$supplier_id', '$category_id', '{$value['id']}', '{$value['qty']}', '$customer_id', '$user_id', '$salesperson_ref', '$booking_ref', '$booking_name', '$address', '$suburb', '$postcode', '$state_id', '$region_id', '$email', '$phone', '$phone2', '$mobile', STR_TO_DATE('$delivery_date', '%d/%m/%Y'), '$stock_taken', '$special_instructions', '$cost_price', '$cost_price_gst', '$sell_price', '$sell_price_gst', '$ext_sell_price', '$retail_customer', '".date('Y-m-d H:i:s', time())."', '".date('Y-m-d H:i:s', time())."', '1')");
Query 2 - This fails when entering a name with a single quote (for example, O'Brien)
$query = mysql_query("INSERT INTO message_log
(order_id, timestamp, message_type, email_from, supplier_id, primary_contact, secondary_contact, subject, message_content, status)
VALUES
('$order_id', '".date('Y-m-d H:i:s', time())."', '$email', '$from', '$row->supplier_id', '$row->primary_email' ,'$row->secondary_email', '$subject', '$message_content', '1')");
You should be escaping each of these strings (in both snippets) with mysql_real_escape_string().
http://us3.php.net/mysql-real-escape-string
The reason your two queries are behaving differently is likely because you have magic_quotes_gpc turned on (which you should know is a bad idea). This means that strings gathered from $_GET, $_POST and $_COOKIES are escaped for you (i.e., "O'Brien" -> "O\'Brien").
Once you store the data, and subsequently retrieve it again, the string you get back from the database will not be automatically escaped for you. You'll get back "O'Brien". So, you will need to pass it through mysql_real_escape_string().
For anyone finding this solution in 2015 and moving forward...
The mysql_real_escape_string() function is deprecated as of PHP 5.5.0.
See: php.net
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_real_escape_string()
PDO::quote()
You should do something like this to help you debug
$sql = "insert into blah values ('$myVar')";
echo $sql;
You will probably find that the single quote is escaped with a backslash in the working query. This might have been done automatically by PHP via the magic_quotes_gpc setting, or maybe you did it yourself in some other part of the code (addslashes and stripslashes might be functions to look for).
See Magic Quotes
You have a couple of things fighting in your strings.
lack of correct MySQL quoting (mysql_real_escape_string())
potential automatic 'magic quote' -- check your gpc_magic_quotes setting
embedded string variables, which means you have to know how PHP correctly finds variables
It's also possible that the single-quoted value is not present in the parameters to the first query. Your example is a proper name, after all, and only the second query seems to be dealing with names.
You can do the following which escapes both PHP and MySQL.
<?
$text = '';
?>
This will reflect MySQL as
How does it work?
We know that both PHP and MySQL apostrophes can be escaped with backslash and then apostrophe.
\'
Because we are using PHP to insert into MySQL, we need PHP to still write the backslash to MySQL so it too can escape it.
So we use the PHP escape character of backslash-backslash together with backslash-apostrophe to achieve this.
\\\'
You should just pass the variable (or data) inside "mysql_real_escape_string(trim($val))"
where $val is the data which is troubling you.
I had the same problem and I solved it like this:
$text = str_replace("'", "\'", $YourContent);
There is probably a better way to do this, but it worked for me and it should work for you too.
mysql_real_escape_string() or str_replace() function will help you to solve your problem.
http://phptutorial.co.in/php-echo-print/

Relation *tablename* does not exist

Recently I'm getting an error message that I don't know how to deal with. It's very vague.
The PostgreSQL statement I use is:
$result = pg_query($ruledbconnection, "INSERT INTO INPUT(num, pkts, bytes ,
target,prot, opt, \"in\", out, source, destination, id)
VALUES('$num','$bytes','$pkts','$target', '$opt', '$protocol', '$in', '$out',
'$source', '$destination', '$id')");
All seems fine, right? However, when I execute this query with variables:
ERROR: syntax error at or near "'INPUT'" LINE 1: INSERT INTO 'INPUT'(num, pkts, bytes ,
target, prot, opt, "i... ^
I've been stuck on this for a while and it might be due escaping in PHP, or maybe something else?
The table that I want to manipulate is called INPUT in my database..
The SQL you showed doesn't match the error. The SQL doesn't have quotes around the table name, the error does.
ERROR: syntax error at or near "'INPUT'" LINE 1: INSERT INTO 'INPUT'(num, pkts, bytes ,
So. Single quotes (apostrophes, ') are for SQL values, not identifiers. Identifiers are quoted with double quotes ("). So you'd write:
INSERT INTO "INPUT" (...) VALUES (...)
Note that quoting the table name will preserve case. So if you double quote it here, you must double quote it everywhere you refer to it from. You will save your sanity if you instead just use lower case:
INSERT INTO input (...) VALUES (...)
and even better, a descriptive table name:
INSERT INTO packets_received (...) VALUES (...)
Your syntax error is the least of your problems, though. Let me introduce you to a classic:
Your query follows the pattern:
pg_query($conn, 'INSERT INTO sometable (col) VALUES ($user_input)')
and thus, is a classic example of an SQL injection vulnerability.
Read:
Bobby Tables
PHP manual on SQL injection
Solved by making sure that I escape the quotes around my table name.
"INSERT INTO INPUT (num, pkts, bytes , target, prot, opt, \"in\", out, source, destination, id)
Should be:
"INSERT INTO \"INPUT\" (num, pkts, bytes , target, prot, opt, \"in\", out, source, destination, id)

basic query statement fails to execute

$query="INSERT INTO ".$table_name." VALUES ('$rowNum','$something',$_SERVER['REQUEST_TIME'], $_SERVER['REQUEST_TIME'], '$somethingelse')";
The error produced is
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in line 15
I have a problem with that query but I don't know where the mistakes are. Anyone sees the light please shed it on me. Thank you for your spot.
EDIT:
The query to create my table is
$query="CREATE TABLE ".$table_name." (id int not null auto_increment, something varchar(128), post_date varchar(32), edit_date varchar(32), somethingelse text)";
I find this syntax easier to manage and debug for anything but the most basic of parameter replacement into strings:
$query = sprintf("INSERT INTO %s VALUES ('%s', '%s', '%s', '%s', '%s');", $table_name,
$rowNum, $something, $_SERVER['REQUEST_TIME'], $_SERVER['REQUEST_TIME'],
$somethingelse)
N.B. You can also use printf in place of sprintf with the same structure to output the same string just like a print or echo statement.
A couple of other suggestions too:
Use PDO to simplify and abstract the database operations as well as making it easier to secure all of the statements with bound parameters in prepared statements.
Instead of using $_SERVER['REQUEST_TIME'] perhaps some default 'now()' date fields and triggers for mod_dates on the database would be more reliable and maintainable. (although I don't have full context to know whether you are explicitly inserting the server time for another reason which can't be handled by timestamping handled by the DB)
Have you tried
$query="INSERT INTO ".$table_name." VALUES ('$rowNum','$something',".$_SERVER['REQUEST_TIME'].",". $_SERVER['REQUEST_TIME']", '$somethingelse')";
EDIT - the problem was with $_SERVER['REQUEST_TIME'] which doesn't get interpreted by php as $sometext and so you have to concatenate it
Try:
$query="INSERT INTO ".$table_name." VALUES ('$rowNum','$something','".$_SERVER['REQUEST_TIME']."','". $_SERVER['REQUEST_TIME']."', '$somethingelse')";
Array values are should not be in single or double quotes.

Can't figure out what's wrong with my php/sql statement

So this is probably a dumb beginner question, but I've been looking at it and can't figure it out. A bit of background: just practicing making a web app, a form on page 1 takes in some values from the user, posts them to the next page which contains the code to connect to the DB and populate the relevant tables.
I establish the DB connection successfully, here's the code that contains the query:
$conn->query("SET NAMES 'utf9'");
$query_str = "INSERT INTO 'qa'.'users' ('id', 'user_name','password' ,'email' ,'dob' ,'sx') VALUES (NULL, $username, $password, $email, $dob, $sx);";
$result = #$conn->query($query_str);
Here's the error that is returned:Insert query failed: 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 ''qa'.'users' ('id', 'user_name' ,'password' ,'email' ,'dob' ,'s' at line 1
Thanks in advance!
Unless it's changed since I did MySQL in PHP, escape your db/column/table names with backticks (`), not apostrophes (').
A good general trouble-shooting technique is to make the query work via another interface to the database. For example, phpMyAdmin. If it works there, you have some confidence going forward. or you may find how to fix your SQL. (phpMyAdmin is handy because it will convert your SQL into a ready-made string for PHP.)
You need to escape your column names with a backtick (`) instead of (')
You also need to properly escape the actual values you are inserting as well (use a single quote)
OMG not a single right answer
$query_str = "
INSERT INTO `qa`.`users` (`id`, `user_name`,`password` ,`email` ,`dob` ,`sx`)
VALUES (NULL, '$username', '$password', '$email', '$dob', '$sx')";
identifiers being quoted with backticks, while strings being quoted with apostrophes!
and I hope you have passed all your variables through mysql_real_escape string BEFORE putting it into query, i.e.:
$username = mysql_real_escape string($username);
and so on

mystery mysql error

I'm by no means experienced in mysql and keep getting an error in this lines of code:
$sql= "INSERT INTO songs (unique_show_id, artist, date, year, city, state, venue, taper, transfered_by, source, mic_loc, lineage, uploaded_by, uploaded_on, show_notes, show_xml)
VALUES('$showId', '$artist', '$showDate', '$year, '$city', '$state', '$venue', '$taper', '$transferer', '$source', '$mic_loc', '$lineage', '$uploader', NOW(), '$show_notes', '$show_xml')";
//check to see if the query went through
if (!mysql_query($sql,$con)){
echo "query fail";
die('Error: ' . mysql_error());
}
I'm sure it's something simplistic, but I can't see where the error is. The error message I get is:
query failError: 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 'ipuhgbi', 'CA', '', '', '', '', '', '', 'danwoods', NOW(), '', '<show id=\'gm198' at line 2
Some of the values I'm inserting are NULL, but from what I've read I don't think that should be a problem. Any ideas?
Missing quote after $year.
When MySQL issues such an error (near bla di bla), the error is usually immediately before the string it mentions. In this case 'ipuhgbi' maps to $city, so you know it's right before '$city', and what do we see there? Voila, a missing quote.
You need to use mysql_real_escape_string() in each and every single one of your $variables.
Also, read this StackOverflow question carefully regarding SQL Injections.
It looks like the last single quote on the error line is not escaped.
you need to remember to sanitize all of the strings going into the query.
There are quite few things you need to be sure about:
You don't insert primary keys through queries (eg unique_show_id in your code)
For numbers you don't use single quotes.
It is better to use the set variant of inserting records which avoids count problems eg:
Use intval for numbers and mysql_real_escaps_string for strings to avoid injections issues as well as single quotes query erros.
insert into table set field='field_value', field2='field_value' // and so on

Categories