Home > Database > Mysql Tutorial > body text

Detailed explanation of preprocessing examples of php mysqli extension

零下一度
Release: 2017-06-28 16:19:26
Original
1548 people have browsed it

In the previous article MySQL basic knowledge, we talked about the installation and basic operations of MySQL (mainly the query operation of a single SQL statement). Today we introduce a very important part of MySQL: preprocessing.

In mysqli operations, its three main classes are often involved: MySQLi class, MySQL_STMT class, and MySQLi_RESULT class. Preprocessing is mainly done using the MySQL_STMT class.

Preprocessing is an important means of preventing SQL injection and is of great significance to improving website security.

The case of this article is that the database name is test, the data table name is test, the fields include id and title, and the id is an auto-increasing primary key.

connect_errno) {    "Connect Error:".$mysqli->connect_error;
}$mysqli->set_charset('utf8');$id='';$title='title4';//用?代替 变量$sql="INSERT test VALUES (?,?)";//获得$mysqli_stmt对象,一定要记住传$sql,预处理是对sql语句的预处理。$mysqli_stmt=$mysqli->prepare($sql);//第一个参数表明变量类型,有i(int),d(double),s(string),b(blob)$mysqli_stmt->bind_param('is',$id,$title);//执行预处理语句if($mysqli_stmt->execute()){    echo $mysqli_stmt->insert_id;
}else{    echo $mysqli_stmt->error;
}$mysqli->close();
Copy after login


Use mysqli preprocessing to prevent sql injection:

$id='4';$title='title4';$sql="SELECT * FROM test WHERE id=? AND title=?";$mysqli_stmt=$mysqli->prepare($sql);$mysqli_stmt->bind_param('is',$id,$title);if ($mysqli_stmt->execute()) {    $mysqli_stmt->store_result();    if($mysqli_stmt->num_rows()>0){        echo "验证成功";
    }else{        echo "验证失败";
    }
}    $mysqli_stmt->free_result();    $mysqli_stmt->close();
Copy after login


Use mysqli preprocessing to execute query statements:


$sql="SELECT id,title FROM test WHERE id>=?";$mysqli_stmt=$mysqli->prepare($sql);$id=1;$mysqli_stmt->bind_param('i',$id);if($mysqli_stmt->execute()){    $mysqli_stmt->store_result();   //将一个变量绑定到一个prepared语句上用于结果存储    $mysqli_stmt->bind_result($id,$title);    while ($mysqli_stmt->fetch()) {        echo $id.' :'.$title.'
'; } }
Copy after login


The above is the detailed content of Detailed explanation of preprocessing examples of php mysqli extension. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!