【MySQL】PHP连接数据库

mysql_connect 和 PDO

header('content-type:text/html;charset=utf-8');

/////普通链接数据库//////
$config=array('host'=>'localhost','user'=>'root','password'=>'','dbname'=>'30330dbT68jh','charset'=>'utf8');

function connect($config){
    @$link = mysql_connect($config['host'],$config['user'],$config['password']) or die('连接失败'.mysql_error());
    mysql_select_db($config['dbname'], $link) or die('连接失败'.mysql_error());
    mysql_query('set names '.$config['charset']) or die('连接失败'.mysql_error());
    return $link;
}
$link = connect($config);
// var_dump($link);

//////PDO链接数据库//////
function pdo($config){
    $dsn = "mysql:host=".$config['host'].";dbname=".$config['dbname'];
    $pdo = new PDO($dsn,$config['user'],$config['password']);
    $pdo->query('set names '.$config['charset']);
    return $pdo;
}
$pdo=pdo($config);
var_dump($pdo);

mysqli_connect

<?php
    $connect = mysqli_connect('localhost','root','') or die('连接失败'.mysql_error());
    mysqli_select_db($connect,'test');
    mysqli_query($connect,'set names utf8');

    $sql = 'select goods_id,goods_name,cat_id,shop_price from goods';

    $result = mysqli_query($connect,$sql);
    $list = array();
    while ( $row = mysqli_fetch_assoc($result)) {
        $sql = 'select cat_name from category where cat_id='.$row['cat_id'];
        $result2 = mysqli_query($connect,$sql);
        $row2 = mysqli_fetch_assoc($result2);
        $row['cat_name'] = $row2['cat_name'];
        $list[] = $row;
    }
?>


<!DOCTYPE html>
<html>
<head>
    <title>连接查询 join</title>
</head>
<body>
    <h1>报价单</h1>
    <table border="1">
    <thead>
        <tr>
        <td>商品id</td>
        <td>商品类名</td>
        <td>商品名称</td>
        <td>商品价格</td>
        </tr>
    </thead>
    <tbody>
        <?php foreach($list as $v){ ?>
        <tr>
            <td><?php echo $v['goods_id']?></td>
            <td><?php echo $v['cat_name']?></td>
            <td><?php echo $v['goods_name']?></td>
            <td><?php echo $v['shop_price']?></td>
        </tr>
        <?php } ?>
    </tbody>
    </table>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_39251267/article/details/80279651