php和mysql交互 面向对象
不返回结果集
<?php //使用对象属性和方法来插入数据 header('Content-type:text/html;carset=utf8'); $con=new mysqli('localhost','root','123456','t3',3306); $str='insert into tech values (9,"刘海波",132789)'; if($con->connect_error){ $con->connect_error(); } $con->set_charset('utf8'); if($con->query($str)==true){ echo '插入数据成功'; }else{ echo 'ERRPR'.$str.$con->error; } $con->close(); ?>
返回结果集
<?php //使用对象属性和方法来插入数据 header('Content-type:text/html;carset=utf8'); $con=new mysqli('localhost','root','123456','t3',3306); $str='select * from tech'; if($con->connect_error){ $con->connect_error(); } $con->set_charset('utf8'); $result=$con->query($str); //fetch_assoc 返回数组 while($jieguo=$result->fetch_assoc()){ echo $jieguo['id'].'-------'.$jieguo['name'].'---------'.$jieguo['pwd'].'--------'.'<br>'; } $con->close(); ?>
预处理机制
<?PHP header('Content-type:text/html;charset=utf8'); $con=new mysqli('localhost','root','123456','t3'); if($con->connect_error){ die('连接失败'.$con->connect_error); } $con->set_charset('utf8'); $query='insert into tech values (?,?,?)'; //预备sql处理函数 返回一个数据库类型对象 $stmt=$con->prepare($query); $stmt->bind_param('isi',$fid,$fname,$fpwd); $fid=10; $fname="祁筱以"; $fpwd=456852; $stmt->execute(); echo '插入成功'; //释放类型数据库对象结果集 $stmt->free_result(); //关闭数据库连接 $con->close(); ?>
预处理机制返回结果
<?PHP header('Content-type:text/html;charset=utf8'); $con=new mysqli('localhost','root','123456','t3'); if($con->connect_error){ die('连接失败'.$con->connect_error); } $con->set_charset('utf8'); $query='select * from tech where id>?'; //预备sql处理函数 返回一个预编译的sql对象 $stmt=$con->prepare($query); $stmt->bind_param('i',$fid); $fid=1; $stmt->execute(); //预编译sql对象绑定结果 $stmt->bind_result($id,$name,$pwd); while($stmt->fetch()){ echo "{$id}->{$name}->{$pwd}<br>"; } $stmt->free_result(); //关闭数据库连接 $con->close(); ?>