3

I am fetching record with drop down using ajax call but the problem is that it is fetching only one record while there are three records in the database

This is my PHP code:

<?php
include 'config/dbconfig.php';

$genid      = $_POST['id'];
$operatorId = $_POST['operatorId'];

$query = mysqli_query($con, "SELECT * FROM generatorrun WHERE generatorId='$genid' AND operatorId='$operatorId'");
while($result = mysqli_fetch_array($query)) {

    $turnOn           = $result['startTime'];
    $turnOff          = $result['endTime'];
    $datetime1        = new DateTime($turnOn);
    $datetime2        = new DateTime($turnOff);
    $interval         = $datetime1->diff($datetime2);
    $datedifference   = $interval->format('%Y-%m-%d %H:%i:%s');
    $startReading     = $result['startReading'];
    $endReading       = $result['endReading'];
    $dailyConsumption = $endReading - $startReading;

    $postData = array(
        "turnOn"           => $turnOn,
        "turnOff"          => $turnOff,
        "runningTime"      => $datedifference,
        "startReading"     => $startReading,
        "endReading"       => $endReading,
        "dailyConsumption" => $dailyConsumption,
    );
}

echo json_encode($postData);
?>

I have to fetch the values from MySQL and stored in an associative array and then encoding it with json_encode() function.

and this is the code for fetching the record in jquery:

<script>
$(document).ready(function () {
    $(".bg-yellow").hide();
    $(".bg-red").hide();
    $("#getGen").change(function () {

        var id = $('#getGen').val();
        var operatorId = $(".opid").val();
        $.ajax({
            type: "POST",
            url: 'getGenerator.php',
            data: {id: id, operatorId: operatorId},
            success: function (response) {
                var data = jQuery.parseJSON(response);
                $(".turnOn").html(data.turnOn);
                $(".turnOff").html(data.turnOff);
                $(".running").html(data.runningTime);
                $(".startReading").html(data.startReading);
                $(".endReading").html(data.endReading);
                $(".dailyConsumption").html(data.dailyConsumption);
                $(".bg-yellow").show();
                $(".bg-red").show();
            }
        });
    });
});
</script>

the problem is that it is fetching only one record and I have used while loop to iterate through all records which are in MySQL table but it is only fetching only one record

pravindot17
  • 1,199
  • 1
  • 15
  • 32
hotshot code
  • 173
  • 1
  • 10
  • 2
    `$postData[] = array(`. You know what `[]` means, right? – u_mulder Mar 28 '18 at 09:25
  • yes i have also tried with this way but the result is same – hotshot code Mar 28 '18 at 09:26
  • 1
    What does it means - the same? What do you see in a console? If you have array of items - you need to iterate over them. – u_mulder Mar 28 '18 at 09:28
  • 1
    Your script is wide open to [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) – RiggsFolly Mar 28 '18 at 10:00

3 Answers3

0

In your while loop you are assigning the variable. So every loop it overides the values. You must use array_push

$postData = array();
while($result=mysqli_fetch_array($query)){
$turnOn=$result['startTime'];
$turnOff=$result['endTime'];
$datetime1 = new DateTime($turnOn);
$datetime2 = new DateTime($turnOff);
$interval = $datetime1->diff($datetime2);
$datedifference=$interval->format('%Y-%m-%d %H:%i:%s');
$startReading=$result['startReading'];
$endReading=$result['endReading'];
$dailyConsumption=$endReading-$startReading;
  array_push($postData,array(
    "turnOn" => $turnOn,
    "turnOff" => $turnOff,
    "runningTime"=>$datedifference,
    "startReading"=>$startReading,
    "endReading"=>$endReading,
    "dailyConsumption"=>$dailyConsumption
    ));
  }
jerome
  • 695
  • 6
  • 20
0

You just need to define an array.

<?php
include 'config/dbconfig.php';

$postData = array();
$genid=$_POST['id'];
$operatorId=$_POST['operatorId'];

$query=mysqli_query($con,"SELECT * FROM generatorrun WHERE generatorId='$genid' AND operatorId='$operatorId'");

while($result = mysqli_fetch_array($query)) {

    $turnOn=$result['startTime'];
    $turnOff=$result['endTime'];
    $datetime1 = new DateTime($turnOn);
    $datetime2 = new DateTime($turnOff);
    $interval = $datetime1->diff($datetime2);
    $datedifference=$interval->format('%Y-%m-%d %H:%i:%s');
    $startReading=$result['startReading'];
    $endReading=$result['endReading'];
    $dailyConsumption=$endReading-$startReading;

    $postData[] = array(
        "turnOn" => $turnOn,
        "turnOff" => $turnOff,
        "runningTime"=>$datedifference,
        "startReading"=>$startReading,
        "endReading"=>$endReading,
        "dailyConsumption"=>$dailyConsumption
    );
}

echo json_encode($postData);
?>
pravindot17
  • 1,199
  • 1
  • 15
  • 32
0

try this:

include 'config/dbconfig.php';
$genid      = $_POST['id'];
$operatorId = $_POST['operatorId'];
$query = mysqli_query($con, "SELECT * FROM generatorrun WHERE generatorId='$genid' AND operatorId='$operatorId'");
$postData = array();
while($result = mysqli_fetch_array($query))
{

$turnOn           = $result['startTime'];
$turnOff          = $result['endTime'];
$datetime1        = new DateTime($turnOn);
$datetime2        = new DateTime($turnOff);
$interval         = $datetime1->diff($datetime2);
$datedifference   = $interval->format('%Y-%m-%d %H:%i:%s');
$startReading     = $result['startReading'];
$endReading       = $result['endReading'];
$dailyConsumption = $endReading - $startReading;

$postData[] = array( // this is you missed here
        "turnOn"           => $turnOn,
        "turnOff"          => $turnOff,
        "runningTime"      => $datedifference,
        "startReading"     => $startReading,
        "endReading"       => $endReading,
        "dailyConsumption" => $dailyConsumption,
);
}

It will give you multiple results sets.

narayansharma91
  • 2,273
  • 1
  • 12
  • 20