包含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文件的下部分的数据。
答
你的代码是“正确的”,因为你不需要任何更多的东西来访问你的变量。
但你混合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_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);
?>
请发布dbcon.php – David
当你说“我无法访问html文件下半部分的数据”时,你是什么意思? –
[请停止使用mysql_ *函数](http://stackoverflow.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