在php中有很多种方法可连接到mysql数据库我们常用的就有mysqli_connect,mysql_connect,mysqli这三种,有需要的朋友可参考参考.
1、使用Mysqli操作Mysql
例子1.Object oriented style,代码如下:
- <?php
- $mysqli = new mysqli("localhost", "my_user", "my_password", "world");
-
-
- if (mysqli_connect_errno()) {
- printf("Connect failed: %sn", mysqli_connect_error());
- exit();
- }
-
- printf("Host information: %sn", $mysqli->host_info);
-
-
- $mysqli->close();
- ?>
-
-
-
-
-
-
-
-
-
- $sSQL = "select * from db";
-
- $query = mysqli_query($connect,$sSQL);
-
-
-
-
- while($arr = mysqli_fetch_array($query)){
-
- print_r($arr);
-
- }
- mysqli_free_result($query);
-
- mysqli_close($connect);
-
2、使用Mysql操作Mysql
在 PHP 中,这个任务通过 mysql_connect() 函数完成.
语法:mysql_connect(servername,username,password);
例子:在下面的例子中,我们在一个变量中 ($con) 存放了在脚本中供稍后使用的连接,如果连接失败,将执行 "die" 部分,代码如下:
- <?php
- $con = mysql_connect("localhost","peter","abc123");
- if (!$con)
- {
- die('Could not connect: ' . mysql_error());
- }
-
-
-
- ?>
-
-
-
-
-
-
-
-
- mysql_select_db("db");
-
-
-
-
- $sSQL = "select * from db";
-
- $query = mysql_query($sSQL);
-
-
-
- while($arr = mysql_fetch_array($query)){
-
-
- print_r($arr);
- }
- mysql_free_result($query);
-
关闭连接,脚本一结束,就会关闭连接,如需提前关闭连接,请使用 mysql_close() 函数,代码如下:
- <?php
- $con = mysql_connect("localhost","peter","abc123");
- if (!$con)
- {
- die('Could not connect: ' . mysql_error());
- }
-
-
-
- mysql_close($con);
- ?>
3、以OOP方式使用mysqli,代码如下:
- $conn = new mysqli("host","username","passwd","db",port);
-
-
-
-
-
-
-
-
- $sSQL = "select * from user";
-
- $query = $conn->query($sSQL);
-
-
-
- while($arr = $query->fetch_array()){
-
- print_r($arr);
- }
- $query->close();
-
- $conn->close();
|