I am trying to fetch data from my database, but when I visit MYWEBPAGE.com/service.php?id=2
(yes, there is an article with that id), then it just writes: [true]
, instead for showing me the objects as json.
Here is my code:
<?php
include('includingThis.php');
$idFromUrl = addslashes($_GET[id]);
$resultArray = array();
$tempArray = array();
if ($stmtTitle = $con->prepare("SELECT * FROM artikler WHERE id=?")) {
/* bind parameters for markers */
$stmtTitle->bind_param("i", $idFromUrl);
$stmtTitle->execute();
// Loop through each row in the result set
while($row = $stmtTitle->fetch()) {
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
</div>
The trouble you had is with using fetch
. It does not return a row, it returns a boolean. If you wish to get a row of * fields from a prepared statement (using mysqli
), you can do it one of two ways.
1) If you have mysqlnd
available:
You utilize get_result
first, then fetch_assoc
:
<?php
include('includingThis.php');
$resultArray = array();
if ($stmtTitle = $con->prepare("SELECT * FROM artikler WHERE id=?")) {
$stmtTitle->bind_param("i", $_GET['id']);// just put your GET var here
$stmtTitle->execute();
$stmtTitle_result = $stmtTitle->get_result();// get the result object
while($row = $stmtTitle_result->fetch_assoc()) {
$resultArray[] = $row;// add each row into resultArray directly
}
echo json_encode($resultArray);
}
?>
2) If you do NOT have mysqlnd
available:
You utilize bind_result
but must know every field you need: (change fieldnames to what YOUR field names are, not my examples of field
and field2
)
<?php
include('includingThis.php');
$resultArray = array();
if ($stmtTitle = $con->prepare("SELECT field1,field2 FROM artikler WHERE id=?")) {
$stmtTitle->bind_param("i", $_GET['id']);// just put your GET var here
$stmtTitle->execute();
$stmtTitle->bind_result($field1,$field2);// bind to each field
while($stmtTitle->fetch()) {
$resultArray[] = array('field1'=>$field1,'field2'=>$field2);// add each field
}
echo json_encode($resultArray);
}
?>
Incidentally, this is a bit easier (cleaner) using the PDO library.
you might not have mysql native driver installed on your server to use get_result(),try with bind_result()
<?php
include('includingThis.php');
$resultArray = array();
if ($stmtTitle = $con->prepare("SELECT value1,value2 FROM artikler WHERE id=?")) {
$stmtTitle->bind_param("i", $_GET['id']);// just put your GET var here
$stmtTitle->execute();
$stmtTitle->store_result();
$stmtTitle->bind_result($value1,$value2);
while($stmtTitle_result->fetch()) {
$resultArray->val1=$value1;
$resultArray->val12=$value2;
}
echo json_encode($resultArray);
}
?>