1. 程式人生 > >MySQLi面向對象實踐---預處理

MySQLi面向對象實踐---預處理

local mysqli cal sql delete htm www res 結果集

面向對象的預處理和面向過程的預處理一樣,只是轉換一種表現形式而已,可以參照一下面向過程的方法http://www.cnblogs.com/-beyond/p/7577155.html

面向對象的預處理涉及以下幾個函數:

mysqli_stmt mysqli::prepare ( string $query )

bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )

bool mysqli_stmt::execute ( void )

mysqli_result mysqli_stmt::get_result ( void )

void mysqli_stmt::free_result ( void )

bool mysqli_stmt::close ( void )

void mysqli_result::free_result ( void )

具體用法如下

<?php 
	$db=new mysqli("localhost","root","root","test");

    //預處理(增刪改)
    $sql="delete from aaa where uid = ?;";
    $stmt=$db->prepare($sql);
    $uid=4;
    $stmt->bind_param(‘i‘,$uid);
    // $stmt->bind_param(‘i‘,4);wrong
    $stmt->execute();
    $stmt->free_result();
    $stmt->close();

    //預處理(查)
    $sql="select * from aaa where uid >?;";
    $stmt=$db->prepare($sql);
    $uid=1;
    $stmt->bind_param("i",$uid);
    if($stmt->execute()){
	    echo "there are ".$stmt->num_rows." rows\n";
	    echo "there are ".$stmt->field_count." fields\n";
	   	$result=$stmt->get_result();
	   	while(list($id,$name)=$result->fetch_array()){
	   		echo $id."=>".$name."\n";
	   	}
	   $stmt->free_result();
	   $result->free_result();
    } else {
    	echo "failed to execute\n";
    }
	$stmt->close();

	//關閉數據庫
	$db->close();
 ?>

其中關於參數綁定,還有讀取結果集的問題,請查看前兩篇博客

MySQLi面向對象實踐---預處理