2 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超4個(gè)贊
畢竟這是一個(gè)url,所以你可以使用parse_url函數(shù)來提取數(shù)據(jù)。
// Connection string from environmental variable in heroku
$connectionStringHerokuEnv = 'mysql://g46w916ds134b8:639f463e@us-cdbr-east-03.cleardb.net/heroku_45fab1d19h35yetf?reconnect=true';
$parsed = parse_url($connectionStringHerokuEnv);
$dbname = ltrim($parsed['path']. '/'); // PATH has prepended / at the beginning, it needs to be removed
// Connecting to the database
$conn = new PDO("{$parsed['scheme']}:host={$parsed};$dbname={$dbname};charset=utf8mb4", $parsed['user'], $parsed['pass'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
對于數(shù)據(jù)庫連接,您應(yīng)該始終使用 PDO 而不是 mysqli 驅(qū)動程序。PDO 允許您連接到幾乎任何數(shù)據(jù)庫,在 85% 的情況下無需重寫代碼。
不要忘記選項(xiàng)[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
,這將使您能夠捕獲任何錯(cuò)誤并根據(jù)應(yīng)用程序的需要進(jìn)行相應(yīng)的處理。
PDO 接受此連接字符串driver: host=DATABASE_HOST;dbname=DATABASE_NAME; charset=DEFAULT_CHARSET(use utf8 whenever you can)
了解更多信息parse_url
: https: //www.php.net/manual/en/function.parse-url
了解有關(guān) PDO 的更多信息: https ://www.php.net/manual/en/class.pdo.php

TA貢獻(xiàn)1900條經(jīng)驗(yàn) 獲得超5個(gè)贊
<?php
$str = "mysql://g46w916ds134b8:639f463e@us-cdbr-east-03.cleardb.net/heroku_45fab1d19h35yetf?reconnect=true";
// If I correctly understanded 'mysql://login:passwd@host/dbname?some_params'
// data parsing from input string
$sp = explode('/', $str);
$sp1 = explode('@', $sp[2]);
$first_part_sp = explode(':', $sp1[0]);
$login = $first_part_sp[0];
$passwd = $first_part_sp[1];
$host = $sp1[1];
$dbname = explode('?', $sp[3])[0];
$connect_str = "mysql:host=$host;dbname=$dbname";
echo $connect_str." ".$login." ".$passwd;
// database access
$pdo = new PDO($connect_str, $user, $passwd);
?>
- 2 回答
- 0 關(guān)注
- 124 瀏覽
添加回答
舉報(bào)