I'm currently using the following code to fetch some data from my database table and show it into a table. It's using PDO for database connection.
<tbody>
<?php $sql = "SELECT * from users
ORDER BY id DESC";
$query = $dbh->prepare($sql);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_OBJ);
$cnt = 1;
if ($query->rowCount() > 0) {
foreach ($results as $result) {
?>
<form action="manage-users.php" method="post">
<input type="hidden" name="uid" value="<?= $result->id ?>" />
<?php
$status = 1;
if ($result->status == 1) {
$status = 0;
}
?>
<input type="hidden" name="status" value="<?= $status ?>" />
<tr>
<td>
<?php echo htmlspecialchars($cnt); ?>
</td>
<td>
<?php echo htmlspecialchars($result->full_name); ?>
</td>
</tr>
</form>
<?php $cnt = $cnt 1;
}
} ?>
</tbody>
But I wanted to console log the fetched results, so I modified my code as below.
<tbody>
<?php $sql = "SELECT * from users
ORDER BY id DESC";
$query = $dbh->prepare($sql);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_OBJ);
$cnt = 1;
if ($query->rowCount() > 0) {
foreach ($results as $result) {
echo '<script type="text/javascript">' .
'console.log(' . $results . ');</script>';
?>
<form action="manage-users.php" method="post">
<input type="hidden" name="uid" value="<?= $result->id ?>" />
<?php
$status = 1;
if ($result->status == 1) {
$status = 0;
}
?>
<input type="hidden" name="status" value="<?= $status ?>" />
<tr>
<td>
<?php echo htmlspecialchars($cnt); ?>
</td>
<td>
<?php echo htmlspecialchars($result->full_name); ?>
</td>
</tr>
</form>
<?php $cnt = $cnt 1;
}
} ?>
</tbody>
But the issue is it's not showing any data or error in the console. Any help would be much appreciated.
CodePudding user response:
You can use json_encode()
to convert the PHP array into a JavaScript literal.
<?php
$sql = "SELECT * from users
ORDER BY id DESC";
$query = $dbh->prepare($sql);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_OBJ);
$results_js = json_encode($results);
?>
<script>
console.log(<?php echo results_js; ?>);
</script>
<?php