您的位置:首页 > 博客中心 > 数据库 >

PHP+MySQL:测试连接+基本DB操作

时间:2022-03-13 22:56

PHP使用MySQL,从连接、创建、到结果显示

 1 <?php
 2     //连接MySQL测试
 3     $db = mysql_connect("localhost","root","wenwen");
 4     if (!$db)
 5     {
 6           die(‘Could not connect: ‘ . mysql_error());
 7     }
 8     else
 9     {
10         echo "connect success!";
11     }
12 
13     //创建数据库
14     if (!mysql_query("CREATE DATABASE my_db",$db))
15     {
16         echo "Error creating database: " . mysql_error();
17     }
18 
19     //选择数据库
20     mysql_select_db("my_db", $db);
21 
22     //创建表
23     $sql = "CREATE TABLE Persons 
24     (
25         FirstName varchar(15),
26         LastName varchar(15),
27         Age int
28     )";
29     mysql_query($sql,$db);
30 
31     //插入数据
32     mysql_query("INSERT INTO Persons (FirstName, LastName, Age) 
33     VALUES (‘Jordan‘, ‘Michael‘, ‘51‘)");
34     mysql_query("INSERT INTO Persons (FirstName, LastName, Age) 
35     VALUES (‘Bryant‘, ‘Kobe‘, ‘36‘)");
36 
37     //创建结果集
38     $sql = "SELECT * FROM Persons";
39     $result = mysql_query($sql); 
40 
41     //在 HTML 表格中显示结果
42     echo "<table border=‘1‘>
43     <tr>
44     <th>FirstName</th>
45     <th>LastName</th>
46     <th>Age</th>
47     </tr>";
48 
49     while($rs = mysql_fetch_array($result))
50     {
51         echo "<tr>";
52         echo "<td>" . $rs[‘FirstName‘] . "</td>";
53         echo "<td>" . $rs[‘LastName‘] . "</td>";
54             echo "<td>" . $rs[‘Age‘] . "</td>";
55         echo "</tr>";
56     }
57     echo "</table>";
58 
59     //关闭连接
60     mysql_close($db);
61 ?>

运行效果

gxlsystem.com,布布扣

DB中的变化

gxlsystem.com,布布扣

 

PHP+MySQL:测试连接+基本DB操作,布布扣,bubuko.com

热门排行

今日推荐

热门手游