面向对象的方式访问数据库
造对象
$db = new MySQLi("localhost","root","123","mydb");
判断连接是否出错
/*if(mysqli_connect_error())
{
echo "连接失败!";
exit;
}*/
!mysqli_connect_error() or die("连接失败!");
写SQL语句
$sql = "insert into Info values('p010','张三',true,'n002','1988-2-3')";
执行SQL语句,查询语句返回结果集对象,其他语句返回true或false
$result = $db->query($sql);
从结果集对象中读取数据
//$attr = $result->fetch_all(MYSQLI_BOTH); //以二维数组的方式返回所有数据
//$attr = $result->fetch_array(); //返回当前指针指向的这条数据
//$attr = $result->fetch_assoc(); //返回当前指针指向的这条数据(关联数组)
//$attr = $result->fetch_object(); //返回对象
//$attr = $result->fetch_row(); //返回索引数组
<body> <h1>登录</h1> <form action="dlchuli.php" method="post"> <div>用户名:<input type="text" name="uid" /></div> <div>密码:<input type="text" name="pwd" /></div> <input type="submit" value="登录" /> </form> </body> <?php $uid = $_POST["uid"]; $pwd = $_POST["pwd"]; //造对象 $db = new MySQLi("localhost","root","123","mydb"); //判断是否出错 !mysqli_connect_error() or die("连接失败!"); //写SQL语句 //容易被SQL注入攻击,不安全 //$sql = "select count(*) from Users where Uid = '{$uid}' and Pwd='{$pwd}'"; $sql = "select Pwd from Users where Uid='{$uid}'"; //执行SQL语句 $result = $db->query($sql); //取数据 $attr = $result->fetch_row(); if($attr[0] == $pwd) { header("location:main.php"); } else { echo "登录失败!"; } <body> <form action="zcchuli.php" method="post"> <div>用户名:<input type="text" name="uid" /></div> <div>密码:<input type="text" name="pwd" /></div> <div>姓名:<input type="text" name="name" /></div> <div>性别:<input type="radio" value="1" name="sex" />男 <input type="radio" value="0" name="sex" />女</div> <div>生日:<input type="text" name="birthday" /></div> <input type="submit" value="注册" /> </form> </body> <?php $uid = $_POST["uid"]; $pwd = $_POST["pwd"]; $name = $_POST["name"]; $sex = $_POST["sex"]; $birthday = $_POST["birthday"]; $s = $sex==1?true:false; //造对象 $db = new MySQLi("localhost","root","123","mydb"); //判断是否出错 !mysqli_connect_error() or die("连接失败!"); //写SQL语句 $sql = "insert into Users values('{$uid}','{$pwd}','{$name}',{$s},'{$birthday}',0)"; //执行SQL语句 $result = $db->query($sql); if($result) { header("location:zhuce.php"); } else { echo "注册失败!"; } //作业:查询INFO表所有数据,显示在页面上(表格) //性别要显示男女 民族 显示民族名称