数据库
首页 > 数据库> > PHP连接MySQL

PHP连接MySQL

作者:互联网

 

  

 一、实例 (MySQLi - 面向对象)

<?php

  $servername = "localhost";

  $username = "username";

  $password = "password";

  $dbname = "myDB";

   // 创建连接

  //$conn = new mysqli($servername, $username, $password);

  $conn = new mysqli($servername, $username, $password, $dbname );

  // 检测连接

  if ($conn->connect_error)

  {

    die("连接失败: " . $conn->connect_error);

  }

  // 创建数据库

  $sql = "CREATE DATABASE myDB";

  if ($conn->query($sql) === TRUE)

  {

    echo "数据库创建成功";

  } else {

    echo "Error creating database: " . $conn->error;

  }

  $conn->close();

  echo "连接成功";

?>

 

二、实例 (MySQLi - 面向过程)

<?php

  $servername = "localhost";

  $username = "username";

  $password = "password";

  $dbname = "myDB";

  // 创建连接

  //$conn = mysqli_connect($servername, $username, $password);

  $conn = mysqli_connect($servername, $username, $password,$dbname );

  // 检测连接

  if (!$conn) {

    die("Connection failed: " . mysqli_connect_error());

  }

  // 创建数据库

  $sql = "CREATE DATABASE myDB";

  if (mysqli_query($conn, $sql))

  {

    echo "数据库创建成功";

  } else {

    echo "Error creating database: " . mysqli_error($conn);

  }

  mysqli_close($conn);

  echo "连接成功";

?>

三、实例 (PDO)

<?php

  $servername = "localhost";

  $username = "username";

  $password = "password";

  $dbname = "myDBPDO";

  try {

    //$conn = new PDO("mysql:host=$servername;", $username, $password);

    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

    echo "连接成功";

    // 设置 PDO 错误模式为异常 
         $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
         $sql = "CREATE DATABASE myDBPDO"; 
         // 使用 exec() ,因为没有结果返回 
         $conn->exec($sql); 
       echo "数据库创建成功<br>"; 

  } catch(PDOException $e) {

    echo $sql . "<br>" . $e->getMessage(); 

  }

  $conn = null;

?>

四、持久化连接

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));
?>

标签:username,PHP,servername,echo,MySQL,mysqli,password,连接,conn
来源: https://www.cnblogs.com/cje-hsx/p/12418587.html