[英]Getting data out of a database with XMLHttpRequest, PDO, JSON, PHP and JavaScript
因此,在我提出最后一个问题之后,我想使用在输入标签中提交的值来获取数据库中的匹配ID。 我已经为此创建了两个文件,但是我不知道如何链接它们。 还要注意,我创建了一个具有几个值(id,名字等)的数据库,当用户填写1时,我希望它显示id 1和名字。
这段代码来自最后一个问题,我添加了xmlhttp:
Choose a number between 1 and 5 <input type='num' name="input" id="myid">
<p id='dbinfo'>Your info shall be shown here</p>
<button id="btn">Click me!</button>
<script>
var myButton = document.getElementById('btn');
myButton.onclick = function(){
alert(document.getElementById('myid').value);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if( xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var dbText = xmlhttp.responseText;
document.getElementById('dbinfo').innerHTML = dbText;
}
}
xmlhttp.open("POST", "LinkToDataFile", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
</script>
这是用户看到的,并且数字显示正确,但是我现在需要将其链接到我尝试过的文件data.php,但无法获取该值。
<?php
require_once('input_code');
//Get the data from the database and echo them here
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "db_name";
try
{
$connection = new PDO("mysql:host=".$servername.";dbname=".$databasename, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare("SELECT `id`, `firstname`, FROM `db_name` WHERE `id` = :myid"); //Here it needs to grab the value but it does not work.
$statement->bindParam(':id', $id);
$id = $_POST['id'];
$statement->execute();
$result = $statement->setFetchMode(PDO::FETCH_ASSOC);
$data = "";
foreach($statement->fetchAll() as $key => $value)
{
$data .= $value['id']." | ".$value['firstname'];
}
}
catch(PDOException $e)
{
echo "The following error occurded : ".$e->getMessage();
}
echo $data;
?>
那我在做什么错? 我是不是又一次错过了类似$ id的东西,还是一系列错误,现在唯一要做的就是给我一个带有数字的警报。 在此先感谢大家的帮助。
通过在D语句前添加一行并移动$ id可以解决所有问题,这要归功于Dante Javier
输入密码
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //Under this add the following lines:
var id = document.getElementById('myid').value;
xmlhttp.send("id="+id);
数据码
$id = $_POST['id']; //Move this above the $statement = $connection->prepare.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.