ODBC prepared statements in PHP - php

I'm trying to use odbc_prepare and odbc_execute in PHP as follows:
$pstmt=odbc_prepare($odb_con,"select * from configured where param_name='?'");
$res=odbc_execute($pstmt,array('version'));
var_dump($res); //bool(true)
$row = odbc_fetch_array($pstmt);
var_dump($row); //bool(false)
The first var_dump returns true so the execute succeeds, but there is no row returned. A row does indeed exist with the param_name = 'version'. Why is no row returned?
To make things interesting, I ran another very simple example in php using a prepared insert.
$pstmt=odbc_prepare($odb_con,"insert into tmp1 values(?,'?')");
This line, by itself, inserted a row into the database!! Surely this is just wrong? The data entered was col 1 = blank, col 2 = ?
Any advice on where to start fixing this would be appreciated, thanks.
Edit: This is in PHP 5.2.8

Try removing the single quotes from the query string and adding them to the parameter value itself:
$pstmt=odbc_prepare($odb_con,"select * from configured where param_name=?");
$res=odbc_execute($pstmt,array(" 'version'"));
var_dump($res); //bool(true)
$row = odbc_fetch_array($pstmt);
var_dump($row); //bool(false)
The single space character at the beginning of the parameter value is very important--if the space is not there, it will treat the variable as a path to a file.
From http://www.php.net/manual/en/function.odbc-execute.php:
If you wish to store a string which
actually begins and ends with single
quotes, you must add a space or other
non-single-quote character to the
beginning or end of the parameter,
which will prevent the parameter from
being taken as a file name.

when I read this paragraph
Any parameters in parameter_array which start and end with single quotes will be taken as the name of a file to read and send to the database server as the data for the appropriate placeholder.
If you wish to store a string which actually begins and ends with single quotes, you must add a space or other non-single-quote character to the beginning or end of the parameter, which will prevent the parameter from being taken as a file name. If this is not an option, then you must use another mechanism to store the string, such as executing the query directly with odbc_exec()).
It seems to me that it isn't necessary to add single quotes ' to a string, only if you really want to have the quotes as text in the DB
Therefore if I only want to insert the text, without the single quotes I would write something like that ...
see this example from odbc-prepare
http://www.php.net/manual/en/function.odbc-prepare.php
Use this example for IBM DB/2:
$q = "update TABLE set PASS=? where NAME=?";
$res = odbc_prepare ($con, $q);
$a = "secret"; $b="user";
$exc = odbc_execute($res, array($a, $b));
This would result in the following statement
$pstmt=odbc_prepare($odb_con,"select * from configured where param_name=?");
$name = "version";
$params = array($name);
$res=odbc_execute($pstmt,$params);
var_dump($res); //bool(true)
$row = odbc_fetch_array($pstmt);
var_dump($row); //bool(false)
See that I not only removed the qoutes for the value in the params array but also removed the qoutes in the SQL statement.
please give feedback if this was right

You should not enclose variables in quotes in a prepared statement:
$pstmt=odbc_prepare($odb_con,"select * from configured where param_name=?");
$res=odbc_execute($pstmt,array(" 'version'"));
should be:
$pstmt=odbc_prepare($odb_con,"select * from configured where param_name=?");
$res=odbc_execute($pstmt,array("version"));
Question marks represent parameter placeholders, the value passed is meant to represent an unescaped, unenclosed value, which will be properly escaped by the SQL interpreter.

EDIT:
Gah, ignore me, misread php.net
odbc_fetch_array accepts as it's parameter the result of odbc_execute, you seem to be passing in the prepared statement.

What DBMS are you using? The fact that the lone insert prepare statement seems to be executed against the database rather than being prepared points to either a poor implementation of php (unlikely) or the DBMS not supporting prepared sql. If the latter is the case it is possible that their way of supporting the command with out the functionality is just to execute the statement leading to the results you get. If the DBMS does support prepared statements and the php implementation handles it properly there is some kind of issue with the insert being executed which also needs some investigation.

Did you try using double quotes? i.e.
$res=odbc_execute($pstmt,array("version"));

Related

PHP & MySql query with apostrophes

I have the following php version:
PHP Version 5.3.2-1ubuntu4.19
and this php string:
$l_sDesc = "It doesn' t contain any dangerous substances";
If i try to make a query with db_query (Drupal) i get an error due to the apostrophe;
db_query("UPDATE mytable SET description= '$l_sDesc' where id = $id");
I've tried to use mysql_real_escape_string() but i get an empty string:
$l_sDesc = mysql_real_escape_string($l_sDesc); //i have an empty string as result
What's the problem?
Drupal use another DB Wrapper. Normally you can create prepared statements.
https://api.drupal.org/api/drupal/includes!database!database.inc/group/database/7
Here is a correct example. If you use the correct prepared statements your input will be filtered.
Otherwise use stripslashes().
http://php.net/manual/de/function.stripslashes.php
Tom, you need to "prepare" the string for SQL before you actually run the statement.
Try the PHP function mysql_real_escape_string on your strings before you actually use them.
http://php.net/manual/en/function.mysql-real-escape-string.php
I suggest to use $l_sDesc = htmlspecialchars($l_sDesc);

How Mysqli_escape_string or Prepared statement can save me from SQL Injection

I was reading lots of forums and answers on Stack over flow regarding SQL-Injection
and i came to know this is very basic level of SQL-injection
$_POST['name'] = 'xyz;DROP Table users';
mysqli_query ('select * from abc where name='."$_POST['name']")
To prevent this
Use mysqli_escape_stirng on any input that comes from user can save me from SQl-injection
Use PDO and prepare statement can also save me from SQL-injection
Q1. What i want to know here how passing data to Mysqli_escape_string can save me from SQL-Injection
$safe_variable = mysqli_escape_String($connection ,$_POST['name'];
How mysqli_escape_string will only save "XYZ" from POST data and leave the rest of the part (if that is the case)
Q2. How PDO will save me from SQL-Injection
$stmt = $dbh->prepare("select * from ABC where name = :name");
$stmt->bindParam(':name',$name);
$name = $_POST['name'];
$stmt->execute();
Any help in this regard his highly appreciated
The problem with incorporating user input into SQL is that in the resulting SQL you can’t tell which parts were provided by the developer and which by the user. That’s why the developer must ensure that user input gets interpreted as intended.
This is where string escaping functions and parameterization come in:
String escaping functions like mysqli_real_escape_string process the value so that it can be securely used in a string literal without fearing it may be interpreted as anything else than string data.
However, it is important to note that the value is actually placed in a string literal and nowhere else as it’s only intended for that specific purpose, i. e., it ensures that the passed data is interpreted as string data only when placed inside a string literal. Unfortunately, the PHP manual fails to mention the string literal part.
Parameterization as implemented by prepared statements separate the SQL and the data parameters. So there can’t be a confusion of SQL code and provided data. With server-side prepared statements first the statement gets prepared having only parameter placeholders and then the parameter values get passed for execution. And whenever a parameter is encountered, the DBMS uses the corresponding parameter value.
As for your specific example:
What i want to know here how passing data to Mysqli_escape_string can save me from SQL-Injection
$safe_variable = mysqli_escape_String($connection ,$_POST['name'];
How mysqli_escape_string will only save "XYZ" from POST data and leave the rest of the part (if that is the case)
It doesn’t because you didn’t put the value in a string literal. However, the following would work:
mysqli_query("select * from abc where name='$safe_variable'")
How PDO will save me from SQL-Injection
$stmt = $dbh->prepare("select * from ABC where name = :name");
$stmt->bindParam(':name',$name);
$name = $_POST['name'];
$stmt->execute();
As already said, you explicitly state what the SQL looks like by preparing the statement. And then you pass the parameters for execution. As the parameterized SQL and its parameters are separated, they won’t mix and a passed parameter value can’t be mistaken as SQL.
Q1:
mysql(i)_real_escape_string() calls MySQL's library function
mysql(i)_real_escape_string, which prepends backslashes to the following
characters: \x00, \n, \r, \, ', " and \x1a.
(http://php.net/mysqli_real_escape_string)
Note that this depends on the character encoding (not workin in this case is SET NAMES ... (security risk!!!), $mysqli->set_charset('utf8'); should be used!). (You can read about encoding in my post Mastering UTF-8 encoding in PHP and MySQL.)
How does it prevent SQL injection?
- Well it prevents breaking the variables context by escaping ' etc, the thing is, that mysql_query and mysqli_query only execute one query per query, that means, it simply ignores ;DROP Table users.
mysqli_real_escape_string DOES NOT prevent inserting code like DROP DATABASE.
Only PDO and/or mysqli_multi_query are vulnerable in this case.
Q2:
The statement is sent to the server first, then the bound variables will get sent seperated and then the statement gets executed, in this case, the security is provided by the database library, not by the client library. You should prefere this.
That means, you first send $dbh->prepare("select * from ABC where name = :name"); to the server and the database knows your bind param will be inserted into the :name placeholder and it will automatically wrap it properly to not break out of its supposed context. The database will try to look for a name value of xyz;DROP Table users and it won't executed any command, just fill that variable space.
I think this is the case for most SQL escaping functions:
They escape the control chars like ;, ', ", ...
So your string
xyz;DROP Table users
Will be escaped by the functions to
xyz\;DROP Table users
So your string now isn't a valid SQL command anymore.
But be aware of HTML tags in the data stored in a DB.
If I insert for example
<script>alert('foobar');</script>
This will be stored in DB and not treated by the SQL escape functions. If you print out the field somewhere again, the JS will be executed by the visitors browser.
So use in addtion htmlspecialchars() or htmlentities() for sanitize user input. This is also true for prepared statements.

Querying NON-escaped strings in MySQL

The table has company names which are not escaped.
My qry looks like
$sql = "SELECT id FROM contact_supplier WHERE name = '$addy' LIMIT 1";
The problem comes in where the company name values in the table are sometimes things like "Acme Int'l S/L".
(FYI: values of the $addy match the DB)
Clearly, the values were not escaped when stored.
How do I find my matches?
[EDIT]
Ahah!
I think I'm we're on to something.
The source of the $addy value is a file
$addresses = file('files/addresses.csv');
I then do a
foreach ($addresses as $addy) {}
Well, when I escape the $addy string, it's escaping the new line chars and including "\r\n" to the end of the comparison string.
Unless someone suggests a more graceful way, I guess I'll prob strip those with a str_replace().
:)
[\EDIT]
Why do you think the data already stored in the table should be escaped?
You should escape data only right before it is written directly into a text-based language, e.g. as a part of an SQL query, or into an HTML page, or in a JavaScript code block.
When the query is executed, there's nothing espaced. MySQL transforms it and inserts, otherwise it wouldn't insert and gives error because of syntax or we escape them for security like sql injection.
So your query with escaped values will be working fine with the data in your database.
If the values were not escaped when stored then they would have caused SQL errors when you tried to enter them.
The problem is that the data is not being escaped when you make the query.
Quick hack: Use mysql_real_escape_string
Proper solution: Don't build SQL by mashing together strings. Use prepared statements and parameterized queries
Another option would be to change your query to this...
$sql = "SELECT id FROM contact_supplier WHERE name = \"$addy\" LIMIT 1";
Use mysql_real_escape_string:
$addy = mysql_real_escape_string($addy);
Or try using parameterized queries (PDO).
Regarding this statement:
Clearly, the values were not escaped when stored.
This is incorrect logic. If the values weren't escaped in the original INSERT statement, the statement would have failed. Without escaping you'd get an error along the lines of syntax error near "l S/L' LIMIT 1". The fact that the data is correctly stored in the database proves that whoever inserted it managed to do it correctly (either by escaping or by using parameterized queries).
If you are doing things correctly then the data should not stored in the database in the escaped form.
The issue turned out to be new-line characters
The source of the $addy value starts out like this
$addresses = file('files/addresses.csv');
I then goes through
foreach ($addresses as $addy) {}
When I escape the $addy string, it's escaping the new line chars and inserting "\r\n" on the end of the comparison string.
As soon as I dropped those chars with string_replace() after escaping, everything went swimmingly
Thanks-a-BUNCH for the help

Php/SQL/DB2 special characters in where clause

I am trying to SQL a DB2 database (on an iSeries) using PHP and "DB2_exec"- not mysql.
I have these characters in my WHERE clause (variable $EncSSN) which cause the SQL statement to stop: ðIn*Éæng “"Ò×ÑRÈ•`
The SQL is constructed as:
select EENUM, EESSN
from EEMAST
where EESSN = '$EncSSN'
The field in the table EESSN contains encrypted values.
- I get no errors and no log entries. The html renders a blank page.
- I have tried replacing (str_replace) quotes, single quotes, period, etc with escape character '\'
- I can't use mysql_real_escape_string because I am loading the db2_connect resource.
If I change the SQL statement above's where to select a value from a different field, my html is rendered properly.
Can you think of anyway I can accomplish this?
Steven
Prepare the SQL and set the parameter for where clause using the array approach. Never ever attempt to build SQL queries by string functions.
try the addslashes() function http://php.net/manual/en/function.addslashes.php
or heredoc or nowdoc syntax
http://php.net/manual/en/language.types.string.php
you could also put the sql in a stored proc, but you may have the same issues for the parameter value and need to try one of the above.

Problems with mysql insert

My php script won't work if i try to insert into database something in Saxon genitive (for example value "mike's" won't be inserted).
PHP code is plain and simple:
"INSERT INTO cache (id,name,LinkID,number,TChecked) VALUES(".$idUser.",'".$LinkName."',".$LinkID.",".$number.",NOW());"
Everything works great until "$LinkaName" get some value with "special character". How to put values like "mike's", "won't" etc. into MySql database?
You need to escape these strings properly. In addition, the technique that you're using right now exposes you to an SQL injection attack.
The PHP docs for mysql_real_escape_string gives a good example of what you should do:
// Query
$query = sprintf("INSERT INTO cache (id,name,LinkID,number,TChecked) VALUES(%d,'%s',%d,%d,'%s');",
mysql_real_escape_string($idUser),
mysql_real_escape_string($LinkName),
mysql_real_escape_string($LinkID),
mysql_real_escape_string($number),
mysql_real_escape_string(NOW()));
You must escape them first, otherwise you generate an invalid query. The single quote matches the single quote at the start of the string.
$LinkName = mysql_real_escape_string($LinkName);
You can also use prepared statements to bind parameters to the query instead of concatenating and sending a string (use the PDO or mysqli libraries instead of the mysql lib).
You need to use mysql_real_escape_string() on those values.
Also make sure if you are not quoting those other variables, to cast them to integer (the only reason why you wouldn't quote them).
If you're using mysqli or PDO and not the standard extension, you can use a prepared statement instead of escaping.

Categories