Insert Data in Oracle DB using PHP

◇◆丶佛笑我妖孽 提交于 2020-01-25 10:51:12

问题


Inserting data in oracle DB using oci_8. Sample query to insert string with special characters or quotes

 update TABLENAME set COMMENTS = 'As per Mark's email dated 28-Feb-2015 - Bill Gates & Team's effort' where ID = 99;

To insert/update

$query = 'update TABLENAME set COMMENTS = '$_POST[comments]';

$result = customexecute($new_query);

public function customexecute($query)
{

    $resutlt = parent::customquery($query);
    return $resutlt;
}


public static function customquery($query)
{

  try{

        $stmt = oci_parse($conn, $query);
        oci_execute($stmt,OCI_COMMIT_ON_SUCCESS);
        oci_commit(db_singleton::getInstance());
        oci_free_statement($stmt);
        }catch (Exception  $e)
        {
            print_r($e);
        }

    }

Executing it on ORACLE DB it says SQl command not properly ended. Looked into Parameterized queries mentioned here but not able to integrate it succesfully.

$query = 'UPDATE tablename SET field = :field WHERE id = :id';
$stmt = oci_parse($oracleConnection, $query);
oci_bind_by_name($stmt, ':field', "The field value with 'apostrophes' and so");
oci_bind_by_name($stmt, ':id', '125');
$result = oci_execute($stmt);

I can pass :bind_comments in my query which is in my controller. But $stmt resides in my db_singleton file (general for all DB queries) and can not pass seperately for a individual query.

How can I sanitize user input or do not allow data to be used in creating SQL code


回答1:


From the update function, pass everything needed to the execute function:

$result = customExecute(
    'update xxx set comments=:COMMENTS where id=:ID',
    [
        ':COMMENTS' => $_POST['comment'],
        ':ID' => 99
    ]
);

Then in the execute function simply iterate the array to bind all params:

public static function customExecute($sql, array $params = [])
{
    $stmt = oci_parse($conn, $sql);
    foreach ($params as $key => &$value) {
        oci_bind_by_name($stmt, $key, $value);
    }
    $result = oci_execute($stmt);
    ...
}



回答2:


No, unsurprisingly, MySQL functions won't work with Oracle DB :)

You need to parameterise things, e.g.:

$query = 'update TABLENAME set COMMENTS = :bind_comments where id = :bind_id';
$stmt = $dbh->prepare($query);
$stmt->bindParam(':bind_comments', $_POST['comments']);
$stmt->bindParam(':bind_id', $_POST['id']);

$stmt->execute();



回答3:


The correct way of using the OCI8 PHP extensions is:

$query = 'UPDATE tablename SET field = :field WHERE id = :id';
$stmt = oci_parse($oracleConnection, $query);
oci_bind_by_name($stmt, ':field', "The field value with 'apostrophes' and so");
oci_bind_by_name($stmt, ':id', '125');
$result = oci_execute($stmt);

More information: http://php.net/manual/book.oci8.php



来源:https://stackoverflow.com/questions/28871719/insert-data-in-oracle-db-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!