php连接数据库有MySQLi和PDO两种方法
以下以PDO为例
一、创建数据库表(students)
二、连接数据库(db.php)
$dsn:数据库连接服务器,数据库名称
$db_user:登录数据库名称
$db_pass:登录数据库密码
1 <?php 2 $dsn="mysql:dbname=phpsql;host=localhost;charset=utf8"; 3 $db_user='root'; 4 $db_pass='123456'; 5 try{ 6 $pdo=new PDO($dsn,$db_user,$db_pass); 7 $pdo->exec('set names utf8'); 8 }catch(PDOException $e){ 9 echo '数据库连接失败'.$e->getMessage(); 10 } 11 ?>
三、显示数据列表(list.php)
1 <?php 2 require_once 'db.php'; 3 $sql = 'select * from students'; 4 $query = $pdo->query($sql); 5 echo "<table border='1'>"; 6 echo "<tr><td>id</td><td>number</td><td>name</td><td>操作</td><td>删除</td></tr>"; 7 foreach($query as $row){ 8 echo "<tr>"; 9 echo "<td>".$row['Id']."</td>"; 10 echo "<td>".$row['number']."</td>"; 11 echo "<td>".$row['name']."</td>"; 12 echo "<td><a href='update.php?id=".$row['Id']."'>修改</a></td>"; 13 echo "<td><a href='delete.php?id=".$row['Id']."'>删除</a></td>"; 14 echo "</tr>"; 15 } 16 echo "</table>"; 17 ?>
四、添加一条数据(index.php,add.php)
1 <html> 2 <head> 3 <title>添加数据</title> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 </head> 6 <body> 7 <form action="add.php" method="post"> 8 学生编号<input name="number" value="" /><br/> 9 学生姓名<input name="name" value="" /><br/> 10 <input type="submit" value="添加" /> 11 </form> 12 </body> 13 </html>
1 <?php 2 header('Content-Type:text/html; charset=UTF-8'); 3 require_once 'db.php'; 4 $data = $_POST; 5 $number = $data['number']; 6 $name = $data['name']; 7 $sql = 'insert into students (number,name) values ("'.$number.'","'.$name.'")'; 8 $result=$pdo->exec($sql); 9 if($result){ 10 echo "添加成功!"; 11 } else{ 12 echo "添加失败!"; 13 } 14 ?>
五、修改一条数据(update.php)
1 <?php 2 require_once 'db.php'; 3 header("Content-type: text/html; charset=utf-8"); 4 ?> 5 <?php 6 if($_GET){ 7 $id = $_GET['id']; 8 $sql = 'select * from students where Id ='.$id.' limit 1'; 9 $query = $pdo->query($sql); 10 $data = $query->fetch(PDO::FETCH_OBJ) 11 ?> 12 <html> 13 <head> 14 <title>添加数据</title> 15 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 16 </head> 17 <body> 18 <form action="update.php" method="post"> 19 <input type="hidden" name="id" value="<?php echo $data->Id; ?>" /> 20 学生编号<input name="number" value="<?php echo $data->number; ?>" /><br/> 21 学生姓名<input name="name" value="<?php echo $data->name; ?>" /><br/> 22 <input type="submit" value="修改" /> 23 </form> 24 </body> 25 </html> 26 <?php } ?> 27 <?php 28 if($_POST){ 29 $update_data = $_POST; 30 $sql = 'update students set number = "'.$update_data['number'].'",name ="'.$update_data['name'].'" where Id = '.$update_data['id']; 31 $rst = $pdo->exec($sql); 32 echo $rst ? '修改成功!':'修改失败!'; 33 } 34 ?>
六、删除一条数据(delete.php)
1 <?php 2 require_once 'db.php'; 3 header('Content-Type:text/html; charset=UTF-8'); 4 $id = $_GET['id']; 5 $sql = 'delete from students where Id = '.$id; 6 $result = $pdo->query($sql); 7 echo $result ? '删除成功!':'删除失败!'; 8 ?>
注意:数据库,php文件,html文件,开发工具编码必须一致!
来源:https://www.cnblogs.com/yanyufei/p/8167709.html