mysqli使用实例和详解

  1.  ?php
  2. $conn=new mysqli("localhost","root","root","db_database09");
  3. $conn->query("set names gb2312");
  4. $id=$_GET[id];
  5. include_once("conn.php");
  6. $conn->autocommit(false);
  7. if(!$conn->query("delete from tb_sco where id='".$id."'"))
  8. {
  9.  $conn->rollback();
  10. }
  11. if(!$conn->query("delete from tb_stu where id='".$id."'"))
  12. {
  13.  $conn->rollback();
  14. }
  15. $conn->commit();
  16. $conn->autocommit(true);
  17. ==============================================
  18. Mysqli
  19. 连接数据库
  20. $mysqli = new mysqli("localhost""root""secret""test");
  21. if (mysqli_connect_errno( )) {
  22. printf("Connect failed: %s/n", mysqli_connect_error( ));
  23. exit ( );
  24. else {
  25. printf("Connect succeeded/n");
  26. }
  27. ?>
  28. 错误检查
  29. 1)
  30. if ($mysqli->query($sql) <> TRUE) {
  31. printf("Statement failed %d: (%s) %s/n" ,$mysqli->errno,$mysqli->sqlstate,$mysqli->error);
  32. }
  33. ?>
  34. 2)
  35. $mysqli->query($sqlor printf("Statement failed %d: (%s) %s/n" ,$mysqli->errno,$mysqli->sqlstate,$mysqli->error);
  36. ?>
  37. 3)
  38. $mysqli->query($sql);
  39. if ($mysqli->errno <> 0 ) {
  40. printf("Statement failed %d: (%s) %s/n" ,$mysqli->errno,$mysqli->sqlstate,$mysqli->error);
  41. }
  42. ?>
  43. 简单无返回查询
  44. $mysqli->query("CREATE TABLE guy_1 (guys_integers INT)");
  45. if ($mysqli->errno <> 0 ) {
  46. printf("Statement failed %d: (%s) %s/n" ,$mysqli->errno,$mysqli->sqlstate,$mysqli->error);
  47. }
  48. ?>
  49. 返回结果集fetch_object
  50. $sql="SELECT employee_id, surname, salary FROM employees WHERE salary>95000 AND department_id=1 AND status='G'";
  51. $results=$mysqli->query($sql);
  52. if ($mysqli->errno) { die ($mysqli->errno." ".$mysqli->error); }
  53. while($row=$results->fetch_object( )) {
  54. printf("%d/t%s/t%d/n",$row->employee_id,$row->surname,$row->salary);
  55. }
  56. ?>
  57. 使用fetch_row返回结果集
  58. $sql="SELECT employee_id, surname, salary FROM employees WHERE salary>95000 AND department_id=1 AND status='G'";
  59. $results=$mysqli->query($sql);
  60. if ($mysqli->errno) { die ($mysqli->errno." ".$mysqli->error); }
  61. while($row=$results->fetch_row( )) {
  62. printf("%d/t%s/t%d/n",$row[0],$row[1],$row[2]);
  63. }
  64. ?>
  65. 事务管理
  66. $mysqli->autocommit(FALSE);
  67. $mysqli->query("UPDATE account_balance SET balance=balance-$tfer_amount WHERE account_id=$from_account");
  68. if ($mysqli->errno) {
  69. printf("transaction aborted: %s/n",$mysqli->error);
  70. $mysqli->rollback( );
  71. }
  72. else {
  73. $mysqli->query("UPDATE account_balance SET balance=balance+$tfer_amount WHERE account_id=$to_account");
  74. if ($mysqli->errno) {
  75. printf("transaction aborted: %s/n",$mysqli->error);
  76. $mysqli->rollback( );
  77. }
  78. else {
  79. printf("transaction succeeded/n");
  80. $mysqli->commit( );
  81. }
  82. }
  83. ?>
  84. prepare语句
  85. $insert_stmt=$mysqli->prepare("INSERT INTO x VALUES(?,?)"or die($mysqli->error);
  86. $insert_stmt->bind_param("is"$my_number,$my_string); #i=integer
  87. for ($my_number = 1; $my_number <= 10; $my_number++) {
  88. $my_string="row ".$my_number;
  89. $insert_stmt->execute( ) or die ($insert_stmt->error);
  90. }
  91. $insert_stmt->close( );
  92. ?>
  93. 从prepared语句中返回结果集
  94. $sql="SELECT employee_id,surname,firstname FROM employees WHERE department_id=? AND status=? IMIT 5";
  95. $stmt = $mysqli->prepare($sql);
  96. if ($mysqli->errno<>0) {die($mysqli->errno.": ".$mysqli->error);}
  97. $stmt->bind_param("is",$input_department_id,$input_statusor die($stmt-error);
  98. $stmt->bind_result( $employee_id,$surname,$firstnameor die($stmt->error);
  99. $input_department_id=1;
  100. $input_status='G';
  101. $stmt->execute( );
  102. if ($mysqli->errno<>0) {die($stmt.errno.": ".$stmt->error) ;}
  103. while ($stmt->fetch( )) {
  104. printf("%s %s %s/n"$employee_id,$surname,$firstname);
  105. }
  106. ?>
  107. 获得 Metadata结果集
  108. $metadata = $stmt->result_metadata( );
  109. $field_cnt = $metadata->field_count;
  110. while ($colinfo = $metadata->fetch_field( )) {
  111. printf("Column: %s/n"$colinfo->name);
  112. printf("max. Len: %d/n"$colinfo->max_length);
  113. printf("Type: %d/n/n"$colinfo->type);
  114. }
  115. ?>
  116. 调用无结果集的存储过程
  117. $sql = 'call simple_stored_proc( )';
  118. $mysqli->query($sql);
  119. if ($mysqli->errno) {
  120. die("Execution failed: ".$mysqli->errno.": ".$mysqli->error);
  121. }
  122. else {
  123. printf("Stored procedure execution succeeded/n");
  124. }
  125. ?>
  126. 返回单个结果集的存储过程
  127. CREATE PROCEDURE department_list( ) READS SQL DATA SELECT department_name,location from departments;
  128. $sql = "call department_list( )";
  129. $results = $mysqli->query($sql);
  130. if ($mysqli->errno) {
  131. die("Execution failed: ".$mysqli->errno.": ".$mysqli->error);
  132. }
  133. while ($row = $results->fetch_object( )) {
  134. printf("%s/t%s/n"$row->department_name, $row->location);
  135. }
  136. ?>
  137. 有输入参数和返回结果集的存储过程
  138. CREATE PROCEDURE customers_for_rep(in_sales_rep_id INT) READS SQL DATA SELECT customer_id,customer_name FROM customers WHERE sales_rep_id=in_sales_rep_id;
  139. $sql = "CALL customers_for_rep(?)";
  140. $stmt = $mysqli->prepare($sql);
  141. if ($mysqli->errno) {die($mysqli->errno.":: ".$mysqli->error);}
  142. $stmt->bind_param("i"$in_sales_rep_id);
  143. $in_sales_rep_id = 1;
  144. $stmt->execute( );
  145. if ($mysqli->errno) {die($mysqli->errno.": ".$mysqli->error);}
  146. $stmt->bind_result($customer_id,$customer_name);
  147. while ($stmt->fetch( )) {
  148. printf("%d %s /n"$customer_id,$customer_name);
  149. }
  150. ?>
  151. 输出参数的处理
  152. CREATE PROCEDURE sp_rep_customer_count(in_emp_id DECIMAL(8,0), OUT out_cust_count INT) NOT DETERMINISTIC READS SQL DATA BEGIN SELECT count(*) INTO out_cust_count FROM customers WHERE sales_rep_id=in_emp_id; END;
  153. $sql="CALL sp_rep_customer_count(1,@customer_count)";
  154. $stmt = $mysqli->prepare($sql);
  155. if ($mysqli->errno) {die($mysqli->errno.": ".$mysqli->error);}
  156. $stmt->execute( );
  157. if ($mysqli->errno) {die($mysqli->errno.": ".$mysqli->error);}
  158. $stmt->close( );
  159. $results = $mysqli->query("SELECT @customer_count AS customer_count");
  160. $row = $results->fetch_object( );
  161. printf("Customer count=%d/n",$row->customer_count);
  162. ?>
  163. 多结果集处理
  164. CREATE PROCEDURE stored_proc_with_2_results(in_sales_rep_id INT) DETERMINISTIC READS SQL DATA BEGIN SELECT employee_id,surname,firstname FROM employees WHERE employee_id=in_sales_rep_id; SELECT customer_id,customer_name FROM customers WHERE sales_rep_id=in_sales_rep_id; END;
  165. $query = "call stored_proc_with_2_results( $employee_id )";
  166. if ($mysqli->multi_query($query)) {
  167. $result = $mysqli->store_result( );
  168. while ($row = $result->fetch_object( )) {
  169. printf("%d %s %s/n",$row->employee_id,$row->surname,$row->firstname);
  170. }
  171. $mysqli->next_result( );
  172. $result = $mysqli->store_result( );
  173. while ($row = $result->fetch_object( )) {
  174. printf("%d %s /n",$row->customer_id,$row->customer_name);
  175. }
  176. }
  177. ?>
  178. 不确定结果集数的处理
  179. $query = "call stored_proc_with_2_results( $employee_id )";
  180. if ($mysqli->multi_query($query)) {
  181. do {
  182. if ($result = $mysqli->store_result( )) {
  183. while ($finfo = $result->fetch_field( )) {
  184. printf("%s/t"$finfo->name);
  185. }
  186. printf("/n");
  187. while ($row = $result->fetch_row( )) {
  188. for ($i=0;$i<$result->field_count;$i++) {
  189. printf("%s/t"$row[$i]);
  190. }
  191. printf("/n");
  192. }
  193. $result->close( );
  194. }
  195. while ($mysqli->next_result());
  196. }
  197. ?>
  198. PDO
  199. 连接数据库
  200. $dsn = 'mysql:dbname=prod;host=localhost;port=3305';
  201. $user = 'root';
  202. $password = 'secret';
  203. try {
  204. $dbh = new PDO($dsn$user$password);
  205. }
  206. catch (PDOException $e) {
  207. die('Connection failed: '.$e->getMessage( ));
  208. }
  209. print "Connected/n";
  210. ?>
  211. 简单查询
  212. $sql="CREATE TABLE my_numbers (a_number INT)";
  213. $dbh->exec($sql);
  214. ?>
  215. $rows=$dbh->exec("INSERT INTO my_numbers VALUES (1), (2), (3)");
  216. printf("%d rows inserted/n",$rows);
  217. ?>
  218. 错误处理
  219. $sql="CREATE TABLE my_numbers (a_number INT)";
  220. $dbh->exec($sql);
  221. if ($dbh->errorCode( )<>'00000') {
  222. $error_array=$dbh->errorInfo( );
  223. printf("SQLSTATE : %s/n",$error_array[0]);
  224. printf("MySQL error code : %s/n",$error_array[1]);
  225. printf("Message : %s/n",$error_array[2]);
  226. }
  227. ?>
  228. $sql="CREATE TABLE my_numbers (a_number INT)";
  229. $dbh->exec($sql);
  230. if ($dbh->errorCode( )<>'00000') {
  231. die("Error: ".implode(': ',$dbh->errorInfo( ))."/n");
  232. }
  233. ?>
  234. 事务管理
  235. $dbh->beginTransaction( );
  236. $dbh->exec("UPDATE account_balance SET balance=balance-$tfer_amount WHERE account_id=$from_account");
  237. if ($dbh->errorCode( )<>'00000') {
  238. printf("transaction aborted: %s/n",implode(': ',$dbh->errorInfo( )));
  239. $dbh->rollback( );
  240. }
  241. else {
  242. $dbh->exec("UPDATE account_balance SET balance=balance+$tfer_amount WHERE account_id=$to_account");
  243. if ($dbh->errorCode( )<>'00000') {
  244. printf("transaction aborted: %s/n",implode(': ',$dbh->errorInfo( )));
  245. $dbh->rollback( );
  246. }
  247. else {
  248. printf("transaction succeeded/n");
  249. $dbh->commit( );
  250. }
  251. }
  252. ?>
  253. 结果集处理
  254. $sql = 'SELECT department_id,department_name FROM departments';
  255. foreach ($dbh->query($sqlas $row) {
  256. printf("%d /t %s/n",$row['department_id'],$row['department_name']);
  257. }
  258. ?>
  259. $sql = 'SELECT department_id,department_name FROM departments';
  260. foreach ($dbh->query($sqlas $row) {
  261. printf("%d /t %s/n",$row[0],$row[1]);
  262. }
  263. ?>
  264. prepare语句
  265. $sql = 'INSERT INTO my_numbers VALUES(1),(2),(3)';
  266. $sth = $dbh->prepare($sql);
  267. $sth->execute() or die (implode(':',$sth->errorInfo( )));
  268. ?>
  269. 从prepare语句中返回结果集
  270. $sql='SELECT department_id,department_name FROM departments LIMIT 5';
  271. $sth=$dbh->prepare($sqlor die (implode(':',$sth->errorInfo( )));
  272. $sth->execute() or die (implode(':',$sth->errorInfo( )));
  273. while($row=$sth->fetch( )) {
  274. printf("%d /t %s /n",$row['department_id'],$row['department_name']);
  275. }
  276. ?>
  277. 为prepare绑定数据
  278. $sql='SELECT customer_id,customer_name FROM customers WHERE sales_rep_id=:sales_rep_id AND contact_surname=:surname';
  279. $sth = $dbh->prepare($sql);
  280. if ($dbh->errorCode( )<>'00000') {
  281. die("Error: ".implode(': ',$dbh->errorInfo( ))."/n");
  282. }
  283. $sth->bindParam(':sales_rep_id'$sales_rep_id, PDO::PARAM_INT);
  284. $sth->bindParam(':surname'$surname, PDO::PARAM_STR, 30);
  285. $sales_rep_id=41;
  286. $surname = 'SMITH';
  287. $sth->execute( );
  288. if ($dbh->errorCode( )<>'00000') {
  289. die("Error: ".implode(': ',$dbh->errorInfo( ))."/n");
  290. }
  291. while($row=$sth->fetch( )) {
  292. printf("%d %s /n",$row['customer_id'],$row['customer_name']);
  293. }
  294. ?>
  295. 查询 metadata
  296. $sth = $dbh->prepare("SELECT employee_id,surname,date_of_birth FROM employees where employee_id=1");
  297. $sth->execute() or die (implode(':',$sth->errorInfo( )));
  298. $cols=$sth->columnCount( );
  299. for ($i=0; $i<$cols ;$i++) {
  300. $metadata=$sth->getColumnMeta($i);
  301. printf("/nDetails for column %d/n",$i+1);
  302. printf(" Name: %s/n",$metadata["name"]);
  303. printf(" Datatype: %s/n",$metadata["native_type"]);
  304. printf(" Length: %d/n",$metadata["len"]);
  305. printf(" Precision: %d/n",$metadata["precision"]);
  306. }
  307. ?>
  308. 执行简单存储过程
  309. $sql='call simple_stored_proc( )';
  310. $dbh->exec($sql);
  311. if ($dbh->errorCode( )<>'00000') {
  312. die("Error: ".implode(': ',$dbh->errorInfo( ))."/n");
  313. }
  314. ?>
  315. 单个结果集的存储过程
  316. $sql = 'call stored_proc_with_1_result( )';
  317. foreach ($dbh->query($sqlas $row) {
  318. printf("%d /t %s/n",$row[0],$row[1]);
  319. }
  320. ?>
  321. $sql='call stored_proc_with_1_result( )';
  322. $sth=$dbh->prepare($sqlor die (implode(':',$sth->errorInfo( )));
  323. $sth->execute() or die (implode(':',$sth->errorInfo( )));
  324. while($row=$sth->fetch( )) {
  325. printf("%s /t %s /n",$row['department_name'],$row['location']);
  326. }
  327. ?>
  328. 绑定输入参数
  329. $sql='CALL customers_for_rep(:sales_rep_id,:surname)';
  330. $sth = $dbh->prepare($sql);
  331. if ($dbh->errorCode( )<>'00000') {
  332. die("Error: ".implode(': ',$dbh->errorInfo( ))."/n");
  333. }
  334. $sth->bindParam(':sales_rep_id'$sales_rep_id, PDO::PARAM_INT);
  335. $sth->bindParam(':surname'$surname, PDO::PARAM_STR, 30);
  336. $sales_rep_id=41;
  337. $surname = 'SMITH';
  338. $sth->execute( );
  339. ?>
  340. 多结果集处理
  341. CREATE PROCEDURE stored_proc_with_2_results(in_sales_rep_id INT) DETERMINISTIC READS SQL DATA BEGIN SELECT employee_id,surname,firstname FROM employees WHERE employee_id=in_sales_rep_id; SELECT customer_id,customer_name FROM customers WHERE sales_rep_id=in_sales_rep_id; END;
  342. $sth = $dbh->prepare("call stored_proc_with_2_results( $employee_id )");
  343. $sth->execute() or die (implode(':',$sth->errorInfo( )));
  344. while ($row1=$sth->fetch( )) {
  345. printf("%d %s %s/n",$row1['employee_id'],$row1['surname'],$row1['firstname']);
  346. }
  347. $sth->nextRowset( );
  348. while ($row2=$sth->fetch( )) {
  349. printf("%d %s /n",$row2['customer_id'],$row2['customer_name']);
  350. }
  351. ?>
  352. 不确定结果集数量的处理
  353. CREATE PROCEDURE sp_employee_report(in_emp_id decimal(8,0)) READS SQL DATA BEGIN DECLARE customer_count INT; SELECT surname,firstname,date_of_birth FROM employees WHERE employee_id=in_emp_id; SELECT department_id,department_name FROM departments WHERE department_id=(select department_id FROM employees WHERE employee_id=in_emp_id); SELECT count(*) INTO customer_count FROM customers WHERE sales_rep_id=in_emp_id; IF customer_count=0 THEN SELECT 'Employee is not a current sales rep'; ELSE SELECT customer_name,customer_status FROM customers HERE sales_rep_id=in_emp_id; SELECT customer_name,sum(sale_value) FROM sales JOIN customers USING (customer_id) WHERE customers.sales_rep_id=in_emp_id GROUP BY customer_name; END IF;
  354. function many_results($dbh$sql_text) {
  355. $sth = $dbh->prepare($sql_text);
  356. $sth->execute() or die(implode(':'$sth->errorInfo( )));
  357. do {
  358. if ($sth->columnCount( ) > 0) { //是结果集
  359. //输出字段名
  360. for ($i = 0; $i < $sth->columnCount( ); $i ++) {
  361. $meta = $sth->getColumnMeta($i);
  362. printf("%s/t"$meta["name"]);
  363. }
  364. printf("/n");
  365. while ($row = $sth->fetch( )) {
  366. for ($i = 0; $i < $sth->columnCount( ); $i ++) {
  367. printf("%s/t"$row[$i]);
  368. }
  369. printf("/n");
  370. }
  371. printf("-------------------/n");
  372. }
  373. while ($sth->nextRowset( ));
  374. }
  375. ?>
  376. 输出参数
  377. CREATE PROCEDURE 'sp_rep_customer_count'(in_emp_id DECIMAL(8,0),OUT out_cust_count INT) READS SQL DATA BEGIN SELECT count(*) AS cust_count INTO out_cust_count FROM customers WHERE sales_rep_id=in_emp_id; END ;
  378. $sql = "call sp_rep_customer_count(?,?)";
  379. $sth = $dbh->prepare($sqlor die(implode(':'$sth->errorInfo( )));
  380. $sth->bindParam(1,$sales_rep_id,PDO::PARAM_STR,4000);
  381. $sth->bindParam(2,$customer_count, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT);
  382. $sth->execute() or die(implode(':'$sth->errorInfo( )));
  383. ?>
  384. 不使用bindParam获得输出参数
  385. $sql="call sp_rep_customer_count(1,@customer_count)";
  386. $sth = $dbh->prepare($sql);
  387. $sth->execute() or die (implode(':',$sth->errorInfo( )));
  388. $sql="SELECT @customer_count";
  389. foreach ($dbh->query($sqlas $row) {
  390. printf("Customer count=%d/n",$row[0]);
  391. }
  392. ?> 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值