所以我第一次尝试 AJAX,我很兴奋!我有一个名为 ajaxtest1.html 的文件,它只有一个简单的文本框,其中输入了里程数,然后传递到另一个文件,它接收它,将其放入查询中并发回结果。这是ajaxtest1 ...
<html>
<body>
<script language="javascript" type="text/javascript">// <![CDATA[
function ajaxFunction(){
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
var miles = document.getElementById('miles').value;
var queryString = "?miles=" + miles;
ajaxRequest.open("GET", "results.php" + queryString, true);
ajaxRequest.send(null);
}
// ]]></script>
<form name="myForm">Miles: <input id="miles" type="text" /> <br /> <br /> <input onclick="ajaxFunction()" value="Query MySQL" type="button" /></form>
</body>
</html>
然后,在 results.php 中。我有
<?php
$hostname = 'host';
$username = 'user';
$password = 'password';
$miles = $_GET['miles'];
try {
$dbh = new PDO("mysql:host=$hostname;dbname=ratetable", $username, $password);
echo 'Connected to database<br />';
$stmt = $dbh->prepare('SELECT * FROM rates WHERE mileage <= :miles ORDER BY mileage DESC LIMIT 1');
$stmt->bindParam(':miles', $miles, PDO::PARAM_INT);
if ($stmt->execute()) {
// get the rowcount
$numrows = $stmt->rowCount();
if ($numrows > 0) {
// match
// Fetch rows
$rowset = $stmt->fetchAll();
}
else {
// no rows
}
}
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Mileage</th>";
$display_string .= "<th>Rate Per Mile</th>";
$display_string .= "<th>Inbound skid rate</th>";
$display_string .= "<th>Inbound truckload</th>";
$display_string .= "</tr>";
while($row_object = array($miles)){
$display_string .= "<tr>";
$display_string .= "<td>$row[mileage]</td>";
$display_string .= "<td>$row[ratepermile]</td>";
$display_string .= "<td>$row[skidinbound]</td>";
$display_string .= "<td>$row[truckinbound]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $stmt . "<br />";
$display_string .= "</table>";
echo $display_string;
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
[更新]
我对使用 PDO 很陌生(嗯,一般来说是 PHP,我正在接受它。)
我收到以下错误:
Catchable fatal error: Object of class PDOStatement could not be converted to string
这发生在以下行上:
echo "Query: " . $stmt . "<br />";
它连接到数据库很好。有人可以告诉我可能出了什么问题吗?当它试图形成 PDO 语句时,我有点想它,这样它就可以处理我的查询,而且它在最后一点就窒息了。
我已经更新了 PHP 代码以向您展示我尝试过的内容。
谢谢你看。