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 ??
Since you wish to do something to each element of array $ans, it would be most appropriate to use array_map() , as follows:
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()
:
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
I don't have enough reputation to comment on Milan's post, but beware of array_walk, it won't change your original array. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.