php连接数据库代码_PHP代码连接各种数据库

php连接数据库代码

1)用PHP连接MySQL (1) Connecting with MySQL in PHP)

<?php
$host = "localhost";
$uname = "username";
$pw = "password";
$db = "newDB";
try {
    $conn = new PDO("mysql:host=$host;dbname=$db", $uname, $pw);
    // set error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
}
catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?> 

Here, we are using PDO (PHP Data Objects) to create a MySQL connection. We then check if there are any errors. If there are none, we print "connected Successfully" or else, we print "connection failed" followed by the error thrown by PDO.

在这里,我们使用PDO(PHP数据对象) 创建MySQL连接 。 然后,我们检查是否有任何错误。 如果不存在,则打印“连接成功” ,否则,打印“连接失败”,然后打印PDO引发的错误。

2)用PHP连接postgres (2) Connecting with postgres in PHP)

<?php
$host = "localhost";
$uname = "username";
$pw = "password";
$db = "newDB";
$dbcon = pg_connect("host=$host port=5432 dbname=$db user=$uname password=$pw");
?>

Here, we are using pg_connect() method to connect to a postgres database. We can choose to either define the database details in variables or inline directly.

在这里,我们使用pg_connect()方法 连接到postgres数据库 。 我们可以选择在变量中定义数据库详细信息,也可以直接内联。

3)用PHP连接SQLite数据库 (3) Connecting with SQLite database in PHP)

<?php
   class MyDB extends SQLite3 {
      function __construct() {
         $this->open('example.db');
      }
   }   
?>

Here, we are creating a new Class (myDB) which extends to the SQLite3 extension. __construct function is used to create an array that holds the example.db SQLite database.

在这里,我们正在创建一个扩展到SQLite3扩展的新类( myDB )。 __construct函数用于创建一个保存example.db SQLite数据库的数组。

翻译自: https://www.includehelp.com/php/php-code-to-connect-various-databases.aspx

php连接数据库代码

  • 3
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值