• php 创建数据库


    mysqli

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "123456";
    $dbname = "test";
     
    // 创建连接
    $conn = new mysqli($servername, $username, $password);
    // 检测连接
    if ($conn->connect_error) {
        die("连接失败: " . $conn->connect_error);
    } 
     
    // 创建数据库
    $sql = "CREATE DATABASE IF NOT EXISTS ".$dbname." DEFAULT CHARSET utf8 COLLATE utf8_general_ci;";
    if ($conn->query($sql) === TRUE) {
        echo "数据库创建成功";
    } else {
        echo "Error creating database: " . $conn->error;
    }
    

    pdo

    $servername = "localhost"; 
    $username = "root"; 
    $password = "123456";
    $dbname = "test";
    
    try { 
        $conn = new PDO("mysql:host=$servername", $username, $password); 
    
        // 设置 PDO 错误模式为异常 
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
        $sql = "CREATE DATABASE IF NOT EXISTS ".$dbname." DEFAULT CHARSET utf8 COLLATE utf8_general_ci;";
    
        // 使用 exec() ,因为没有结果返回 
        $conn->exec($sql); 
    
        echo "数据库创建成功<br>"; 
    } 
    catch(PDOException $e) 
    { 
        echo $sql . "<br>" . $e->getMessage(); 
    } 
    
    $conn = null; 
    
  • 相关阅读:
    字符串案例1
    字符串1
    标准类制作
    构造方法
    封装
    成员变量和局部变量
    类和对象的案例

    案例
    方法的参数传递
  • 原文地址:https://www.cnblogs.com/jiqing9006/p/13072641.html
Copyright © 2020-2023  润新知