我有一个我想访问的SQL表名为' name_scraper'并在一个设定范围之间检索数据,然后将生成的数组返回到我的node.js文件以供使用。基本上,Node js请求,php $ _GET [''],mysqli_query,然后?
这是我的节点js代码联系php文件
var request = require('request');
var http = require('http');
var post_options = {
host: 'localhost',
path: '/name_request.php?pos1=0&pos2=5',
method: 'POST',
headers: {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded',
}
};
var post_req = http.request(post_options, function (res) {
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
chnk = chunk;
console.log("chunk: " +chnk[0]); //random test I did that doesn't work
});
});
post_req.end();
现在上面的代码可以联系我的php文件,然后将该数组输出到控制台。
这是我的php:
$servername = "localhost"; //localhost
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$start = $_GET['pos1'];
$end = $_GET['pos2'];
$sql = mysqli_query($conn, "SELECT * FROM name_scraper WHERE ID BETWEEN '$start' AND '$end'");
$array = mysqli_fetch_all($sql);
print_r($array); //can change to specific index and it works fine
?>
这总体上设法检索数据但不以可用的形式返回数据,该数组不是返回的数组,只是响应的一部分。我需要它以可用的形式返回数组,这样我就可以在每个索引中操作和提取数据。
答案 0 :(得分:1)
您应该更改输出方法,如下所示;
$sql = mysqli_query($conn, "SELECT * FROM name_scraper WHERE ID BETWEEN '$start' AND '$end'");
$array = mysqli_fetch_all($sql,MYSQLI_ASSOC); //If you add MYSQLI_ASSOC your output will be better
echo json_encode($array); //That will output an json array
希望这有帮助