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連接數據庫代碼