>  기사  >  백엔드 개발  >  php-预编译

php-预编译

WBOY
WBOY원래의
2016-06-23 13:57:421910검색

当出现当量操作sql语句,比如大量将数据插入数据库中,原来的那种单个执行sql语句或者批量执行sql语句的做法,显然是不可行的,因为无论是单个执行还是批量执行都会连续的发送sql语句向数据库中,数据库接到sql语句对它进行编译处理,从而导致效率底下。

而php中出现的预编译解决了这个问题,他的工作原理是:将sql语句发过去,数据库对这一个sql语句进行预编译处理。之后你只需要将要数据发送到数据库即可。

下面通过一个官方的例子来说明这个情况:

<?php $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');/* check connection */if (mysqli_connect_errno()) {    printf("Connect failed: %s\n", mysqli_connect_error());    exit();}$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);$code = 'DEU';$language = 'Bavarian';$official = "F";$percent = 11.2;/* execute prepared statement */$stmt->execute();printf("%d Row inserted.\n", $stmt->affected_rows);/* close statement and connection */$stmt->close();/* Clean up table CountryLanguage */$mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");printf("%d Row deleted.\n", $mysqli->affected_rows);/* close connection */$mysqli->close();?> 


其中$mysqli->prepare进行sql语句的预编译处理,

$stmt->bind_param是进行参数绑定。

$stmt->execute();是进行插入操作。

如果需要插入多个数据,只需要操作$stmt->bind_param和$stmt->execute();即可。

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.