简体   繁体   English

mysqli_real_escape_string与php中的数组?

[英]mysqli_real_escape_string with array in php?

My code is like this 我的代码是这样的

 public function addQuestions($data){


    $ans = array();
    $ans[1] = $data['ans1'];
    $ans[2] = $data['ans2'];
    $ans[3] = $data['ans3'];
    $ans[4] = $data['ans4'];
    $ans= mysqli_real_escape_string($this->db->link, $data[$ans]);

}

Is this right way to use array in this sql function ?? 这是在这个sql函数中使用数组的正确方法吗?

Since you wish to do something to each element of array $ans, it would be most appropriate to use array_map() , as follows: 由于您希望对数组$ ans的每个元素执行某些操作,因此最适合使用array_map() ,如下所示:

public function addQuestions($data){


    $ans = array();
    $ans[1] = $data['ans1'];
    $ans[2] = $data['ans2'];
    $ans[3] = $data['ans3'];
    $ans[4] = $data['ans4'];

    $escaped_ans = array_map(function( $e ) {
             return mysqli_real_escape_string( $this->db->link, $e);
    }, $ans );

Since you have an array, and you want mysqli_real_escape_string on each element of an array, you can use array_walk() : 由于你有一个数组,并且你想在数组的每个元素上使用mysqli_real_escape_string ,你可以使用array_walk()

function myescape($val)
{
    return mysqli_real_escape_string($val);
}

... then ... 然后

array_walk($ans, 'myescape');

if you use MYSQL PDO you won't need add "mysqli_real_escape_string" because all your variables a safe (from SQL injection) after you bind it 如果您使用MYSQL PDO,则不需要添加“mysqli_real_escape_string”,因为绑定后所有变量都是安全的(来自SQL注入)

http://php.net/manual/en/pdostatement.bindparam.php http://php.net/manual/en/pdostatement.bindparam.php

I don't have enough reputation to comment on Milan's post, but beware of array_walk, it won't change your original array. 我没有足够的声誉评论米兰的帖子,但要注意array_walk,它不会改变你原来的阵列。 For Milan's code to actually affect your array, the function would have to be 对于实际影响阵列的米兰代码,函数必须是

function myescape(&$val) //Note the '&' which calls $val by reference.
{
    $val = mysqli_real_escape_string($val);
}

array_walk($ans, 'myescape');

To answer your question though: 要回答你的问题:

public function addQuestions($data){
    $ans = array('',$data['ans1'],$data['ans2'],$data['ans3'],$data['ans4']);
    //I would recommend using an object/associative array in this case though, just the way $data is already

    $ans_escaped = array_map(function($val) {
        return mysqli_real_escape_string($this->db->link, $val);
    }, $ans);

    //do whatever you need to do with escaped array
}

My advice though, would be to really look into prepared statements. 不过,我的建议是真正研究准备好的陈述。 It might just seem like extra work that you don't want to bother with - at first - but once you learn it, you will never want to do it any other way. 它可能看起来像你不想打扰的额外工作 - 起初 - 但是一旦你学会它,你将永远不想以任何其他方式去做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM