我正在使用phpMyAdmin + MySQL。
我创建了一个数据库,现在正尝试在PHP脚本中建立连接。奇怪的是连接到数据库工作,所以我得到了连接到MySQL服务器"消息,但我在选择“宠物食品”时说。数据库,脚本显示" DIED在选择"。
知道为什么吗?谢谢,这是我的代码:
<?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";
?>
答案 0 :(得分:6)
发现差异:
$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 :(得分:-2)
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);