php课程---练习连接数据库及增删改
方式一:用php中的内置函数来做 (适用于5.1之前的版本)
//1.生成连接 $conn = mysql_connect("localhost","root",""); //2.选择操作的数据库 mysql_select_db("today",$conn); //3.写sql语句 $sql = "select * from Info"; //4.执行mysql语句 $result = mysql_query($sql); //5.提取数据 $array = mysql_fetch_row($result); $array = mysql_fetch_row($result); print_r($array);
结果:
//1.生成连接 $conn = mysql_connect("localhost","root",""); //2.选择操作的数据库 mysql_select_db("today",$conn); //3.写sql语句 $sql = "insert into Info values('p100','张三',false,'n001','1998-3-4')"; //4.执行mysql语句 $result = mysql_query($sql); //5.提取数据 echo var_dump($result);
结果:
方式二:用类和对象来做(适用于5.1之后的版本)
//1.造连接对象 $db=new mysqli("localhost","root","","today"); //2.判断是否连接成功 if(mysqli_connect_error()) { echo "连接失败"; exit; //退出整个程序 } else { //3.写sql语句 $sql = "select * from Info"; //4. 执行sql语句 $result = $db->query($sql); //5.处理数据(提取数据) echo "<table width='100%' cellpadding='0' cellspacing='0' border='1'>"; echo "<tr bgcolor='#660099'><td>代号</td><td>姓名</td><td>性别</td><td>民族</td><td>生日</td><tr>"; //遍历每一条数据 while($row=$result->fetch_row()) { //处理性别 $sex = (bool)$row[2]?"男":"女"; //处理民族 $nation = NationName($db,$row[3]); //处理生日 $birthday = date("Y年m月d日",strtotime($row[4])); //需要的参数是一个时间戳,需要转一下,转成时间戳 echo "<tr><td>{$row[0]}</td><td>{$row[1]}</td><td>{$sex}</td><td>{$nation}</td><td>{$birthday}</td><tr>"; } echo "</table>"; } //根据民族代号查询民族名称 function NationName($db,$code) { //写sql语句 $sql = "select * from Nation where Code='{$code}'"; //执行sql语句 $result = $db->query($sql); //处理数据 if($row=$result->fetch_row()) { return $row[1]; } else { return ""; } }
结果: