2 回答

TA贡献1802条经验 获得超4个赞
毕竟这是一个url,所以你可以使用parse_url函数来提取数据。
// 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]);
对于数据库连接,您应该始终使用 PDO 而不是 mysqli 驱动程序。PDO 允许您连接到几乎任何数据库,在 85% 的情况下无需重写代码。
不要忘记选项[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
,这将使您能够捕获任何错误并根据应用程序的需要进行相应的处理。
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
了解有关 PDO 的更多信息: https ://www.php.net/manual/en/class.pdo.php

TA贡献1900条经验 获得超5个赞
<?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 关注
- 93 浏览
添加回答
举报