PHP开发的一些趣事
配置运行环境studyPhp:
http://www.phpstudy.net/phpstudy/PhpStudy20180211.zip
PHP运行环境:5.4
首先做的是一个表单测试吧
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>Document</title> 9 </head> 10 11 <body> 12 <form action="welcome.php" method="post" accept-charset="utf-8"> 13 名字: <input type="text" name="fname"> 姓名: <input type="text" name="lastname"> 年龄: <input type="text" name="age"> 14 <input type="submit" value="提交"> 15 </form> 16 </body> 17 18 </html> 19 20 <html>
标识红色的地方,都易出编码问题!
我请求的是:con_db.php
还有就是php本身未开启utf-8扩展,所以跳向php也会出现乱码(但数据库不会乱码),例如
数据库则正常!
后面,我们只需要开启utf-8模式,再重启服务器即可!
studyPhp默认
localhost:3306
username:root
password:root
1 <?php echo $_POST["fname"]; ?>!<br> 2 <?php echo $_POST["age"]; ?><br> 3 <?php echo $_POST["lastname"]; ?> 4 5 <?php 6 $servername = "localhost:3306"; 7 $username = "root"; 8 $password = "root"; 9 $dbname = "mydb"; 10 11 // 创建连接 12 $conn = new mysqli($servername, $username, $password, $dbname); 13 // 检测连接 14 if ($conn->connect_error) { 15 die("连接失败: " . $conn->connect_error); 16 } 17 18 $sql = "INSERT INTO MyGuests (firstname, lastname, email) 19 VALUES ('$_POST[fname]','$_POST[lastname]','$_POST[age]')"; 20 21 if ($conn->query($sql) === TRUE) { 22 echo "新记录插入成功"; 23 } else { 24 echo "Error: " . $sql . "<br>" . $conn->error; 25 } 26 27 $conn->close(); 28 ?>
查询数据库
1 <?php 2 $servername = "localhost:3306"; 3 $username = "root"; 4 $password = "root"; 5 $dbname = "mydb"; 6 7 // 创建连接 8 $conn = new mysqli($servername, $username, $password, $dbname); 9 // Check connection 10 if ($conn->connect_error) { 11 die("连接失败: " . $conn->connect_error); 12 } 13 14 $sql = "SELECT id, firstname, lastname FROM MyGuests"; 15 $result = $conn->query($sql); 16 17 if ($result->num_rows > 0) { 18 // 输出数据 19 while($row = $result->fetch_assoc()) { 20 echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; 21 } 22 } else { 23 echo "0 结果"; 24 } 25 $conn->close(); 26 ?>