猿问

在 PHP 中连接 MySQL 数据库

我正在尝试建立一个博客网站。
它部署在 Heroku 上,并且应该连接到 MySQL 数据库。登录我的数据库所需的信息存储在 Heroku 上的环境变量中,如下所示(当然这些是假凭证):

mysql://g46w916ds134b8:639f463e@us-cdbr-east-03.cleardb.net/heroku_45fab1d19h35yetf?reconnect=true

它包含数据库名称、用户、密码和主机。

有没有一种方法可以直接在我的 PHP 代码中使用这个字符串来连接数据库?我检查了 MySQLi 和 PDO 文档,似乎它们只接受 DSN/用户/密码或主机/用户/密码/DBname 格式。


守着一只汪
浏览 94回答 2
2回答

慕虎7371278

毕竟这是一个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

梵蒂冈之花

<?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);?>
随时随地看视频慕课网APP
我要回答