【发布时间】:2015-06-28 19:15:33
【问题描述】:
我正在尝试发出 AJAX 请求,但未能构建正确的 php 文件。 我在 php_error.log 中收到此类错误。相同的 php 代码在通常的 html 文件中工作正常。
PHP Notice: Undefined variable: dbh
PHP Fatal error: Call to a member function prepare()
像这样包含 jQuery
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
AJAX:
$(function() {
$('.openbook').click(function() {
function testAjax(handleData) {
$.ajax({
url:'getopen.php',
success:function(data) {
handleData(data);
alert(data);
}
});
testAjax(函数(输出){ document.getElementById('#thiswindow').innerHTML = 输出; }); } } });
getopen.php:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
if ( isset( $_SESSION['login'] ) ) {
$login = $_SESSION['login'];
$id=$_SESSION['id'];
$username="root";
$password="root";
$hostname = "localhost";
$dbname= "kotik";
function testdb_connect ($hostname, $username, $password) {
$dbh = new PDO("mysql:host=$hostname;dbname=kotik", $username, $password);
return $dbh;
}
try {
$dbh = testdb_connect ($hostname, $username, $password);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
$title_select_query= $dbh -> prepare("SELECT title FROM books WHERE id = :id ORDER BY date DESC LIMIT 5,5 ");
$title_select_query ->execute(array(':id' => $id));
$title_select_query_result = $title_select_query->fetchColumn();
echo($title_select_query_result);
?>
</body>
</html>
这里有什么问题?我还尝试了 html+php 和 getopen.php 中的仅 php 结构。你能解释一下有什么区别吗?
编辑 2:AJAX 输出
编辑:根据一些变化:
<?php
session_start();
if ( isset( $_SESSION['login'] ) ) {
$login = $_SESSION['login'];
$id=$_SESSION['id'];
$username="root";
$password="root";
$hostname = "localhost";
$dbname= "kotik";
function testdb_connect ($hostname, $username, $password){
$dbh = new PDO("mysql:host=$hostname;dbname=kotik", $username, $password);
return $dbh;
}
try {
$dbh = testdb_connect ($hostname, $username, $password);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$title_select_query= $dbh -> prepare("SELECT title FROM books WHERE id = :id ORDER BY date DESC LIMIT 5,5 ");
$title_select_query ->execute(array(':id' => $id));
$title_select_query_result = $title_select_query->fetchColumn();
echo($title_select_query_result);
?>
</body>
</html>
【问题讨论】: