SQL and PHP problems - php

What is wrong with this query?
$query3 = "INSERT INTO Users
('Token','Long','Lat')
VALUES
('".$token."','".$lon1."','".$lat."')";

You have several issues with this.
Column names should be backtick escaped, not quoted (also LONG is a datatype in MySQL hence it's reserved and must be backtick-escaped).
You have SQL injection problems if those arguments aren't escaped.
You should provide us with the result of mysql_error() if it's not working.
Try running this code:
$token = mysql_real_escape_string($token);
$lon1 = mysql_real_escape_string($lon1);
$lat = mysql_real_escape_string($lat);
$query3 = "INSERT INTO `Users` (`Token`, `Long`, `Lat`)
VALUES ('{$token}', '{$lon1}', '{$lat}')";
$result3 = mysql_query($query3) or die("Query Error: " . mysql_error());
If that still doesn't work, give us the error message that's produced.

Long is the mysql reserved word and reserved words needs to be enclosed in backticks
$query3 = "INSERT INTO Users
(`Token`,`Long`,`Lat`)
VALUES
('".$token."','".$lon1."','".$lat."')";

You're using single quotes around your field names. This isn't valid in any SQL variant I know of. Either get rid of them or quote the field names in the correct way for your SQL flavor.
Your code likely has an SQL injection vulnerability, unless you left out the code that escapes $token etc
You shouldn't be putting values into the SQL string like that. This isn't the 1990s - we have parametrized queries now.
The mysql_ functions make it a bit difficult to do queries properly. Switch to either mysqli or PDO.

Related

MYSQL, PHP: Insert records from one database to another

I have a necessity to insert some record from one table1 in database1 to another table2 in database2.
So far I have this..
$records_r = mysqli_fetch_assoc(mysqli_query($conn_r, "SELECT * FROM `export` WHERE ID < 100"));
$columns_r = implode(",",array_keys($records_r));
$values_r = implode(",",array_values($records_r));
$import = mysqli_query($conn_i,"INSERT INTO NOTimport ($columns_r) values ($values_r)");
if (!$import) {
printf("Error: %s\n", mysqli_error($conn_i));
exit();}
It gives me the error:
Error: You have an error in your SQL syntax;
This is how the syntax looks:
INSERT INTO `NOTimport` ('xx,xx,xx,xx,xx,xx,xx,xx') values ('11,'11,E,2079,1931,xx,xx,x')
I am 99% sure that single quotes are causing the error, but why are there?
As per your original post https://stackoverflow.com/revisions/31116693/1 and completely overwriting your original post without marking it as an edit:
You're using the MySQL import reserved word
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
It needs to be wrapped in ticks
INSERT INTO `import` ($columns_r) values ($values_r)
or rename that table to something other than a reserved word.
Plus, $values_r may require to be quoted and depending on what's being passed through $columns_r, you may need to use ticks around that.
I.e.:
INSERT INTO `import` (`$columns_r`) values ('".$values_r."')
Even then, that is open to SQL injection.
So, as per your edit with these values values ('11,'11,E,2079,1931,xx,xx,x'), just quote the values since you have some strings in there. MySQL will differentiate between those values.
Escape your values:
$values_r = implode(",",array_values($records_r));
$values_r = mysqli_real_escape_string($conn_r, $values_r);
or $conn_i I'm getting confused as to which variable is which here. Be consistent if you're using the same db.
Edit:
As stated in comments by chris85, use prepared statements and be done with it.
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
import is a reserved word in MYSQL. So, you need to use backticks (``) around it in your query.
So rewrite as follows:
$import = mysqli_query($conn_i,"INSERT INTO `import` ($columns_r) values ($values_r)");
Without Using PHP you can use MySql Query Which Will Perform Insert Operation As:-
$columns_r='`name`,`class`';
mysqli_query($conn_i,"INSERT INTO `import` ({$columns_r}) select {$columns_r} from `export`");

difference between ' single quote and ` backtick for mysqli_query

This is bizarre, I'm changing some code from mysql to mysqli functions cause of php 5.5+, in these two basic examples, mysql_query had no ' single quote nor ` backtick and worked fine.
$sql = "SELECT * FROM `".$table."`"; // requires: ` ` or fails
$result = mysqli_query($con,$sql);
$sql = "SHOW TABLES LIKE '".$table."'"; // requires: ' ' or fails
$result = mysqli_query($con,$sql);
Can someone explain why?
EDIT: I guess the essence of my question is that: Both functions worked fine without any kind of quotes with mysql_query, and both failed mysqli_query without some kind of quotes. Meaning I will have to fiddle around with half my query's when changing from mysql_ to mysqli_
In your first select statement you are trying to select a table by it's name, hence it will accept the name either with ` or without them, but now with single or double quotes. These should work :
$sql = "SELECT * FROM `table_name`";
$sql = "SELECT * FROM table_name";
In the second case you need to pass in a string to be compared by the like statement hence you need to surround it either with single ' or double " quotes:
$sql = "SHOW TABLES LIKE 'string'";
$sql = "SHOW TABLES LIKE \"string\"";
Edit:
Check out this previous answer on SO as well:
Using backticks around field names
Edit 2:
Since we (me and in comments) suggested that backticks are somehow optional, keep in mind that as a best practise use them whenever you can since although it will allow you to pass most queries without them, some queries using MySql reserved words would break when containing mysql reserved words

Simple PHP/MySQL Syntax error, told to "check manual?"

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 website.
mysql_query("UPDATE Scholarships2 SET Requirements2 = '$requirements2'
WHERE scholarshipID = '$sID'")
or die("Insert Error1: ".mysql_error());
I read other Stackoverflow questions/answers on this subject but cannot find the reserved word I am using.
$sID is just an int while, $requirements2 is
$regex = '/<h4>Requirements<\/h4>([\n\n\n]|.)*?<\/table>/';
preg_match_all($regex,$data,$match);
$requirements2 = $match[0][0];
for the right syntax to use near 's website
This means it's complaining about the bit of your query that is 's website. "Where is that bit in your query?", I hear you ask.
Well, one of those variables in there contains something like Bob's website and the fact that you're blindly injecting that into your query will give you something like:
UPDATE Scholarships2 SET Requirements2 = 'Bob's website' ...
This particular query will not go down well with the SQL parser :-)
Other possibilities that don't immediately choke the parser will also not go down well with your customer base when little Bobby Tables steals or deletes your credit card database.
See this link for a fuller explanation and strategies for avoidance. In your case, that's probably going to involve mysql-real-escape-string.
In other words, you'll need something like:
mysql_query(
"UPDATE Scholarships2 SET Requirements2 = '" .
mysql_real_escape_string($requirements2) .
"' WHERE scholarshipID = '" .
mysql_real_escape_string($sID) .
"'"
) or die("Insert Error1: ".mysql_error());
As an aside, if $sID is just an integer (and not subject to injection attacks), you could probably remove the quotes from around it. I don't think it matters with MySQL (due to its "everything is a string" nature) but your query won't be portable to other DBMS'.
It depends on the values you have in your variables
Depending on the data type here is what you can do
$requirements2 = mysql_real_escape_string($requirements2); // escape string
$sID = (int)$sID; // force integer
the problem is if you have a string in your $requirement and it contains a single quote ' it will break your sql statement.
Here is something i often do to organize my code.
$sql = "UPDATE Scholarships2 SET Requirements2 = '%s'
WHERE scholarshipID =%d";
$sql = sprintf($sql,
mysql_real_escape_string($requirements2),
(int)$sID
);
Are you just taking form fields in from a POST or AJAX query? It sounds like you have a string containing 's website.
Make sure you run your code though mysqli_escape_string.
You need to escape whatever input you are getting in $requirements2
You can do this by
$req2=mysql_real_escape_string($requirements2);
mysql_query("UPDATE Scholarships2 SET Requirements2 = '$req2'
WHERE scholarshipID = '$sID'")
or die("Insert Error1: ".mysql_error());
This will escape any special characters like the apostrophe found in $requirements2
The problem is that your $requirements2 variable contains a single quote (the error message shows it when it says near 's website - presumably you're inserting something like welcome to Sal's website). When MySQL encounters this character, it's interpreting it as the termination of the entire string.
For example, if you substituted the phrase Welcome to Sal's website into your query where $requirements2 currently is, your query would look like this:
UPDATE Scholarships2 SET Requirements2 = 'Welcome to Sal's website'
As you can see, this results in a quoted string Welcome to Sal with the rest of the string hanging off the end not a part of anything. That's the part that the error is complaining about.
You really need to switch to PDO and prepared statements, otherwise you're leaving yourself wide open to these types of errors, including SQL injection which is a Very Bad Thing.
Prepared statements allow you to specify queries with placeholders where dynamic data can be placed. This extra data is then passed to PDO in a separate function where PDO/the database can determine the best way to sanitize it so that it doesn't get misinterpreted as part of the query structure itself.

Sending a slash through mysql

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

PHP syntax for postgresql Mixed-case table names

I have a code below:
<?php
require "institution.php"
/* in this portion, query for database connection is executed, and */
$institution= $_POST['institutionname'];
$sCampID = 'SELECT ins_id FROM institution where ins_name= '$institution' ';
$qcampID = pg_query($sCampID) or die("Error in query: $query." . pg_last_error($connection));
/* this portion outputs the ins_id */
?>
My database before has no mixed-case table names, that's why when I run this query, it shows no error at all. But because I've changed my database for some reasons, and it contains now mixed-case table names, i have to change the code above into this one:
$sCampID = 'SELECT ins_id FROM "Institution" where ins_name= '$institution' ';
where the Institution has to be double quoted. The query returned parse error.
When i removed this portion: where ins_name= '$institution', no error occured.
My question is how do I solve this problem where the table name which contains a mixed-case letter and a value stored in a variable ($institution in this case) will be combined in a single select statement?
Your answers and suggestions will be very much appreciated.
You can use the double quote instead
$sCampID = "SELECT ins_id FROM \"Institution\" where ins_name= '$institution'";
<?php
require "institution.php"
/* in this portion, query for database connection is executed, and */
$institution= pg_escape_string($_POST['institutionname']);
$sQuery = "SELECT ins_id FROM \"Institution\" where ins_name= '$institution'";
$qcampID = pg_query($sQuery)
or trigger_error("Error in query: $sQuery." . pg_last_error($connection));
/* this portion outputs the ins_id */
?>
Note
pg_escape_string as it ought to be used, not to protect from any injections but as just a part of the syntax.
trigger_error which should be used instead of echo (and note proper variable name)
and double quotes or your variable won't be extrapolated ( http://php.net/types.string for ref)
and slashes at double quotes (same ref)
$sCampID = 'SELECT ins_id FROM "Institution" where ins_name= \''.$institution.'\'';
String escaping.
As another commenter posted, read about SQL injection. What I have is not injection safe, consider using something with prepared statements, preferably PDO.
To add to other answers (quote the table name, and use prepared statements to gain security and performance), read about PG and tables case sensitivity. If you have the option, you might consider to change your db schema, so that tables names (and columns and identifiers in general) are all lowercase. That would simplify a little your queries - (but require you to check all your actual quoted queries and unquote them).
What happens if $institution contains the following string: ' or 1 = 1; --
That's what we call an SQL injection attack, and it's a super-easy way for hackers to steal your data -- and get you into big trouble with your customers.
You need to escape that string using pg_escape_string() before putting it into an SQL query. I like to use sprintf() to build my queries:
$sql = sprintf("SELECT ins_id FROM \"Institution\" where ins_name= '%s'", pg_escape_string($conn, $institution));
In the above example, $conn is the connection identifier, created by calling pg_connect().

Categories