I'm attempting to run a pdo query on a button click but I'm not getting any results back.
I have similar things like this in other files but I can't get this one to work. The page is refreshing but no data is showing. I'm assuming that the session array isn't being created but I'm not skilled enough in php to tell what is going on.
Index.php
<?php
session_start();
?>
<a href="#" id="show-data">
<table>
<thead>
<tr>
<th>Field One</th>
<th>Field Two</th>
<th>Field Three</th>
</tr>
</thead>
<tbody>
<?php
for ($i = 0; $i < count($_SESSION['data']); $i++)
{
echo '
<tr>
<td>' . $_SESSION['data'][$i]['FieldOne'] . '</td>
<td>' . $_SESSION['data'][$i]['FieldTwo'] . '</td>
<td>' . $_SESSION['data'][$i]['FieldThree'] . '</td>
</tr>
';
}
?>
</tbody>
</table>
<script>
$('#show-data').click(function() {
$.ajax({
url: 'php/functions.php',
data: { "function": "showData" },
complete: function (response) {
location.reload();
},
error: function() {
console.log("Error");
}
});
return false;
});
</script>
functions.php
<?php
session_start();
$DB_host = "localhost";
$DB_user = "me";
$DB_pass = "password";
$DB_name = "data";
$DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$DB_con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
if ($_GET["function"] == "showData")
{
showData();
}
function showData()
{
$stmt = $DB_con->prepare("SELECT * FROM data");
$stmt->execute();
$data = array();
if ($stmt->execute())
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$data[] = $row;
$_SESSION['data'] = $data;
}
}
}
?>