普通写法!
<?php
$mysqli=new mysqli("localhost","root","","demo");
//判断连接
if($mysqli->connect_error){
die("连接失败!"。$mysqli->connect_error());
}
//update语句 把ID=10121 的stuname改成 小明;
$sql="update student set stuname='小明' where id=10121";
//判断 执行sql语句
if($mysqli->query($sql)===true){
echo "修改成功!";
}else{
echo "修改失败!";
}
//关闭连接
$mysqli->close();
?>
封装写法
<?php
//接收mysqli
$mysqli=conn();
//调用update 传参数(连接,表名,条件)
update($mysqli,"student","stuname='和珅' where id=888888");
连接数据库(封装)
function conn(){
$tmysqli= new mysqli("localhost","root","","demo");
if($tmysqli->connect_error){
die("连接失败!".$tmysqli->connect_error());
}
return $tmysqli;
}
function update($tmysqli,$table,$tiaojian){
$sql="update $table set $tiaojian ";
if($tmysqli->query($sql)===true){
echo "修改成功!";
}
}
?>
//类写法
<?php
//创建新的对象
$test=new Test();
//调用连接
$mysqli=$test->conn();
//调用update 并传参数!
$test->update($mysqli,"student","stuname='和珅' where id=1888");
调用close 关闭连接
$test->close($mysqli);
//创建类
class Test{
private $ip="localhost";
private $user="root";
private $pwd="";
private $db="demo";
function conn(){
$tmysqli=new mysqli($this->ip,$this->user,$this->pwd,$this->db);
if($tmysqli->connect_error){
die("链接数据库失败!".$tmysqli->connect_error());
}
echo "ok<br/>";
return $tmysqli;
}
function update($tmysqli,$table,$tiaojian){
$sql="update $table set $tiaojian";
if($tmysqli->query($sql)===true){
$res=$tmysqli->query($sql);
if(!$res){
echo "操作失败!".$tmysqli->error();
}else{
if($tmysqli->affected_rows>0){
echo "执行OK!";
}else{
echo "没有行受到影响!";
}
}
}
function close($closql){
$closql->close() ;
}
}
?>