user2562125
user2562125

Reputation: 175

Json encode a php mysql query

I am having issues with a $json variable in my code. For some reason, my php query isn't being encoded into my $json variable.

$sql = "SELECT `$column`, `Year`, `Month` FROM unemployed WHERE year BETWEEN ? AND ? and month= ?";

$stmt = $conn->stmt_init();
$stmt->prepare($sql); 
$stmt->bind_param('sss', $gYear, $gYear2, $gMonth);
$stmt->bind_result($Column, $year, $month);
$stmt->execute();
$stmt->store_result();
$numRows = $stmt->num_rows;
$json = array();

if ($numRows) { ?>

<table>
<tr>
<th scope="col"> Hi </th>
<th scope="col"> Year </th>
<th scope="col"> Month </th>
</tr>

<?php while ($row = $stmt->fetch()) { ?>
<tr>
<td> <?php echo $Column; ?> </td>
<td> <?php echo $year; ?> </td>
<td> <?php echo $month; ?> </td>
</tr> 
$json['unemployed'][]= $row;
<?php } ?>
</table>
<?php
echo json_encode($json);
var_dump($json);
?>

After running this script, there still isn't anything in my $json variable. Does anyone know why that is? Shouldn't the variable now be an array with my query values (each row would now be part of an array)?

Upvotes: 0

Views: 363

Answers (2)

Rickkwa
Rickkwa

Reputation: 2291

It doesn't even look like

$json['unemployed'][]= $row;

is within php tags.

Also, it looks like fetch() returns boolean. When you call fetch(), it looks like it fills the variables $Column, $year, and $month with the values from the row. So instead of

$json['unemployed'][]= $row;

Do this:

$json['unemployed'][]= array($Column, $year, $month);

Upvotes: 1

Ohgodwhy
Ohgodwhy

Reputation: 50787

The issue is that you're outside of the scope of the PHP interpreter when attempting to parse the PHP code.

</tr> 
$json['unemployed'][]= $row;

to

</tr> 
<?php $json['unemployed'][]= $row; ?>

Upvotes: 0

Related Questions