PHP: JSON Returning NULL Values - php

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.

Related

unable to insert multiple array data from dynamic generated field?

I am unable to enter multiple data, it enter only single data. I have tried using for loop and then entering data, using 3 user and 2 task, there is an error previously offset.
public function add($postData)
{
// dd($postData);
$c = count($postData['user_name']);
$t = count($postData['task_name']);
for ($i = 0; $i < $c; $i++) {
$user_name = $postData['user_name'][$i];
$user_email = $postData['user_email'][$i];
$data['insert']['user_name'] = $user_name;
$data['insert']['user_email'] = $user_email;
}
for ($j = 0; $j < $t; $j++) {
$task_name = $postData['task_name'][$j];
$data['insert']['task_name'] = $task_name;
}
$data['insert']['name'] = $postData['name'];
$data['insert']['description'] = $postData['description'];
$data['insert']['customer_name'] = $postData['customer_name'];
$data['insert']['billing_method'] = $postData['billing_method'];
$data['insert']['dt_created'] = DT;
$data['table'] = PROJECT;
$result = $this->insertRecord($data);
if ($result == true) {
$response['status'] = 'success';
$response['message'] = 'Project created';
} else {
$response['status'] = 'danger';
$response['message'] = DEFAULT_MESSAGE;
}
return $response;
}
As Per lack of question details attached, I am supposing that you want to insert multiple task entry with project name, description etc.
Here is updated code:
<?php
// dd($postData);
$username = $postData['username'];
$user_email = $postData['user_email'];
$task_name = $postData['task_name'];
foreach ($username as $key => $value) {
$data['insert']['name'] = $postData['name'];
$data['insert']['description'] = $postData['description'];
$data['insert']['customer_name'] = $postData['customer_name'];
$data['insert']['billing_method'] = $postData['billing_method'];
$data['insert']['username'] = $value;
$data['insert']['user_email'] = $user_email[$key];
$data['insert']['task_name'] = $task_name[$key];
$data['insert']['dt_created'] = DT;
$data['table'] = PROJECT;
$result = $this->insertRecord($data);
}

How I can do this PHP If Statement in right way?

I have 50 variables in php. I want to check each of them and if they true then add 2 points in a variable called $point. I am new so I write a few lines but I think I am doing wrong way.
$strenght_point = 0;
if($f_name){$strenght_point++;}
if($l_name){$strenght_point + 2;}
if($full_name){$strenght_point + 2;}
How can I do it right way.Thanks
Update my full function is here...
It's Codeigniter Controller Function
Hope you guys understand well now
function strength_scale() {
$user_id = $this->uri->segment(2);
$user_name = $this->uri->segment(3);
$query = $this->db->get_where('aoa_user', array('id' => $user_id, 'username' => $user_name));
foreach ($query->result() as $row){
$f_name = $row->f_name;
$l_name = $row->l_name;
$full_name = $row->full_name;
$username = $row->username;
$alias_name = $row->alias_name;
$gender = $row->gender;
$country = $row->country;
$avatar = $row->avatar;
$cover_photo = $row->cover_photo;
$email = $row->email;
$skill = $row->skill;
$other_skills = $row->other_skills;
$ex_time = $row->ex_time;
$about = $row->about;
$company = $row->company;
$company_position = $row->company_position;
$phone = $row->phone;
$facebook = $row->facebook;
$facebook_page = $row->facebook_page;
$google_plus = $row->google_plus;
$twitter = $row->twitter;
$youtube = $row->youtube;
$skype = $row->skype;
$linkedin = $row->linkedin;
$website = $row->website;
$latitude = $row->latitude;
$longitude = $row->longitude;
$verification = $row->verification;
}
$strength_point = 0;
if($f_name){$strength_point++;}
if($l_name){$strength_point + 2;}
if($full_name){$strength_point + 2;}
}
Create an array with the variables instead.
https://3v4l.org/FYTtG
$arr = array("f_name" => true, "l_name" => true, "full_name" => true);
$strength=0;
Foreach($arr as $var){
if($var) $strength = $strength+2;
}
Echo $strength;
As Rizier123 said, you need to increment your strength variable correcly.
You could write a simple function that would accept one of your 50 variables and return the strength increment:
function defineStrength($param)
{
if ($param) {
return 2;
}
return 0;
}
$strength = 0;
$f_name = true;
$l_name = false;
$full_name = false;
$strength += defineStrength($f_name);
$strength += defineStrength($l_name);
$strength += defineStrength($full_name);
However, an array would be a better way to go, as Andreas mentionned.
In your question update you said you use CodeIgniter. As the documentation states you can return the query result as a pure array.
So you could further develop like that :
function defineStrengthFromArray(array $row)
{
$strength = 0;
foreach ($row as $param) {
$strength += defineStrength($param);
}
return $strength;
}
foreach ($query->result_array() as $row){
$strength = defineStrengthFromArray($row);
}

Access return value from result() function

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;

PHP: When using explode() twice, how to auto increase

I was trying something but I need to explode it twice because I store 2 variables in a string. Anyways, I used a while loop but I don't understand, I use cid++, but it does not appear to increase. ANyways, here's the code.
$cid = 0;
while($row = mysql_fetch_array($result)){
$comment = explode("-", $row['comments']);
$madeby = explode("///", $comment[$cid]);
$cid++;
echo $madeby[1];
}
Since you're setting a var and incrementing you can use it as a key for both arrays.
$cid = 0;
while($row = mysql_fetch_array($result)){
$comment[$cid] = explode("-", $row['comments']);
$madeby[$cid] = explode("///", $comment[$cid]);
echo $madeby[$cid][1];
$cid++;
}
Then you can do this:
foreach($madeby as $key=>$tempArr){
echo '"'.$madeby[$key][0].'" by "'.$madeby[$key][1].'"<br>';
}
To see the whole array:
print_r($madeby);
try this
while($row = mysql_fetch_array($result))
{
$comment = explode("-", $row['comments']);
foreach($comment as $each_comment)
{
$madeby = explode("///", $each_comment);
echo $madeby[1];
}
}
or if you really want to use cid then
while($row = mysql_fetch_array($result))
{
$comment = explode("-", $row['comments']);
for($cid=0;$cid<count($comment);$cid++)
{
$madeby = explode("///", $comment[$cid]);
echo $madeby[1];
}
}
try this:
while($row = mysql_fetch_array($result)){
$comment = explode("-", $row['comments']);
$cnt = count($comment);
$madeby = array();
for($cid=0; $cid<$cnt; $cid++){
$madeby[] = explode("///", $comment[$cid]);
}
print_r($madeby);
}

How to get the next row in mysqli result?

I want to get the next row in a cycle of a mysql result to write a list with the next and previous element code like this example:
<?php $previous = null;
$next = null;
while ($row = $result->fetch_assoc()) {
$next = ??????????????? // how to get it?
?>
<li code="<?php echo $row['code']; ?>" previous="<?php echo $previous; ?>" next="<?php echo $next; ?>">Hello world!</li>
<?php
$previous = $row['code']; // previous is easy to get...
} ?>
Not sure with MySQLi but here is how I do it in PDO:
$data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
for($i = 0; $i < count($data); $i++) {
$next = isset($data[$i+1]) ? $data[$i+1] : null;
}
if there is no fetchAll in mysqli then do:
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
if ( ! empty($data)) {
for($i = 0; $i < count($data); $i++) {
$next = isset($data[$i+1]) ? $data[$i+1] : null; // next
$prev = isset($data[$i-1]) ? $data[$i-1] : null; // previous
$curr = isset($data[$i]) ? $data[$i] : null; //current
}
}
How about something on the lines of this:
SELECT * FROM table WHERE id > '$currentID' ORDER BY id LIMIT 1;
to get the single next possible row.
Look at this solution, what do you think about it? it works, but will be more slow? this algorithm requires at least double pass or not? what do you think?
$db = DB::getConnection();
$result = $db->query( "SELECT * FROM objects" );
$next = null;
$previous = null;
$temp_previous = null;
$print = false;
$row = null;
$fetchit = false;
$code = null;
echo "<ul>";
while (true)
{
if ($print) {
if ($fetchit) {
$row = $result->fetch_assoc();
$next = $row['code'];
}
echo "<li code='$code' next='$next' previous='$previous'>{$row['description']}</li>" . endl();
$previous = $temp_previous;
$print = false;
}
else {
if (!$fetchit)
$row = $result->fetch_assoc();
$code = $row['code'];
$temp_previous = $row['code'];
$print = true;
$fetchit = true;
}
if(!is_array($row)) break;
}
echo "</ul>";

Categories