我正在使用phpMyAdmin + MySQL。
我创建了一个数据库,现在正在尝试在 PHP 脚本中建立连接。奇怪的是连接到数据库可以工作,所以我收到"连接到MySQL服务器"消息,但是在选择"宠物食品"数据库时,脚本显示"选择时死亡"。
知道为什么吗?谢谢,这是我的代码:
<?php
$user = 'localhost';
$pass = 'password';
$db_name = 'petfood';
$db_conn = new mysqli("localhost", $user, $pass, $db_name) or die("Cannot connect to DB");
echo "Connected to MySQL server";
mysql_select_db($db_name) or die("DIED at selection");
echo "Database Selected";
?>
找出差异:
$db_conn = new mysqli("localhost", $user, $pass, $db_name) or die("Cannot connect to DB");
^----
mysql_select_db($db_name) or die("DIED at selection");
^---
如果你有适当的调试,你会被告知这个问题:
mysql_select_db($db_name) or die(mysql_error());
^^^^^^^^^^^^^^
当您可以让系统告诉您出了什么问题时,切勿输出固定(无用)错误消息。
> 1:使用 mysql
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db("examples",$dbhandle) or die("Could not select examples");
$query = "SELECT name FROM mytable" ;
$result = mysqli_query($query);
2:使用Mysqli
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
$query = "SELECT name FROM mytable" ;
$result = mysqli_query($link, $query);