最近在将项目代码由面向过程改为面向对象时,发现数据库使用的还是php5.6已经废弃的mysql相关函数,在查询php手册时,发现了一些有趣的方法,在网络查询中发现相关的资料还比较少,为了方便以后复习将已经掌握的部分总结在此。
首先附上一个较为完整的查询并获取查询结果的实例,$sql_object为数据库连接对象
$stmt = $mysqli -> stmt_init(); //本行可以忽略 $sql = "SELECT id FORM table_name WHERE tel = ?"; $stmt = $sql_object -> prepare($sql); //创建声明 $stmt -> bind_param("i", $tel); //绑定查询变量,相关变量需在本行之前赋值 $stmt -> execute(); //执行SQL语句 $stmt -> bind_result($id); //绑定结果变量 $stmt -> fetch(); //获取查询结果.多条结果可用while或其他循环遍历 $stmt -> close(); //关闭声明
其中
bind_param()为绑定参数方法,这个方法有两个必须参数,第一个参数为参数类型,第二个为参数值,对应sql语句中的?
参数类型共有以下四种,常用的为i和s
i int 整型 s string(字符串型) d double类型 b blob(二进制大对象),以包的形式发送
附上另外几个bind_param()实例
1. $sql = "SELECT id FORM table_name WHERE tel = ? AND name = ?"; $stmt = $sql_object -> prepare($sql); //创建声明 $stmt -> bind_param("is", $tel,$name); //绑定查询变量,相关变量需在本行之前赋值 2. $sql = "INSERT INTO table_name(id,tel,name) VALUE(?,?,?)"; $stmt = $sql_object -> prepare($sql); //创建声明 $stmt -> bind_param("iis",$id, $tel,$name); //绑定查询变量,相关变量需在本行之前赋值
补充:stmt属性及方法,源自PHP手册
MySQLi_STMT { /* 属性 */ int $mysqli_stmt->affected_rows; int $mysqli_stmt->errno; array $mysqli_stmt->error_list; string $mysqli_stmt->error; int $mysqli_stmt->field_count; int $mysqli_stmt->insert_id; int $mysqli_stmt->num_rows; int $mysqli_stmt->param_count; string $mysqli_stmt->sqlstate; /* 方法 */ int mysqli_stmt_affected_rows ( mysqli_stmt $stmt ) int mysqli_stmt::attr_get ( int $attr ) bool mysqli_stmt::attr_set ( int $attr , int $mode ) bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] ) bool mysqli_stmt::bind_result ( mixed &$var1 [, mixed &$... ] ) bool mysqli_stmt::close ( void ) void mysqli_stmt::data_seek ( int $offset ) int mysqli_stmt_errno ( mysqli_stmt $stmt ) array mysqli_stmt_error_list ( mysqli_stmt $stmt ) string mysqli_stmt_error ( mysqli_stmt $stmt ) bool mysqli_stmt::execute ( void ) bool mysqli_stmt::fetch ( void ) int mysqli_stmt_field_count ( mysqli_stmt $stmt ) void mysqli_stmt::free_result ( void ) mysqli_result mysqli_stmt::get_result ( void ) object mysqli_stmt::get_warnings ( mysqli_stmt $stmt ) mixed mysqli_stmt_insert_id ( mysqli_stmt $stmt ) public bool mysqli_stmt::more_results ( void ) public bool mysqli_stmt::next_result ( void ) int mysqli_stmt_num_rows ( mysqli_stmt $stmt ) int mysqli_stmt_param_count ( mysqli_stmt $stmt ) mixed mysqli_stmt::prepare ( string $query ) bool mysqli_stmt::reset ( void ) mysqli_result mysqli_stmt::result_metadata ( void ) bool mysqli_stmt::send_long_data ( int $param_nr , string $data ) string mysqli_stmt_sqlstate ( mysqli_stmt $stmt ) bool mysqli_stmt::store_result ( void ) }