jquery_stack
jquery_stack

Reputation: 261

Plot from mysql database

I'm trying to plot just a simple x-y line graph with the data obtained from a MySQL database. The code is the following one:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.3/jquery.flot.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
</head>
<body>
    <h3><b>Database</b></h3>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "prueba2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, username, password, email, x, y FROM user";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    echo "<table>
             <tr>
                 <th>ID</th>
                 <th>Username</th>
                 <th>Password</th>
                 <th>Email</th>
                 <th>X</th>
                 <th>Y</th>
               </tr>";
     // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "
             <tr>
                 <td>" . $row["id"]. "</td>
                 <td>" . $row["username"]. "</td>
                 <td>" . $row["password"]. "</td>
                 <td>" . $row["email"]. "</td>
                 <td>" . $row["x"]. "</td>
                 <td>" . $row["y"]. "</td>
            </tr>";
    }
    echo "</table>";
    $dataset1 = array();
    while ($row = $result->fetch_assoc()) {
        $dataset1[] = array(intval($row["x"]),intval($row["y"]));
    }
} else {
     echo "0 results";
}
$conn->close();
?>
<br>
<h3>Test plot</h2>
<div id="placeholder"></div>
<script type="text/javascript">
        var dataset1 = <?php echo json_encode($dataset1); ?>;
        $(function () {
             $.plot($("#placeholder"), [ dataset1 ]);
        });
</script>
</body>
</html>

The result I get is the table perfectly set but an empty Flot Chart plot. That's to say the data is loaded correctly but I'm not able to plot it or to store it in variables or maybe the flot charts syntaxis is not well/well placed. Any suggestions? Thanks!

Upvotes: 1

Views: 826

Answers (1)

Renzo
Renzo

Reputation: 27424

The problem is that the assignment to the array is done after the first while, that produces the rows for the html table, when the result has been already fetched by the server. So the second loop exit immediately without assigning anything.

You should do the assignment inside the first loop, after the echo statement.

Upvotes: 1

Related Questions