I'm neubie with PHP. I need to build some Web Service so, I have problems.. please help me.
I have this code, I have to put in array the Select's records and the return in JSON.
The CODE...
function redeem() {
// Check for required parameters
if (isset($_POST["id_cliente"]) && isset($_POST["id_sucursal"])) {
// Put parameters into local variables
$cliente = $_POST["id_cliente"];
$sucursal = $_POST["id_sucursal"];
$stmt = $this->db->prepare('SELECT id_arbitro FROM arbitro WHERE id_cliente =? AND id_sucursal =?') or die(mysqli_error($this->db));
$stmt->bind_param("ii", $cliente, $sucursal);
$stmt->execute();
//$stmt->bind_result($id_arbitro);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$cuantos = count($result);
echo "$cuantos";
$registros = 0;
/*while ($stmt->fetch()) {
$registros ++;
// Return unlock code, encoded with JSON
$result = array("id_arbitro" => $stmt,);
echo "$id_arbitro !";
}
*/
$stmt->close();
if ($registros < 0) {
sendResponse(400,"No existen arbitros con los parĂ¡metros recibidos");
return false;
}
//echo json_encode($result);
sendResponse(200, "FIN");
//printf("ERROR %s",$registros);
return true;
}
sendResponse(400, 'Invalid request');
return false;
}
To encode the results of your query, use something like that
$statement=$pdo->prepare("SELECT * FROM table");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
Based on your comment, you're having trouble understanding how to put them all into an array.
First, make sure that whatever you use for database calls doesn't already have a fetchAll style function that could do this for you.
If you still need to do, you need to define an array first and then add to it:
$results = array();
while ($record = $stmt->fetch()) {
$registros ++;
$results[] = $record;
}
print json_encode($results);
The syntax might vary slightly for your database class but this gives you an idea.
Related
I've a class with viewData() method that pull the data from the DB table.
I want to return the data result array in Class and iterate the array in Object
I'm able to make it work with fetchAll() but couldn't figure it out how to return the result with fetch() using while loop.
<?php
class CrudClass{
private $db;
function __construct($DB_con){
$this->db = $DB_con;
}
/* DATA VIEW METHOD */
public function viewData(){
$sql = "SELECT * FROM tbl_users";
$stmt = $this->db->prepare($sql);
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
return $row; // it doesn't work
}
// below code is working
/*if($stmt->rowCount()>0){
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}*/
}
}
// instantiate an Object
$obj = new CrudClass($DB_con);
$rows = $obj->viewData();
foreach($rows as $row) {
echo $row['first_name']. " ". $row['last_name'] ."<br>";
}
?>
The reason I want to do that way, because I don't want to pull the data at one go with fetchAll. Instead want to loop through each row at a time. Any help will be appreciated.
You should return array.
$result = []; // initiate the array
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
return $result[] = $row; // put each row in the result array
}
return $result; // return the result array
Now the whole method will look something like below
/* DATA VIEW METHOD */
public function viewData() {
$sql = "SELECT * FROM tbl_users";
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = []; // initiate the array
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
return $result[] = $row; // put each row in the result array
}
return $result; // return the result array
}
This way you are assured that even if there is no result set, only array will get returned.
If above doesn't work. Try following two solutions.
1.Test explicitly for false.
while(($row = $stmt->fetch(PDO::FETCH_ASSOC) !== false) {
return $result[] = $row; // put each row in the result array
}
2.Use foreach
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
return $result[] = $row; // put each row in the result array
}
It is possible to return something you can use in a foreach without having to preload all the results (i.e. using PDOStatement::fetchAll()) and without returning the PDOStatement itself -- if that's what you are trying to do.
Because PDOStatement implements Traversable you you can construct an IteratorIterator from the PDOStatement and return that.
class CrudClass
{
public function viewData()
{
$sql = "SELECT * FROM tbl_users";
$stmt = $this->db->prepare($sql);
$stmt->execute();
return new \IteratorIterator($stmt);
}
}
// instantiate an Object
$obj = new CrudClass($DB_con);
$rows = $obj->viewData();
foreach($rows as $row) {
echo $row['first_name']. " ". $row['last_name'] ."<br>";
}
Note that if you were try and foreach over $rows more than once, it will error because because the results of a PDOStatement cannot be rewound.
I have a php script which retrieves data from mysql db.
Everything works fine, but my problem is that this $result = $dao->joinedEvents($userId); returns an array of numbers and what I would like to do is to run this $secondResult = $dao->joinedEventsInfo($receivedIds); for every ID and this script I'm using right now returns data only for one ID.
This is part of my php script:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId); //This is getting the IDs array
if(!empty($result)) {
$receivedIds = $result["event_id"];
$ids = explode(",", $receivedIds);
foreach($ids as $id){
$secondResult = $dao->joinedEventsInfo($id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id" . $id;
}
}
} else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
And this is joinedEvents script:
public function joinedEvents($userId){
$returnValue = array();
$sql = "SELECT event_id from MyTable WHERE userId= '$userId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
This is joinedEventsInfo script:
public function joinedEventsInfo($eventId){
$returnValue = array();
$sql = "SELECT * FROM Events WHERE eventId = '$eventId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
Edit: Tha reason I need this is that I have two tables. In the first one I have just IDs and in the second one I have info. So first I need to get the IDs and then I need to get data for every ID I have just received.
Thank you very much , I'm totally stuck.
Based on the updated code snippets and the discussion below, it is found that $result is indeed an array, and the solution is:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId);
if(count($result)){
foreach($result as $array){
$event_id = $array['event_id'];
$secondResult = $dao->joinedEventsInfo($event_id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id: " . $event_id;
}
}
}else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
Have you tried array_map()?
That would allow you to call a php function on each member of an array easily.
Another way would be to use the common while ($row = mysql_fetch_array($result)) which would execute the code in the while loop for each row of your returned results. Note, you will likely have to change the mysql_fetch_array to something specific for your SQL connection.
I use this code to get rows from database.
// Prepare WC statement
$queryUP = $pdo->prepare("SELECT * FROM unitprices WHERE id_quot = :idQuotation");
// Execute Unit prices statement
$queryUP->execute(array(
'idQuotation' => $idQuotation
));
// How to check the results is empty or not ?
if (results) {
// foreach($queryUP as $rowup) {
//...
// }
} else {
// do another thing
}
I don't how to do to check if there is some results in the query before continuing the code ?
$queryUP = $pdo->prepare("SELECT * FROM unitprices WHERE id_quot = ?");
$queryUP->execute(array($idQuotation));
//here you go
$results = $queryUP->fetchAll();
if ($results) {
// foreach($results as $rowup) {
//...
// }
} else {
// do another thing
}
Hope you are doing your foreach in the template, not right in place as shown here.
If your memory allows you, you can fetch all:
$queryUP = $pdo->prepare("SELECT * FROM unitprices WHERE id_quot = :idQuotation");
$queryUP->bindParam(':idQuotation', $idQuotation, PDO::PARAM_STR);
$queryUP->execute();
$result = $queryUP->fetchAll(PDO::FETCH_ASSOC);
if (count($result) > 0) {
} else {
}
I am trying to fetch multiple rows in form of an array and then converting it to json
Heres my code :
public function getTest($standard,$chapid,$count)
{
if($count>0)
{
$stmt = $this->conn->prepare("SELECT question from questions where standard=? and chapterId=? ORDER BY rand()");
$stmt->bind_param("ss", $standard,$chapid);
$result=$stmt->execute();
echo $result;
$stmt->close();
$rows = $this->resultToArray($result);
echo json_encode($rows);// Array of rows
}
else
{
$rows["success"] = 0;
$rows["message"] = "Posts NOT Available!";
}
echo json_encode($rows);
}
public function resultToArray($result) {
$rows["success"] = 1;
$rows["message"] = "Post Available!";
$rows["posts"] = array();
while($row = $result->fetch_assoc()) // <--Getting ERROR OVER HERE
{
array_push($rows["posts"], $row);
}
return $rows;
}
I am new to php so I can't figure out why I am getting an error in resultToArray() function on while line.
You need to fetch the results of your query; fetch(PDO::FETCH_ASSOC) will return each result as an associative array:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
array_push($results, $row);
}
Your $result passed to your function resultToArray() is in fact a bool. You are passing the wrong variable.
I've searched and can't find an answer to my question.
I have the following code which is to loop through an array and then fetch back results for the different $id's.
The output when using echo json_encode($row); returns all results but the zend layout displays.
However when using $this->_helper->json($row,true); the layout doesn't display but only one result returns.
How can I return more than one result?
Any help would be much appreciated.
public function testAction()
{
//Get latest revision from database and loop through $id's
$id = array('308', '307', '306');
//Connect to database
foreach($id as $lId) {
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select('')
->from('LinktagRevisions')
->where('linktagId = ?', $lId)
->order('updated DESC')
->limit(1);
$stmt = $select->query();
while ($row = $stmt->fetch()) {
$this->_helper->json($row,true);
//Encode as json and echo result
// echo json_encode($row);
}
}
}
I think you can try this:
$result = array();
foreach($id as $lId) {
....
$stmt = $select->query();
$result[$lId] = $stmt->fetchAll();
}
$this->_helper->json($result,true);