php数据库的两种操作方式

MySQL
与MySQL连接:

 static function util(){
        $conn = mysql_connect("localhost","root","root") or die("不能连接到数据库!");
        if($conn)
            echo "连接数据库成功"."
"
; else echo "连接失败".mysql_error($conn); mysql_select_db('mydb') or die("选择数据库不成功!"); echo "选择数据库成功"."
"
; mysql_query("set names utf-8"); return $conn; }
>操作数据库方法:mysql_query()(提示->::是类调用静态属性或方法)

遍历获得的数据:

 function listData($data=null){
        echo "<table><tr><td>idtd><td>姓名td><td>电话td><td>密码td><td>头像路径td><td>零钱td><td>状态td><td>是否有效td><td>创建时间td>tr>";
        while ($row = mysql_fetch_row($data,MYSQL_ASSOC)){
            echo "<tr><td>{$row['id']}td>".
                "<td>{$row['name']}td>".
                "<td>{$row['phone']}td>".
                "<td>{$row['pass']}td>".
                "<td>{$row['logo']}td>".
                "<td>{$row['money']}td>".
                "<td>{$row['status']}td>".
                "<td>{$row['isvalid']}td>".
                "<td>{$row['date']}td>tr>";
        }
        echo "table>";
    }

PDO-MySQL:
连接数据库:

$dbhost = 'localhost:3306';  // mysql服务器主机地址
$dbuser = 'root';            // mysql用户名
$dbpass = '123456';          // mysql用户名密码
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
    die('Could not connect: ' . mysqli_error());
}
echo '数据库连接成功!';
mysqli_close($conn);
 static function connect(){
        $dbms = 'mysql';
        $dbName = 'mydb';
        $user = 'root';
        $pwd = 'root';
        $host = 'localhost';
        $dsn = "$dbms:host=$host;dbname=$dbName";
        try{
            $pdo = new PDO($dsn,$user,$pwd);
            echo "PDO连接MySQL成功";
            return $pdo;
        }catch (Exception $e){
            echo $e->getMessage().'
'
; } }

遍历方法:

function listData($stmt){
        echo "<table><tr><td>idtd><td>姓名td><td>电话td><td>密码td><td>头像路径td><td>零钱td><td>状态td><td>是否有效td><td>创建时间td>tr>";
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            echo "<tr><td>{$row['id']}td>".
                "<td>{$row['name']}td>".
                "<td>{$row['phone']}td>".
                "<td>{$row['pass']}td>".
                "<td>{$row['logo']}td>".
                "<td>{$row['money']}td>".
                "<td>{$row['status']}td>".
                "<td>{$row['isvalid']}td>".
                "<td>{$row['date']}td>tr>";
        }
        echo "table>";
    }

你可能感兴趣的:(笔记)