用PHP连接到我的数据库

时间:2014-06-06 02:19:03

标签: php mysql database connection

我想将我的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);


?>

2 个答案:

答案 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
  • 然后你的MySQL查询会失败,因为它有自己的语法错误: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);

?>