Access return value from result() function - php

Trying to get the result of my query send it back to controller and return it to a view and access it there. I can't seem to display the value at my view so I tried echoing out what I got as a result from controller. It keeps stating undefined offset 1...please tell me how to access model return value properly
Model
$output = $this->db->query("SELECT * from incoming ORDER BY incomingId LIMIT 20");
return $output->result();
Controller
$data = $this->search_form->searchIdIncoming($searchQuery);
echo $data[0][1];
$this->load->view("searchIncoming", $data);
View
if(isset($incomingId))
echo "Primary key is available";

Try
echo $data[0]["Your Database field name"]; instead of echo $data[0][1];
like
echo $data[0]["id"];

If you want to display the result from model in view the most appropriate way is like this:
1) Return the resultant records from the model as an array like:
$output = $this->db->query("SELECT * from incoming ORDER BY incomingId LIMIT 20");
return $output->result();
2) Access this value in Controller by calling the function for this model query say (as you have not detailed well, I am not sure which function you are using),
$data['details'] = $this->search_form->searchIdIncoming($searchQuery); // store the result in an array
and pass the array to the view
$this->load->view("searchIncoming", $data);
3) In the view file, you can display the records with
if(!empty($details))
{
foreach($details as $row)
{
if($row->incomingId!=0)
echo "Primary key is available";
...........
}
}

I finally made it work by replacing the result() function with the result_array() function in codeigniter added a few other stuff to properly get table functions but here's the result I got:
$rows[] = array();
$rows2[] = array();
$rows3[] = array();
$i = 0;
$companyName = $this->db->query("SELECT id, name from company");
foreach($companyName->result_array() as $row2){
$rows2[$i]['id'] = $row2['id'];
$rows2[$i]['name'] = $row2['name'];
$i++;
}
//get all company names
$i = 0;
$staffName = $this->db->query("SELECT id, surname, firstName, middleInitial from employee");
foreach($staffName->result_array() as $row3){
$rows3[$i]['id'] = $row3['id'];
$rows3[$i]['name'] = $row3['surname'].", ".$row3['firstName']." ".$row3['middleInitial'];
$i++;
}
//get all employee names
$i= 0;
$output = $this->db->query("SELECT * from incoming ORDER BY incomingId LIMIT 20");
if ($output->num_rows() > 0) {
foreach($output->result_array() as $row){
$count = 0;
$j = 0;
$rows[$i]['incomingId'] = $row['incomingId'];
$rows[$i]['referenceNo'] = $row['referenceNo'];
$rows[$i]['documentTypeId'] = $row['documentTypeId'];
$rows[$i]['documentDate'] = $row['documentDate'];
$rows[$i]['dateReceived'] = $row['dateReceived'];
$rows[$i]['sender'] = $row['sender'];
while($count < sizeof($rows2)){
if($rows2[$j]['id'] != $row['companyId']){
$j++;
}else{
$rows[$i]['companyName'] = $rows2[$j]['name'];
break;
}
$count++;
}
$j= 0;
$count = 0;
while($count < sizeof($rows3)){
if($rows3[$j]['id'] != $row['responsibleStaffId']){
$j++;
}else{
$rows[$i]['responsibleStaffName'] = $rows3[$j]['name'];
break;
}
$count++;
}
$rows[$i]['subject'] = $row['subject'];
$rows[$i]['actionDone'] = $row['actionDone'];
$rows[$i]['track'] = $row['track'];
$rows[$i]['completed'] = $row['completed'];
$rows[$i]['remarks'] = $row['remarks'];
$i++;
}
return $rows;
}
return false;

Related

How to assign array value into variable inside foreach loop in codeigniter

I have an array of users with different userIds and I am trying to loop these array using a foreach loop. Inside that loop I am calling a function to get values of each users by passing their userid into a function. But its only passing one index of array.
My code
public function getDailyReportTest($orgId, $date)
{
$query = $this->db->query("SELECT * FROM `organization_users` WHERE orgId='7'");
$timestamp = strtotime($date);
$day = date('l', $timestamp);
$data = array();
$i = 0;
foreach ($query->result_array() as $row) {
$data[$i]['date'] = $date;
$data[$i]['day'] = $day;
$data[$i]['user_id'] = $row['orgUserId'];
$data[$i]['user_name'] = $row['orgUserName'];
$data[$i]['workingHours'] = self::getUserWorkingHours($data[$i]['user_id'],$date);
$delayTime=self::getUserDelayTime($row['orgUserId'],$date);
$shortTime=self::getUserShortTime($row['orgUserId'],$date);
$overTime=self::getUserOverTime($row['orgUserId'],$date);
$data[$i]['delayTime'] =$delayTime;
$data[$i]['shortTime'] =$shortTime;
$data[$i]['overTime'] =$overTime;
$data[$i]['shift1_start'] = self::getUserShiftStartTime($row['orgUserId'], $date);
$i=$i+1;
}
//return $data;
print_r($data);
die();
}
public function getUserShiftStartTime($userId, $date)
{
$query = $this->db->query("SELECT * FROM `office_employee_assigned_shifts` WHERE employeeId='$userId' &&shiftdate='$date'");
$entry = $query->num_rows();
$data = $query->result_array();
if($entry==0)
{
return NULL;
}
else
{
$shiftId = $data[0]['shiftId'];
$shiftquery = $this->db->query("SELECT startTimeSpan, endTimeSpan FROM `office_shift_time` WHERE officeShiftId='$shiftId'");
$dataShift = $shiftquery->result_array();
$startSpan = $dataShift[0]['startTimeSpan'];
$endSpan = $dataShift[0]['endTimeSpan'];
$firstPunchQuery = $this->db->query("SELECT punchTime AS firstPunch FROM `employee_punch_log` WHERE punchDate='$date' && employeeId='140' && punchTime BETWEEN '$startSpan' AND '$endSpan' AND punchType='1' LIMIT 1");
$punchEntryCount = $firstPunchQuery->num_rows();
if($punchEntryCount>0)
{
$dataFirstPunch = $firstPunchQuery->result_array();
$firstPunchStartTime = $dataFirstPunch[0]['firstPunch'];
return $firstPunchStartTime;
}
else
{
return "AB";
}
}
// return $entry;
}
It only passes the $data[1]['user_id'].
I want to pass $data[0]['user_id'], $data[1]['user_id'], $data[2]['user_id'] to the function
named getUserShiftStartTime($userId, $date)
Any Help?
Thanks for the help in advance
Then pass the current variable to your method:
self::getUserShiftStartTime($data[$i]['user_id'], $date);

encode php recordset in custom format

I'm currently have a recordset created with dreamweaver and have encode the results in json format which work fine.
Recordset
$maxRows_rs_feeds = 3;
$pageNum_rs_feeds = 0;
if (isset($_GET['pageNum_rs_feeds'])) {
$pageNum_rs_feeds = $_GET['pageNum_rs_feeds'];
}
$startRow_rs_feeds = $pageNum_rs_feeds * $maxRows_rs_feeds;
mysql_select_db($database_vivalooks, $vivalooks);
$query_rs_feeds = "SELECT fname,lname FROM profile";
$query_limit_rs_feeds = sprintf("%s LIMIT %d, %d", $query_rs_feeds, $startRow_rs_feeds, $maxRows_rs_feeds);
$rs_feeds = mysql_query($query_limit_rs_feeds, $vivalooks) or die(mysql_error());
$row_rs_feeds= mysql_fetch_assoc($rs_feeds);
if (isset($_GET['totalRows_rs_feeds'])) {
$totalRows_rs_feeds = $_GET['totalRows_rs_feeds'];
} else {
$all_rs_feeds = mysql_query($query_rs_feeds);
$totalRows_rs_feeds = mysql_num_rows($all_rs_feeds);
}
$totalPages_rs_feeds = ceil($totalRows_rs_feeds/$maxRows_rs_feeds)-1;
do {
echo json_encode($row_rs_feeds);
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));
mysql_free_result($rs_feeds);
Recordset Results
{"fname":"Benjamin","lname":"Blay"}{"fname":"Alfread","lname":"Mark"}{"fname":"yaa","lname":"tiwaa"}
But i want the results to be encode like this rather
[{"fname":"Benjamin","lname":"Blay"},{"fname":"Alfred","lname":"Mark"},{"fname":"yaa","lname":"tiwaa"}]
Try
do {
$json[]=json_encode($row_rs_feeds);
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));
echo "[".implode(", ", $json)."]";
OR
do {
$rows[] = $row_rs_feeds;
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));
echo json_encode($rows);
You can change your loop to look like this:
echo "[";
$count = 0;
do {
if($count !== 0)
echo ",";
$count++;
echo json_encode($row_rs_feeds);
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));
echo "]";
$count is there just to skip first "," so you don't get [,{...},{...}] or you can put it like false/true... I just can't remember right now what is better in case you have 10k steps loop...
Try:
do {
$rows[] = $row_rs_feeds;
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));
echo json_encode($rows);

After adding pagination PHP function no longer displays mysql array data

I have made a PHP function that pulls data from a table (product_reviews) in my database, showing all reviews for a unique product_id. Here is the code:
function showReviews ($product_id)
{
include('database_conn.php');
$query = "SELECT * FROM product_reviews WHERE product_reviews.productID='".$product_id."'";
if ($queryresult = mysqli_query($conn, $query))
{
while ($currentrow = mysqli_fetch_assoc($queryresult))
{
$result_list[] = $currentrow;
}
foreach ($result_list as $currentrow)
{
$productitems[] = array(
$customer_forename = $currentrow['customer_forename'],
$customer_surname = $currentrow['customer_surname'],
$review_title = $currentrow['review_title'],
$review_text = $currentrow['review_text']);
echo '<article class="Review_Box">';
echo "<h3>".$review_title." by ".$customer_forename." ".$customer_surname."</h3></br>";
echo "<p>".$review_text."</p>";
echo "</article>";
}
}
}
This function is then called from the products page and it works as intended.
But when I add pagination to the function ( following an ehow tutorial), the function doesn't have any output(see here).
if(!function_exists('showReviews'))
{
function showReviews ($product_id)
{
include('database_conn.php');
include('functions.php');
$rowsPerPage = 3;
$currentPage = ((isset($_GET['page']) && $_GET['page'] > 0) ? (int)$_GET['page'] : 1);
$offset = ($currentPage-1)*$rowsPerPage;
$query = "SELECT * FROM product_reviews WHERE product_reviews.productID='".$product_id."' LIMIT '".$offset."','".$rowsPerPage."'";
if ($queryresult = mysqli_query($conn, $query))
{
while ($currentrow = mysqli_fetch_assoc($queryresult))
{
$result_list[] = $currentrow;
}
foreach ($result_list as $currentrow)
{
$productitems[] = array(
$customer_forename = $currentrow['customer_forename'],
$customer_surname = $currentrow['customer_surname'],
$review_title = $currentrow['review_title'],
$review_text = $currentrow['review_text']);
echo '<article class="Review_Box">';
echo "<h3>".$review_title." by ".$customer_forename." ".$customer_surname."</h3></br>";
echo "<p>".$review_text."</p>";
echo "</article>";
}
}
$count = countReviews (1);
$totalPages = $count/$rowsPerPage;
if($currentPage > 1)
{
echo 'Previous Page ';
}
if($currentPage < $totalPages)
{
echo 'Next Page';
}
}
}
I tested my sql query and it works fine in mysql Workbench.
What am I doing wrong? Can anyone recommend a better way to do this?
When you create your query, you are encapsulating the offset and limit between single quotes (if I read your code correctly).
SELECT * FROM product_reviews WHERE product_reviews.productID='25' LIMIT '0','3'
Try removing those single quotes.

PHP: JSON Returning NULL Values

I am currently working on a search function for my site and I returning the results in JSON. However, some values are returning after returning the first results like the following:
{"fullname":"test name","occupation":"test","industry":"testing","bio":"i am testing stuff.","gender":"f","website":"http:\/\/yhisisasite.com","skills":["writing","reading","math","coding","baseball"],"interests":["coding","sampling","googling","typing","playing"]},{"fullname":null,"occupation":null,"industry":null,"bio":null,"gender":null,"website":null,"skills":["coding","docotrs","soeku","spelling"],"interests":["testing","wintro","skating","hockey","code"]}
I currently have a class to work as a template for the results which looks like this:
class SearchResultUserProfile {
public $fullname = "";
public $occupation = "";
public $industry = "";
public $bio = "";
public $gender = "";
public $website = "";
public $skills = array();
public $interests = array();
}
Then to populate those fields I have a few loops during the mysqli fetch:
while ($row = mysqli_fetch_array($result))
{
$max = sizeof($user_id_array);
for($i = 0; $i < $max; $i++)
{
//create a new instance or object
$searchResultUserProfile = new SearchResultUserProfile();
$searchResultUserProfile->fullname = $row['fullname'];
$searchResultUserProfile->occupation = $row['occupation'];
$searchResultUserProfile->industry = $row['industry'];
$searchResultUserProfile->bio = $row['bio'];
$searchResultUserProfile->gender = $row['gender'];
$searchResultUserProfile->website = $row['website'];
//grab the interests and skills
$skillDetails = fetchAllUserSkills($user_id_array[$i]);
foreach($skillDetails as $row) {
$thistest = $row['skills'];
array_push($searchResultUserProfile->skills, $thistest);
}
$interestDetails = fetchAllUserInterests($user_id_array[$i]);
foreach($interestDetails as $row) {
$thistests = $row['interests'];
array_push($searchResultUserProfile->interests, $thistests);
}
array_push($results, $searchResultUserProfile);
}
echo json_encode($results);
}
Any idea why this is happening? Is it how I am iterating through the loop or the set up? I am sure I am overlooking something simple but I cannot figure out what it is.
The problem is that you are overwriting your $row variable in the inner loops:
while ($row = mysqli_fetch_array($result))
^^^^ this is a result row from your query
{
$max = sizeof($user_id_array);
for($i = 0; $i < $max; $i++)
{
$searchResultUserProfile = new SearchResultUserProfile();
$searchResultUserProfile->fullname = $row['fullname'];
...
foreach($skillDetails as $row) {
^^^^ here you are overwriting your query result
...
}
...
}
echo json_encode($results);
}
So if $max is more than 1, from the second iteration on you will be using the last result of your last inner loop. And that will not be the result from the query that you expect it to be.

PHP Add array items from an inner array loop

I am trying to build an array of cart items that has a mix of a la carte items and package deals. I want to pull the products from the packages and enter the products into my order table. Below is what I have. It pulls the data, but will only add the last record of the inner array (package products) to the outer array. The a la carte items are fine.
$sql = "SELECT id, item_id, package
FROM cart WHERE user_id = $userId";
$result = dbQuery($sql);
$arrCartContent = array();
while ($row = dbFetchAssoc($result)) {
if ($row['package'] == 1) {
// Add Product Credits to Company and Order
$arrProductData = fetchProductDataByPackage($row['item_id']);
$numItem = count($arrProductData);
if ($numItem > 0) {
for ($i = 0; $i < $numItem; $i++) {
extract($arrProductData[$i]);
$row['product_id'] = $product_id;
$row['description'] = $pack_product_name;
}
}
} else {
$itemDetails = fetchProductDetails($row['item_id']);
$row['product_id'] = $row['item_id'];
$row['description'] = $itemDetails['name'];
}
$arrCartContent[] = $row;
}
if(!empty($arrCartContent)) {
foreach ($arrCartContent as $cartData) {
$product_id = $cartData['product_id'];
$description = $cartData['description'];
$sqlInsert = "INSERT INTO shop_order_x_product
(order_id, product_id, description)
VALUES
($orderId, $product_id, '$description')";
$resultInsert = dbQuery($sqlInsert) or die('Cannot add order products: ' . mysql_error());
}
}
You mixed it up a bit, your general approach is fine, maybe streamlining it a bit will make this a breeze and prevent you from overwriting the $row variable inside the loop:
$arrCartContent = array();
while ($row = dbFetchAssoc($result))
{
if ($row['package'] == 1)
{
// Add Product Credits to Company and Order
$arrProductData = fetchProductDataByPackage($row['item_id']);
foreach($arrProductData as $productData)
{
$new = array();
$new['product_id'] = $productData['product_id'];
$new['description'] = $productData['description'];
$arrCartContent[] = $new;
}
}
else
{
$itemDetails = fetchProductDetails($row['item_id']);
$new = array();
$new['product_id'] = $row['item_id'];
$new['description'] = $itemDetails['name'];
$arrCartContent[] = $new;
}
}
You're overwriting the $row array elements with each iteration. Try...
if ($row['package'] == 1) {
// Add Product Credits to Company and Order
$arrProductData = fetchProductDataByPackage($row['item_id']);
$numItem = count($arrProductData);
if ($numItem > 0) {
for ($i = 0; $i < $numItem; $i++) {
extract($arrProductData[$i]);
$row['product_id'] = $product_id;
$row['description'] = $pack_product_name;
$arrCartContent[] = $row;
}
}
} else {
$itemDetails = fetchProductDetails($row['item_id']);
$row['product_id'] = $row['item_id'];
$row['description'] = $itemDetails['name'];
$arrCartContent[] = $row;
}

Categories