1

I have an SQL table I want to access called 'name_scraper' and to retrieve data between a set range to then return that resulting array to my node.js file for use. Essentially, Node js request, php $_GET[''], mysqli_query, then ?

this is my node js code to contact the php file

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(); 

Now the above code works in contacting my php file, which then outputs the array into console.

This is my 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

?>

This overall manages to retrieve the data but doesn't return the data in a usable form, the array is not an array returned, just part of the response. I need it to return the array in usable form so I can manipulate and extract data from within each index.

1 Answer 1

1

You should change your output method like below;

$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

Hope this helps

Sign up to request clarification or add additional context in comments.

3 Comments

It helps but still I cannot actually use the array returned in the node.js file, JSON.parse() just gives me an array full of objects and not the data
Does not objects includes your data ? @LorenzoMonsif
Figured out the problem, was just missing something super simple in the json, name_array = JSON.parse(chunk); name_array[0].Name;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.