Query as 400 with php

Php – howto connect to as400 with PHP

I am trying to connect my AS400 with V5R3 with PHP using this code :

;System=xxx.xxx.xxx.xxx; Uid=user;Pwd=password;"; #the name of the iSeries $user="user"; #a valid username that will connect to the DB $pass="password"; #a password for the username $conn=odbc_connect($server,$user,$pass); #you may have to remove quotes #Check Connection if ($conn == false) < echo "Not able to connect to database. 
"; > #Query the Database into a result set - $result=odbc_exec($conn,"SELECT * FROM LIBRARY.V5TDOC0L WHERE T§DTDO = 20120319"); if (!$result) echo ""; echo ""; echo ""; while (odbc_fetch_row($result)) < $ndoc=odbc_result($result,2); $dtdo=odbc_result($result,3); echo ""; echo ""; > echo "
T§NDOCT§DTDO
$ndoc$dtdo
"; #close the connection odbc_close($conn); ?>

Warning: odbc_exec() [function.odbc-exec]: SQL error: [IBM][Programma di controllo ODBC di System i Access][DB2 per i5/OS]SQL0104 – Token � not valid. Token valid: < >= <> != >= � < �>�= IN IS NOT LIKE BETWEEN., SQL state 37000 in SQLExecDirect in F:\xampp\htdocs\php-as400\php-as400.php on line 25
Error in SQL

Removing from the statement SELECT the WHERE T§DTDO = 20120319 , I have it running and listing the elements I want with a warning.

Fatal error: Maximum execution time of 30 seconds exceeded in F:\xampp\htdocs\php-as400\php-as400.php on line 30 T§NDOC T§DTDO C008931 19941102 P005027 19950214 P005031 19950320 P005055 19950612 P005062 19950904 P005065 19950920 P005082 19951218 P005157 19970102 P005186 19970428 P005187 19970429 P005190 19970520 I009353 19970721 P005257 19980217 
while (odbc_fetch_row($result)) 

I believe the problem is the character § as I found looking in internet (https://bugs.php.net/bug.php?id=47133), but I don’t know how to solve it.

Best Solution

I have never seen the character § used in a column name before. This might be a code page conversion issue. Ask the IBM i admin to verify the column name; it might really be T@DTDO, T#DTDO or T$DTDO — something you can actually type. Failing that, try enclosing the column name in double quotes: . where «T§DTDO»=20120319. If that does not work, have the DB2 admin create a view with column names that don’t have special characters in them.

Php – How to prevent SQL injection in PHP

The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create SQL statement with correctly formatted data parts, but if you don’t fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

You basically have two options to achieve this:

    Using PDO (for any supported database driver):

 $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name'); $stmt->execute([ 'name' => $name ]); foreach ($stmt as $row) < // Do something with $row >
 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?'); $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string' $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) < // Do something with $row >

If you’re connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.

Correctly setting up the connection

Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password'); $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

In the above example the error mode isn’t strictly necessary, but it is advised to add it. This way the script will not stop with a Fatal Error when something goes wrong. And it gives the developer the chance to catch any error(s) which are throw n as PDOException s.

What is mandatory, however, is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren’t parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).

Although you can set the charset in the options of the constructor, it’s important to note that ‘older’ versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN.

Explanation

The SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute , the prepared statement is combined with the parameter values you specify.

The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn’t intend.

Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains ‘Sarah’; DELETE FROM employees the result would simply be a search for the string «‘Sarah’; DELETE FROM employees» , and you will not end up with an empty table.

Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.

Oh, and since you asked about how to do it for an insert, here’s an example (using PDO):

$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)'); $preparedStatement->execute([ 'column' => $unsafeValue ]); 

Can prepared statements be used for dynamic queries?

While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.

For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.

// Value whitelist // $dir can only be 'DESC', otherwise it will be 'ASC' if (empty($dir) || $dir !== 'DESC')
Php + unixODBC + DB2 + DESCRIBE = token not valid

The iSeries flavor of DB2 does not support the SQL DESCRIBE statement. Instead, you have to query the system table:

select * from qsys2.columns where table_schema = 'my_schema' and table_name = 'my_table' 

Источник

Как подключиться к as400 с PHP

Я пытаюсь подключить свой AS400 с V5R3 с помощью PHP, используя этот код:

php $server="Driver=;System=xxx.xxx.xxx.xxx; Uid=user;Pwd=password;"; #the name of the iSeries $user="user"; #a valid username that will connect to the DB $pass="password"; #a password for the username $conn=odbc_connect($server,$user,$pass); #you may have to remove quotes #Check Connection if ($conn == false) < echo "Not able to connect to database. 
"; > #Query the Database into a result set - $result=odbc_exec($conn,"SELECT * FROM LIBRARY.V5TDOC0L WHERE T§DTDO = 20120319"); if (!$result) echo ""; echo ""; echo ""; while (odbc_fetch_row($result)) < $ndoc=odbc_result($result,2); $dtdo=odbc_result($result,3); echo ""; echo ""; > echo "
T§NDOCT§DTDO
$ndoc$dtdo
"; #close the connection odbc_close($conn); ?>

Предупреждение: odbc_exec () [function.odbc-exec]: ошибка SQL: [IBM] [Programma di controllo ODBC di System i Access] [DB2 per i5 / OS] SQL0104 – токен недействителен. Текущий токен: <> = <> ! => = < >= IN НЕ НРАВИТСЯ МЕЖДУ., Состояние SQL 37000 в SQLExecDirect в F: \ xampp \ htdocs \ php-as400 \ php- as400.php в строке 25 Ошибка в SQL

Удаление из инструкции SELECT WHERE T§DTDO = 20120319 , я запускаю его и перечисляю элементы, которые я хочу, с предупреждением.

Fatal error: Maximum execution time of 30 seconds exceeded in F:\xampp\htdocs\php-as400\php-as400.php on line 30 T§NDOC T§DTDO C008931 19941102 P005027 19950214 P005031 19950320 P005055 19950612 P005062 19950904 P005065 19950920 P005082 19951218 P005157 19970102 P005186 19970428 P005187 19970429 P005190 19970520 I009353 19970721 P005257 19980217 
while (odbc_fetch_row($result)) 

Я считаю, что проблема заключается в характере §, который я нашел в Интернете ( https://bugs.php.net/bug.php?id=47133 ), но я не знаю, как его решить.

Я никогда не видел символа §, используемого в имени столбца раньше. Это может быть проблемой преобразования кодовой страницы. Попросите администратора IBM i проверить имя столбца; это может быть T @ DTDO, T # DTDO или T $ DTDO – что-то, что вы можете на самом деле напечатать. В противном случае попробуйте включить имя столбца в двойные кавычки: … где «T§DTDO» = 20120319 … Если это не сработает, попросите администратора DB2 создать представление с именами столбцов, которые не имеют специальных символов в их.

Попробуйте использовать цитаты:

$result=odbc_exec($conn,'SELECT * FROM LIBRARY.V5TDOC0L WHERE "T§DTDO" = 20120319'); 

Характер § и £ являются «итальянскими эквивалентами» @ и #.

В итальянском CCSID (например, 280) вы увидите (и используете) поля V5TDOC0L таким образом: T§TDOC, T§NDOC. В другом CCSID (например, 37) вы увидите T @ TDOC и T @ NDOC (для того же файла!).

Я не знаю, какой ccsid будет использовать задание, обслуживающее страницу PHP. Это может зависеть от системного значения по умолчанию.

Попробуйте «SELECT * FROM LIBRARY.V5TDOC0L ГДЕ T @ DTDO = 20120319»

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

fvettore/PHP-AS400-isql-wrapper

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

As reported elsewhere Iseries IBM ODBC 64 bit drivers are badly implemented and causes segmentation fault on NULL returned values with PHP-ODBC. It seems it was implemented on outdated Unix-ODBC specifications. Since command line isql (iusql for UNICODE) tools works perfectly I decided to build a light&simple PHP wraper to query AS400 DB.

  • query
  • basic ODBC error handling
  • fetch_array
  • syntax similar to MySQLI

####Drawbacks#### NULL field value not detecetd. Relaced with »

####Status#### Very initial stage. Tested with Centos7 seems to be able to quickliy fetch tables with several thousands lines.

####DONATE#### If you can and find this useful: Paypal: fabrizio (at) vettore.org

Источник

Читайте также:  Use end in python
Оцените статью