使用PHP在Oracle DB中插入数据

时间:2015-03-05 06:54:18

标签: php oracle prepared-statement oci

使用oci_8在oracle DB中插入数据。用于插入带有特殊字符或引号的字符串的示例查询

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

插入/更新

$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);
        }

    }

在ORACLE DB上执行它SQl command not properly ended.查看Parameterized queries提到的here,但无法成功整合。

$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);

我可以在我的控制器中的查询中传递:bind_comments。但是$stmt驻留在我的 db_singleton 文件中(对于所有数据库查询都是通用的),并且不能单独传递单个查询。

如何清理用户输入或不允许在创建SQL代码时使用数据

3 个答案:

答案 0 :(得分:0)

不,不出所料,MySQL函数不适用于Oracle DB:)

您需要对事物进行参数化,例如:

$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();

答案 1 :(得分:0)

使用OCI8 PHP扩展的正确方法是:

$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);

更多信息:http://php.net/manual/book.oci8.php

答案 2 :(得分:0)

从更新功能,传递执行功能所需的一切:

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

然后在execute函数中简单地迭代数组以绑定所有参数:

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);
    ...
}