包含php文件的变量

时间:2013-11-26 10:41:07

标签: php mysql include

我目前有一个带有html代码的php文件。在body标签的开头,我包括一个dbcon.php,它包含一个db连接,一个查询和一个fetch_result。我现在想在html文件中稍后使用这些结果,但我无法让它工作。

网站文件如下所示:

<html>
<head>...</head>
<body>
<?php include("dbcon.php"); ?>
...
<some html stuff>
...
<? here i want to use the data from the query ?>
...
</body></html>

dbcon.php只包含连接,查询和fetch_results。

编辑: dbcon:

<?php

$con=mysql_connect("localhost:8889","user","pw","db");
$result_query = mysql_query($con,"SELECT * FROM table");
$results = mysql_fetch_array($results_query);

?>

我无法访问html文件下半部分的数据。

2 个答案:

答案 0 :(得分:0)

您的代码是“正确的”,因为您无需再访问dbcon.php个变量。

但是你混合了mysql_mysqli_语法:

  • mysql_query将查询作为第一个参数,而不是连接
  • mysqli_query将第一个参数作为connexion,将查询作为第二个参数

您应该使用mysqli_

$con = mysqli_connect("localhost:8889","user","pw","db");
$result_query = mysqli_query($con, "SELECT * FROM table");
$results = mysqli_fetch_array($results_query);

另一个版本,面向对象:

$mysqli = new mysqli("localhost:8889", "user", "pw", "db");
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}
$results = array();
if ($result_query = $mysqli->query("SELECT * FROM table")) {
    $results = $result_query->fetch_array();
} 

答案 1 :(得分:0)

不要使用mysql_功能,不推荐使用。
无论如何你使用错误的变量名称。 $results_query中的mysql_fetch_array($results_query)因此将其更改为$result_query,它可能会有效。

<?php

$con=mysql_connect("localhost:8889","user","pw","db");
$result_query = mysql_query("SELECT * FROM table");
$results = mysql_fetch_array($result_query );

?>
相关问题