PHP语言 -- 数据访问,连接数据库
1.过时方法,面向过程方式
//设置页面编码格式 header("content-type:text/html;charset=utf-8"); //生成连接 $db_connect = $mysql_connect("localhost","root","123");//服务器地址,用户名,密码 //选择操作的数据库 mysql_select_db("lianxi",$db_connect);//要操作的数据库,用哪个连接 //写SQL语句 $sql = "select * from Info"; //执行SQL语句 $result = mysql_query($sql); //处理查询结果 $row = mysql_fetch_row($result);
2.面向对象方式
//生成连接对象,需要四个参数 $db = new MySQLi("localhost","root","123","lianxi"); //判断连接是否成功 !mysqli_connect_error() or die("连接失败"); //die();函数包含:echo "连接失败"; exit;//直接退出程序 //写SQL语句 $sql = "select * from Info"; //执行SQL语句 $result = $db->query($sql); //操作结果数据 //$row = $result->fetch_row(); /*while($row = $result->fetch_row()) { print_r($row); echo "<br>"; }*/ //$attr = $result->fetch_all(); //返回所有数据,以二维数组的形式返回 $attr = $result->fetch_assoc();//返回一条数据,以关联数组的形式返回
例题:
1.查询一张表的数据,并显示在表格里
<body> <?php //造连接对象 $db = new MySQLi("localhost","root","123","mydb"); //判断是否出错 !mysqli_connect_error() or die("连接失败"); //写SQL语句 $sql = "select * from Info"; //执行SQL语句 $result = $db->query($sql); //处理数据并显示 echo "<table width='100%' border='1' cellpadding='0' cellspacing='0'>"; ehco "<tr><td>代号</td><td>姓名</td><td>性别</td><td>民族</td><td>生日</td></tr>"; while($row = $result->fetch_row()) { $sex = $row[2]?"男":"女" $name = ShowNation($db,$row[3]); echo"<tr><td>{$row[0]}</td><td>{$row[1]}</td><td>{$sex}</td><td>{$name}</td><td>{$row[4]}</td></tr>"; } echo "</table>"; //让Nation 列显示汉字 function ShowNation($db,$code) { //写SQL语句 $sql = "select Name from Nation where Code ='{$code}'"; //执行SQL语句 $result = $db->query($sql); $jieguo = $result->fetch_row(); return $jieguo[0]; } ?> </body>
2.下拉列表
<body> <select> <?php $db = new MySQLi("localhost","root","123","lianxi"); !mysqli_connect_error() or die("连接失败"); $sql = "select * from Nation"; $result = $db->qurey($sql); $attr = $result->fetch_all(); for($i = 0;$i<count($attr);$i++) { list($code,$name) = $attr[$i]; echo "<option value = '{$code}'>{$name}</option>"; } ?> </select> </body>
3.登录
登录页面
<body> <form action="loginchuli.php" method="post";> <div> 用户名: <input type="text" name="uid" /> //必须要有name </div> <div> 密码: <input type="text" name="pwd" /> </div> <div> <input type="submit" value="登录" /> </div> </form> </body>
loginchuli.php 处理页面
<?php $uid = $_POST["uid"]; //取帐号 $pwd = $_POST["pwd"];//取密码 $db = new MySQLi("localhost","root","123","lianxi"); !mysqli_connect_error() or die("连接失败"); $sql = "select count(*) from login where username='{$uid}' and password='{$pwd}'"; $result = $db->query($sql); $attr = $result->fetch_row(); if($attr[0]==1) { header("main.php"); // 帐号密码正确跳转到主页面 } else { header("location:login.php"); //错误,跳转页面 header("location:页面地址") }