是否可以对具有串联变量的查询进行参数化处理?

时间:2019-05-10 10:08:18

标签: php mysql sql mysqli parameters

在学习php和sql注入时,我想对我的查询进行参数化,以获取安全的网站应用程序。但是,我的系统不起作用,我尝试对更新进行参数化并选择查询,但没有达到使程序正常运行的目的。

当前输出抛出错误,找不到?

到目前为止,这是我的代码,我是否缺少一些不起作用的东西?

<?php  
//connection
$connection = mysqli_connect("hostserver","username","");
$db = mysqli_select_db($connection, 'dbname');

if (isset($_POST['qrname'])) {
    $qrid = $_POST['qrid'];

    //Query No. 1
    $qrQuery = "SELECT * FROM scratch_cards WHERE code='$qrid' ";
    $qrQuery_run = mysqli_query($connection,$qrQuery);

    //Query No. 2
    $qrQuery2 = "UPDATE scratch_cards SET status = 'U' WHERE code='$qrid' ";
    $qrQuery_run2 = mysqli_query($connection,$qrQuery2);
    $qrQuery2->bind_param("s", $qrid);
    $qrQuery2->execute();

    while ($qrRow = mysqli_fetch_array($qrQuery_run)) {
        $txtQrvalue = $qrRow['amount'];
        $txtQrstatus = $qrRow['status'];

        // QUERY TO UPDATE THE VALUE
        // BIND AND PARAMETIZE MY QUERY
        $qrQuery3 = $db->parepare("UPDATE shopusers SET ewallet = ewallet + " . (0+?) . " WHERE id = '?' ");
        $qrQuery3->bind_param("ii", $txtQrvalue, $id);
        $qrQuery3->execute(); 
        //END
    }

3 个答案:

答案 0 :(得分:1)

如果我正确地阅读了您的问题和代码,则可以使用JOIN将此问题简化为两个查询,这样就可以摆脱SELECT语句。两者都使用准备好的语句。

我还指定了连接的字符集为UTF-8(应该为PHP和HTML标头以及数据库表设置该字符集)。

<?php 
$connection = mysqli_connect("hostserver","username","");
$db = mysqli_select_db($connection, 'dbname');
$connection->set_charset("utf8");

if (isset($_POST['qrname'])) {
    $qrid = $_POST['qrid'];

    $sql = "UPDATE scratch_cards SET status = 'U' WHERE code=?";
    $stmt = $connection->prepare($sql);
    $stmt->bind_param("s", $qrid);
    $stmt->execute();
    $stmt->close();

    $sql = "UPDATE shopusers su
               INNER JOIN scratch_cards sc
                 ON sc.qrid = su.code
               SET su.ewallet = su.ewallet + sc.amount,
                   sc.status = 'U'
               WHERE sc.code = ?";
    $stmt = $connection->prepare($sql);
    $stmt->bind_param("s", $qrid);
    $stmt->execute();
    $stmt->close();
}

答案 1 :(得分:0)

我们在PDO绑定参数中具有foll语法,在此我以您的更新查询为例,它工作得很好。 尝试搜索命名参数绑定

<?php


$user = 'root';
$pass = 'xxxx';
$DB = 'test';
$host = 'localhost';

$mysqlConnection = new \PDO('mysql:host='.$host.';dbname='.$DB, $user, $pass);
$mysqlConnection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

$sql = 'update info set fname = fname + :fn where id = 1';

$stmt = $mysqlConnection->prepare($sql);
$stmt->bindValue(':fn', '100');
$stmt->execute();
echo $stmt->rowCount();


?>

答案 2 :(得分:0)

这是您要使用mysqli绑定参数运行的查询吗?

<?php

ini_set('display_errors', 1);
$user = 'root';
$pass = 'xxxx';
$DB = 'test';
$host = 'localhost';

$sql = 'update info set fname =  fname + ? where id = 1';

$conn = new mysqli($host, $user, $pass, $DB);
$stmt = $conn->prepare($sql);

$stmt->bind_param("i", $val);
$val = 100;
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
exit;