PHP自學筆記21--DB操作

PHP操作DB有兩種方式,一種是面向過程,一種是面向對象。

1,面向過程

PHP5.5之前呢,使用mysql_connect() ,mysql_query()等mysql_***這樣的函數。

PHP5.5之後雖然也可以使用,但不推薦使用了,而使用mysqli_***這樣的函數。用法跟以前差不多。

 

2,面向對象

使用new mysqli,mysqli->query($sql)這樣的面向對象的寫法。

 

下面對這兩種分別寫一個例子。

 

1,面向過程。(只使用mysqli_***)

<?php
header("Content-Type:text/html;charset=utf-8");

$conn=mysqli_connect('localhost','root','') or die('wrong connect!');
mysqli_select_db($conn, "student") or die('select wrong db!');
mysqli_query($conn, "set names 'utf-8'");

$sql="select * from student";
$result=mysqli_query($conn,$sql);

if($result){
    echo "<table>";
    while($rows=mysqli_fetch_assoc($result)){
        echo "<tr>";
        echo "<td>{$rows['id']}</td>";
        echo "<td>{$rows['username']}</td>";
        echo "<td>{$rows['email']}</td>";
        echo "<td>{$rows['datetime']}</td>";
        echo "</tr>";
    }
    echo "</table>";
}else{
    echo "<br/>you got nothing<br/>";
}
?>

運行結果:

※當然了,想得到如下結果,你得創建一個student數據庫,然後再創建一個student表,並插幾條數據進去。

1 lili [email protected] 2000-09-05 
2 pipi [email protected] 2000-09-05 
3 lulu [email protected] 2000-09-05 

 

2,面向對象方式

<?php 
$mysqli = new mysqli('localhost', 'root', '', 'student');
if($mysqli->connect_errno){
    echo'fail';
    exit;
}

$mysqli->set_charset("UTF8");

$sql="SELECT * FROM student";
$result=$mysqli->query($sql);

if($result){
    echo "<table>";
    while ($row =$result->fetch_assoc()){
        echo "<tr>";
        echo "<td>{$row['id']}</td>";
        echo "<td>{$row['username']}</td>";
        echo "<td>{$row['email']}</td>";
        echo "<td>{$row['datetime']}</td>";
        echo "</tr>";
    }
    echo "</table>";
}else{
    echo "<br/>you got nothing<br/>";
}
?>

 

運行結果和1是一樣的。

 

兩種方式差不多,但爲了跟上時代發展,除非你的項目已經用了面向過程的了,

否則,推薦使用面向對象的方式。

發佈了11 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章