Getting a SQL table to display in a Hype element

@Chriswhardy

Not withstanding the arguments reflecting security.

Here’s an approach to get the results that you want from the files you’ve provided.

These are the changes needed for the PHP

<?php

$host = "localhost";
$user = "";
$pass = "";
$databaseName = "";
$userName = "'" . $_POST['user'] . "'"; // from the AJAX call in Hype. Also notice the added single quotes for SQL correct syntax

$con = mysqli_connect($host, $user, $pass, $databaseName);
 
// Check connection
if($con === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Attempt select query execution
$sql = "SELECT * FROM Users WHERE userName=$userName";
if($result = mysqli_query($con, $sql)){
    if(mysqli_num_rows($result) > 0){
        echo '<table style="width: 99%">'; // added a width here for the look.
            echo "<tr>";
                echo "<th>ID</th>";
                echo "<th>userName</th>";
                echo "<th>BMReading</th>";
                echo "<th>Insulin</th>";
            echo "</tr>";
        while($row = mysqli_fetch_array($result)){
            echo "<tr>";
                echo "<td>" . $row['id'] . "</td>";
                echo "<td>" . $row['userName'] . "</td>";
                echo "<td>" . $row['BMReading'] . "</td>";
                echo "<td>" . $row['Insulin'] . "</td>";
            echo "</tr>";
        }
        echo "</table>";
        // Free result set
        mysqli_free_result($result);
    } else{
        echo "No records matching your query were found.";
    }
} else{
    echo "ERROR: Was not able to execute $sql. " . mysqli_error($con);
}
 
// Close connection
mysqli_close($con);
?>

These needed for the Hype function

$.ajax({
	url: 'data.php',
	type: 'POST',
	dataType: 'HTML',
	data: {
		user: $('#user').val()
	},
	success: function (res) {  
		$('#resultBox').html(res);
	}
});
4 Likes