欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP连接MySQL

程序员文章站 2022-06-15 14:11:19
一、实例 (MySQLi - 面向对象)

 

  

 一、实例 (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
));
?>