我想将我的HTML页面连接到我的数据库,但我不知道为什么。代码有什么问题?
<?php
$con = mysqli_connect("localhost","root","","sibd02");
$query = sprintf("SELECT*FROM fornecedor ",
$result = mysql_query($query);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
答案 0 :(得分:2)
您的代码存在很多问题。这是我清理过的代码版本,应该可以使用:
// Set the connection or die returning an error.
$con = mysqli_connect("localhost", "root", "sibd02") or die(mysqli_connect_errno());
// Set the query.
$query = "SELECT * FROM fornecedor";
// Run the query.
$result = mysqli_query($con, $query) or die(mysqli_connect_errno());
// Print the result for initial testing.
echo '<pre>';
print_r($result);
echo '</pre>';
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
因此,让我们看看您的原始代码,并在每个问题上注明以下内容:
$con = mysqli_connect("localhost","root","","sibd02");
$query = sprintf("SELECT*FROM fornecedor ",
$result = mysql_query($query);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
$query = sprintf("SELECT*FROM fornecedor ",
在PHP中是不正确的语法。并且不需要sprintf
。SELECT*FROM fornecedor
SELECT*FROM
应该有这样的空格SELECT * FROM
。mysqli_connect
进行连接,然后使用mysql_query
进行查询。这些是不同类别中两个100%不同的功能。像这样混合它们将永远不会奏效。答案 1 :(得分:0)
混合 MySQL 和 MySQLi 无法正常工作。你可以这样做:
<?php
/* ESTABLISH CONNECTION */
$con=mysqli_connect("localhost","root","","sibd02");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
$query = "SELECT * FROM fornecedor";
$result = mysqli_query($con,$query); /* EXECUTE QUERY */
/* IF YOU WANT TO PRINT THE RESULTS, HERE IS AN EXAMPLE: */
while($row=mysqli_fetch_array($result)){
echo $row['column']." ".$row['column2']." ".$row['column3']; /* JUST REPLACE THE NECESSARY COLUMN NAME */
} /* END OF WHILE LOOP */
mysqli_close($con);
?>