dongzhou8764 2011-02-23 20:25
浏览 76
已采纳

如何在SQL查询中使用prepared和bound语句

I have been told that my query below is very susceptible to an sql injection - I should be using bound parameters instead,

class search
{

    public $mysqli = null;

    public function __construct($mysqli,$keyword = null)
    {
       $this->mysqli = $mysqli;
    }

    public function get_result($parameter)
    {
        $sql = "
        SELECT *
        FROM root_contacts_cfm
        WHERE root_contacts_cfm.cnt_id = '".$parameter."'
        ORDER BY cnt_id DESC
        ";

        $item = $this->mysqli->fetch_assoc($sql);
        return $item;
    }
}

can I ask - how can I turn this search class with a prepared and bound statement?

I have read some articles online why we should use prepared statements, article 1 article 2

But I still don't have a clue how to improve my query... I tried with this amendment below,

class search
{

    public $mysqli = null;

    public function __construct($mysqli)
    {
       $this->mysqli = $mysqli;
    }

    public function get_result($parameter)
    {
        $sql = "
        SELECT *
        FROM root_contacts_cfm
        WHERE root_contacts_cfm.cnt_id = '?'
        ORDER BY cnt_id DESC
        ";

        $stmt = $this->mysqli->prepare($sql);

        /* bind parameters for markers */
        $stmt->bind_param("s", $parameter);

        /* execute query */
        $stmt->execute();

         /* fetch value */
        return $stmt->fetch();

    }
}

So when I call the search class as an object,

$mysqli = new database(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$output = new search($mysqli);
print_r($output->get_result('1'));

I will get this error,

Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of variables doesn't match number of parameters in prepared statement in C:\wamp\www\xxxl\class_database.php on line 487

line 487 refers to $stmt->bind_param("s", $parameter);

Thanks.

  • 写回答

2条回答 默认 最新

  • douzhi4991 2011-02-23 20:57
    关注

    Try removing ', which surrounds your ? placeholder.

    $sql = "
    SELECT *
    FROM root_contacts_cfm
    WHERE root_contacts_cfm.cnt_id = ?
    ORDER BY cnt_id DESC
    ";
    

    In prepared statements whole thing is about specifying type of param when you bind it, not in SQL query - which you did, when wrote '?' . You've said that has to be string, but is not required, when you bind param as a string. Database engine will now how to insert/escape that value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!