Binding PHP variables to ODBC SQL UPDATE statement - php

I am trying to bind parameters to an UPDATE statement using ODBC in PHP but the SQL statement is failing and I cannot for the life of me work out why. I've tried Googling but there seems to be very little info regarding using ODBC with PHP as opposed to the likes of MySQLi and PDO.
Most examples I've found with parameter binding use a SELECT statement but as far as I can tell that shouldn't make a difference. The closest answer I've found was here on stackoverflow. As far as I can see they are doing what I'm doing but I keep getting an error. Here is my code:
$updQuery = "UPDATE Demographic SET dmg_FirstName=? WHERE dmg_ID=?";
$update = odbc_prepare($connect, $updQuery);
$fname = $_POST['firstname'];
$pID = 145100007;
$updResult = odbc_execute($update, array($fname, $pID)) or die (odbc_errormsg());
Here's the error I keep getting on the above code:
Warning: odbc_execute(): SQL error: [Microsoft][ODBC Driver Manager] SQL data type out of range, SQL state S1004 in SQLBindParameter in C:\xampp\htdocs\work\ajaxdd.php on line 44
The code works when I remove the parameter binding so if worst comes to the worst I can try to sanitise the data as best I can but that's obviously not preferable.

This probably means that you're trying to insert an ID that is higher than that integer column allows. Try verifying if this is the case first. What is the type of dmg_ID? 145100007 is a rather high number so I suspect this might be the culprit.

Related

Error accessing MySQL database with PHP object (nested queries)

I want to get some data from a Sphinx server and pass it to MySQL to execute some queries. I'm new to PHP so probably I'm missing something here. I've looked for similar questions but can't find anything so maybe you can help me.
The error is in the first while. I'm pretty sure it's due to the $rown variable but don't know the reason. (I've verified that I can retrieve data from the connections so it is passing the data where the error lies - could be the sql syntax of the query but that seems fine).
Edited the code thanks to the comments below, now I get the error: Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given in C:\Apache24\htdocs\test3.php on line 20. This is because the query failed, I still suspect it is because $rown.
$sphinxcon = mysqli_connect...
$mysqlcon = mysqli_connect...
$query = "SELECT names FROM iproducts LIMIT 0,1000";
$raw_results= mysqli_query($sphinxcon, $query);
//Until here works ok, now I want to pass $raw_results to MySQL
while ($row = mysqli_fetch_object($raw_results)) {
$rown = $row->names;
$mquery = "SELECT text FROM claims WHERE EXISTS ($rown) LIMIT 0,1000";
$mysqlresults = mysqli_query($mysqlcon, $mquery);
while ($final = mysqli_fetch_object($mysqlresults)) //this is line 20
{
printf ("%s<br />", $final->text);
}
}
Thanks :)
Well $row contains an object, so would have to use it as such, maybe
$rown = (string)$row->names;
... assuming you want the variable to contain the 'names' attribute you just SELECTed from Sphinx index.
As for the mysql EXISTS(), no idea what you really doing here, seems confused. How you structured it currently suggests that 'names' attribute in sphinx contains a complete SELECT query, that mysql could execute for the exists condition. That seems unlikely.
Guessing you meaning to more normal query something like
$mquery = "SELECT text FROM claims WHERE text LIKE '%$rown%' LIMIT 0,1000";
But that is subject to SQL injection, particully if names might contain single quotes. SO should escape it. Perhaps
$rown = mysqli_real_escape_string($mysqlcon, $row->names);
But might be worth reading up on prepared queries.
btw, the 'Error' you getting, is because you creating an invalid query and not dealing with it. So $mysqlresults is FALSE.
$mysqlresults = mysqli_query($mysqlcon, $mquery) or die("Mysql Error: ".mysqli_error($link)."\n");

PHP escape SQL Query algorithm

I'm currently working with PHP 5.4.x and SQL Server 7 and I'm having TONS of issues with the PDO object for the ODBC Driver (Which is the only one that works on Sql Server 7), Statements throw errors everywhere ....
I finally got it working using PDO::query() method, BUT I need to escape the Input .... And PDO::quote IS NOT WORKING, I red the Documentation on php pdo docs about PDO and it says that PDO::quote is Not well implemented on PDO_ODBC, which might explain why im getting errors.
For Example: this
$escapedString = $pdoObject->quote($myQueryString);
returns False, it does not return the escaped string.
That been said,
Do you know a good way to escape input to prevent SQL INJECTION???
PS: Due to driver issues (old tech) I CANNOT Trust in SQL Statements, so is not an option.
Any ideas??
EDIT:
For Example. This does not work
getQueryFromFile is only retrieving a query from a file.
and SqlServerPdo is just a wrapper class I wrote over the PHP PDO so I get the connection as a Singleton
For the Record, the query actually WORKS, it has been tested on the Sql Server Engine
$conn = SqlServerPdo::connect();
$query = SqlServerPdo::getQueryFromFile('STUDENTS_FIND');
$statement = $conn->prepare($query);
$statement->bindParam(':id', $id, PDO::PARAM_INT);}
$statement->execute();
This throws the error:
text is incompatible with int (SQLExecute[206] at ext\pdo_odbc\odbc_stmt.c:133)
It seems as if the statement is treating the :id param as a text, not as an INT.
bindValue returns the same error

PHP mssql_query warnings that still run the script

So, I am doing a bunch of things parsing an XML from 1 server, writing stuff into another server and then updating the mssql db! The whole process appeared to run smoothly until I ran the script from the terminal for the sake of FUN!
When I run it from the terminal, it throws in a bunch of warnings like:
PHP Warning: mssql_query(): message: Incorrect syntax near 's'. (severity 15) in
/Volumes/Data/Users/username/Desktop/createXML.php on line 375
PHP Warning: mssql_query(): General SQL Server error: Check messages from the SQL
Server (severity 15) in /Volumes/Data/Users/username/Desktop/createXML.php on line 375
PHP Warning: mssql_query(): message: Unclosed quotation mark after the character
string ';'. (severity 15) in /Volumes/Data/Users/username/Desktop/createXML.php on line 375
PHP Warning: mssql_query(): General SQL Server error: Check messages from the SQL
Server (severity 15) in /Volumes/Data/Users/pdwivedi/Desktop/createXML.php on line 375
PHP Warning: mssql_query(): Query failed in /Volumes/Data/Users/username/Desktop
/createXML.php on line 375
Here is line 375:
$query = mssql_query("UPDATE table_name SET C_ITP_STATUS = '".$ITP_Status."',
C_ITP_ERRORS = '". $ITP_Error ."' WHERE id = '".$ID."';");
The funny thing is that the query executes and I have an updated DB. But, it still shows these warnings when run from terminal. And I WANT TO get rid of them!
I MUST user MS SQL!!
Have tried looking around for solutions, but people hardly use MS SQL with mySQL being so much better (at least in terms of being widely used). Any help?
FUNNY THING: When I ONLY connect to the DB and perform this query in a new php script, it works fine and there are no warnings. Not sure why its like this!
RESOLVED:
I didnt care to test my input parameters (pretty lame) in to the string BECAUSE I was super confident about what I was doing! ALWAYS ESCAPE SPECIAL CHARS no matter how confident you are (just shouting out loud)!!
It sounds to me like one of your input strings might contain a quote, and this is messing up the query. Your errors also indicate this. You should always treat all possible user input as tainted, and make it a habit to sanitize them every time, even if you don't think you need to.
I created a new php script and hard coded the 3 parameters and the query runs fine!
This also leads me to believe that there is a quote or special character somewhere in your variables that is messing up the query. You would want to use mysql_real_escape_string() to correct this.
$ITP_Status = mysql_real_escape_string($ITP_Status);
$ITP_Error = mysql_real_escape_string($ITP_Error);
$ID = mysql_real_escape_string($ID);
$query = mssql_query("UPDATE table_name SET C_ITP_STATUS = '".$ITP_Status."', C_ITP_ERRORS = '". $ITP_Error ."' WHERE id = '".$ID."';");
It should also be noted that you are using the old MySQL functions. The new MySQLi functions are the replacement, and what you should be using at a bare minimum.
You mention MS SQL. If you plan on using that, you cannot use the MySQLi functions. In that case it is recommended that you use the PDO interface, which will work for both MySQL and MS SQL. Many recommend PDO over MySQLi even if you are only using MySQL.

I have a SQL Syntax error on my php page

Here is the mysql insert the I am running in php. I have removed the part giving the error but then I get a error on the next piece. I am not seeing what is diffrent to cause the error.
$fields="adv_exchange SET synum='".$synum."', worknum='".$_POST['worknum']."', user_id='".$current_user->ID."', f_name='".$current_user->user_firstname."', l_name='".$current_user->user_lastname."', email='".$current_user->user_email."', regnum=".$_POST['regnum'].", item='".$item."', qsver='".$_POST['qsver']."', flashrom='".$_POST['flashrom']."',expansion='".$_POST['board']."', rdisplay='". $_POST['rdisplay']."', screen_model='".$_POST['screen_model']."', p_hardware='".$_POST['cable']."', pcolor='".$_POST['pcolor']."', pname='".$_POST['pname']."', kboard='".$_POST['kboard']."', ip='".$_POST['ip']."', reg_name='".$_POST['reg_name']."', mem=".$_POST['mem'].", dt_server='".$_POST['dt_server']."', alert='".$_POST['alert']."', ows='".$_POST['ows']."', w_date='".$_POST['w_date']."', flashromver='".$_POST['flashromver']."', s_size='".$_POST['s_size']."', mag='".$_POST['mag']."', rcard='".$_POST['rcard']."', kvsid=".$_POST['kvsid'].", finger='".$_POST['finger']."', stand_alone='".$_POST['stand_alone']."', standards='".$_POST['standards']."', profile='".$_POST['profile']."', man_date='".$_POST['man_date']."', l_sn='".$_POST['l_sn']."', misc='".$_POST['misc']."', problem='".$_POST['problem']."'";
then $query = "insert into $fields";
I receive back
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 ' item='JS900CV', qsver='', flashrom='',expansion='', rdisplay='', screen_model='' at line 1
Blockquote
if I echo the $query I get this:
insert into adv_exchange SET synum='SY5135', worknum='123456', user_id='2', f_name='REMOVED', l_name='REMOVED', email='REMOVED', regnum=, item='JS900CV', qsver='', flashrom='',expansion='', rdisplay='', screen_model='', p_hardware='', pcolor='', pname='', kboard='', ip='192.168.1.16', reg_name='', mem=, dt_server='', alert='', ows='', w_date='', flashromver='', s_size='', mag='', rcard='', kvsid=3, finger='', stand_alone='', standards='', profile='', man_date='', l_sn='', misc='misc test\r\n', problem='gen test'
Depending on what I enter in the error is changing spots in my statement. Not all fields are used the form is dynamic that is supplying the data so the fields are dependent on what options are selected. On a side note in case of concern about using $_POST to insert directly into mysql, I sanitize the array first. Any help would be greatly appreciated.
Look at regnum=,. You don't provide a value for regnum. Either leave it out entirely or set it to an appropriate value.
You're using a very, very bad approach to MySQL databases: manually creating the queries. You should really use prepared statements instead: this issue will be resolved as well.
Don't use mysql_* functions, use PDO instead.
Your code would look like this (simplified):
// This holds the query
$statement = $pdo->prepare('INSERT INTO adv_exchange SET synum=?, worknum=?, etc=?, problem=?');
// This executes it with the given arguments. It's 100% injection-proof and safe. In fact, it's also faster.
$statement->execute(array($synum, $_POST['worknum'], $_POST['therest'], $_POST['problem']));
regnum=".$_POST['regnum']." is causing the problem. When it is undefined, you get regnum=, in the SQL query
A bigger concern is that you are not escaping your inputs. Either use mysql_real_escape_string around them, or better, use prepared statements.
You need to SET regnum=SOMETHING.
Currently it's empty.

Vulnerability with MySQL error

I have no idea about PHP security, but if I add an ' to the input in my POST method form.
I'm getting the following message:
Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in /usr/local/www/login.php
Is that a SQL injection? If so, how it can be abused by the "hackers" ?
That means you're vulnerable to SQL injection, and your code is not doing sufficient checking for errors.
An absolute barebones "safe" bit of code would be:
<?php
... connect to db ...
$stringval = mysql_real_escape_string($_GET['param']);
$sql = "SELECT somefield FROM sometable WHERE otherfield='$stringval'";
$result = mysql_query($sql) or die(mysql_error());
better yet is to stop using the mysql functions and switch to PDO and parameterized queries. They handle the injection problems for you automatically.
The root cause of your error message is that your query has caused a syntax error. When a query fails outright like that, mysql_query() returns a boolean FALSE value, not a statement handle.
Since you lack any kind of error checking, you blindly took that boolean false and passed it on to the fetch function, which has rightfully complained that you didn't provide a result handle.
You should escape any user input before passing it to mysql. Use the PHP function mysql_real_escape_string() to escape any user input before adding it to your query. Here is the link to PHP manual for mysql_real_escape_string()
Update: Yes, what others are saying about using prepared statements or mysqli is much better that using the mysql extension.
Here are a few links on MySQL Injection which I found:
http://www.php.net/manual/en/security.database.sql-injection.php
http://25yearsofprogramming.com/blog/2011/20110205.htm
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet

Categories