我在开始学习 PHP 时遇到了非常奇怪的问题。我已经在 MySQL 数据库中创建了包含一些数据的表,现在我想在网页中显示它们。
这是我遇到此问题的来源:
<?php
// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $con);
// I check the connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
// It always goes here
echo "Connected to database!";
}
// I am testing very simple SQL query.. there should be no problem
$result = mysql_query("SELECT * FROM cathegories", $con, $db);
if (!$result) {
// but it always dies
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
mysql_close($con);
?>
出了什么问题?
提前致谢!
最佳答案
您正在混合 mysql 和 mysqli。 尝试这样的事情:
<?php
$con= new mysqli("localhost","user","passwd","database");
if ($con->connect_errno){
echo "could not connect";
}
$select = "SELECT * FROM tablename";
if($result = $con->query($select)){
while($row = $result->fetch_object()){
echo $row->rowname."<br>";
}
}
else { echo 'no result'; }
$con->close();
?>
关于PHP:已连接到数据库,但 mysql_query 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23183771/