包含php文件的变量

问题描述:

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

网站文件看起来是这样的:

<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文件的下部分的数据。

+1

请发布dbcon.php – David

+0

当你说“我无法访问html文件下半部分的数据”时,你是什么意思? –

+2

[请停止使用mysql_ *函数](http://*.com/q/12859942/1238019),它们[已正式弃用](https://wiki.php.net/rfc/mysql_deprecation) 。相反的,对[预处理语句(http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html)看看,然后用[mysqli的(HTTP:/ /php.net/manual/en/book.mysqli.php)或[PDO](http://php.net/manual/en/book.pdo.php)。 – zessx

你的代码是“正确的”,因为你不需要任何更多的东西来访问你的变量。

但你混合mysql_mysqli_语法:

  • mysql_query采取的第一个参数查询,没有了连接
  • mysqli_query就拿第一个参数了连接,并查询作为第二个

你应该使用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(); 
} 
+0

谢谢,就是这么做的。我的包括也没有工作。 – szpar

不使用mysql_功能,它depricated。
无论如何你使用错误的变量名称。 $results_querymysql_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); 

?> 
+0

'mysql_query($ con,$ query);'无效,它应该引发一个错误。 – zessx

+0

你是真的,我更新我的答案。 – DS9