从数据库中获取,如JSON

时间:2018-01-28 17:23:24

标签: php arrays json

我正在尝试从我的数据库中获取数据,但是当我访问MYWEBPAGE.com/service.php?id=2时(是的,有一篇带有该ID的文章),那么它只是写道: [true],而不是将对象显示为json。

这是我的代码:



<?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);
?>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您遇到的问题是使用fetch。它不返回一行,它返回一个布尔值。如果您希望从准备好的语句中获取一行*字段(使用mysqli),您可以采用以下两种方式之一。

1)如果您有mysqlnd可用:

您首先使用get_result,然后使用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)如果您没有mysqlnd可用:

您使用bind_result但必须知道您需要的每个字段:(将字段名称更改为您的字段名称,而不是fieldfield2的示例

<?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);
}
?>

顺便说一句,使用PDO库会更容易(更干净)。

答案 1 :(得分:0)

您的服务器上可能没有安装mysql本机驱动程序以使用get_result(),请尝试使用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);
}
?>