Codeigniter Count / If - php

this is taking me too long to figure out. I am using Codeigniter to query a database.
The model does this
function currentfunction($id)
{
$query = $this->db->get_where('mytable', array("id =" => $id));
if($query->num_rows() > 0){
return $query->result_array();
}else {
return false;
}
}
The controller
$this->load->model('Display');
$results = $this->Display->currentfunction($id);
$this->load->view('current_items', array('currentitems' => $results));
The view
foreach($currentitems as $row){
echo $row['name']
///....do more
}
works just fine EXCEPT IF no rows are returned
then
Message: Invalid argument supplied for foreach()...
How do I handle the if...else...scenario
I tried this Q-A, but doesn't work for me. PlsHlp.

Just do:
if(is_array($currentitems)) {
foreach($currentitems as $row){
echo $row['name']
///....do more
}
}
else
{
echo "No items in database!";
}
You are getting an error because foreach expects its first argument to be an array. If there are no items in the database however your functions returns false.

This is because when you run your code:
$query = $this->db->get_where('mytable', array("id =" => $id));
if($query->num_rows() > 0){
return $query->result_array();
}else {
return false;
}
when there are no rows returned the above code works fine it just doesnt work in the view where you try to run a for loop.
This for loop should not be run if there are no rows returned. yet you are trying to run a forloop even though there are no rows to work with.
My suggestion is changing the code like so:
$query = $this->db->get_where('mytable', array("id =" => $id));
if($query->num_rows() > 0){
return $query->result_array();
}else {
$noResults = true;
}
in the view you will have something like this before your for loop:
if($noResults != true){
foreach($currentitems as $row){
echo $row['name']
///....do more
}
}
else{
//do something
echo "No items in database!";
}
Hope this helps.
PK

Why don't you just do this:
function currentfunction($id)
{
return $this->db->get_where('mytable', array("id =" => $id));
}
In the view, if there are no results, an empty array will be returned and foreach won't throw an error:
foreach($currentitems->result_array() as $row)
{
echo $row['name']
///....do more
}
Much cleaner IMO.
If you want to show an error message in your view, you can do:
if($currentitems->num_rows() > 0)
{
foreach($currentitems->result_array() as $row)
{
echo $row['name']
///....do more
}
}
else
{
// Error message
}
This is better than checking if there are results with if/else twice, like halfdan and Pavan are suggesting.

Related

Message: Cannot use object of type stdClass as array in CodeIgnitor

I am using CodeIgniter, I am returning more than one value in the model so I did like
return array('true' =>1,'customer_id' => $result->customer_id);
and In the controller, I am displaying like
$true=$result['true'];
$custId=$result['customer_id'];
So there is no issue in this.
Now let's talk about in details
In the model, I have this logic
//sql query
if ($result) {
if ($result->password_change == 0) {
return array('true' =>1,'customer_id' => $result->customer_id);//multiple returns
}
else{
return $result;
}
}
else{return false;}
In the controller
$result=$this->Member_model->check_data(parameters);
$true=$result['true'];
$custId=$result['customer_id'];
if ($result) {
if($true == 1){
//some code here
}
else{
//some code here
}
}
else{
}
This is my second code.
if ($result) {
if ($result - > password_change == 0) {
if ($result - > id == $id) {
return array('true' => 1, 'customer_id' => $result - > customer_id); //return more then 2
} else {
return false;
}
} else {
if ()) // some condition
{
return (array) $result;
} else {
return false;
}
}
} else {
return false;
}
I am getting the error that
"Message: Cannot use object of type stdClass as array"
Because when returning if condition(from the model) then it's working but when it returns else (I mean $result from the model) then I am getting the error because it is not getting the $result['true'].
Hope you can understand my issue. Would you help me out on this issue?
You have two options. Either: ALWAYS return an array, or return an ArrayObject:
Alway return an Array
In your else, cast $result as an array:
//sql query
if ($result) {
if ($result->password_change == 0) {
return array('true' =>1,'customer_id' => $result->customer_id);//multiple returns
}
return (array) $result;
}
return false;
Always return an ArrayObject
Not knowing if this model is returning the result anywhere else in you application, I have no idea if other code expects $result to be an object. Casting as an array might break your code elsewhere. Let's convert $result from stdClass to an ArrayObject:
//sql query
if ($result) {
if ($result->password_change == 0) {
return array('true' =>1,'customer_id' => $result->customer_id);//multiple returns
}
return new \ArrayObject($result, \ArrayObject::ARRAY_AS_PROPS);
}
return false;
This approach will allow you to call $result['test'] AND $result->test.
Yeah, ok this is solution for multiple conditions :
$this->db->select('*'); // Here your column name
$this->db->from('members'); // Table name
$this->db->where($login_access); // Here your condition
$query = $this->db->get();
$result = $query->result_array();
$query = $this->db->get('customer'); // Your code above if condition
$result = $query->result_array(); // Get data in array Format using **result_array()**
if ($result) {
if ($query->num_rows() > 0) { // You have to change condition from **$result['password_change ']** To **$query->num_rows() > 0**
if ($result - > id == $id) { // Also change here condition from **$result - > id** To $result['id']
return array('true' => 1, 'customer_id' => $result['customer_id']); //Also change here from **$result - > customer_id** To $result['customer_id']
} else {
return false;
}
} else {
if () // some condition
{
return $result; // Also Change here from **return (array) $result** To $result
} else {
return false;
}
}
} else {
return false;
}

Show if propel successfully deleted related data

I have something like this
$table = TableQuery::create()
->findOneByTableId(1);
foreach($table->getSomeTables() as $item) { // SomeTable is a table linked with foreign-key
$table->removeSomeTable($item);
}
if($table->save()) {
echo "success";
}else {
echo "fail";
}
The problem here is that despite the $table having someTablesScheduledForDeletion and successfully removing it from database when calling method save(), save still returns 0, as if "0 records were changed", though some records are actually deleted.
The same thing goes if I attach more things in a similar way as I did with someTables
What I want to achieve with this is to just get information if these elements were successfully removed
You should just call ->delete() on $item, then you can use ->isDeleted() as intended.
For example:
$table = TableQuery::create()->findOneByTableId(1);
$deleted = 0;
foreach ($table->getSomeTables() as $item) {
$item->delete();
if ($item->isDeleted()) {
$deleted++;
}
}
if ($deleted > 0) {
echo "Rows deleted.";
} else {
echo "No rows deleted.";
}
Issuing another query may be useful. Is there some reason to avoid this?

How to handle empty array in codeigniter?

So these are my codes.
model
function read() {
$sql= "SELECT * from table WHERE name = 'rabin'";
$query = $this->db->query($sql);
$res = $query->result_array();
return $res;
}
controller
function show() {
$this->load->model("db");
$array['data'] = $this->db->read();
$this->load->view("page", $array);
}
view
foreach($data as $val) {
"<p>" . echo $val['name']; . "</p>"
"<p>" . echo $val['address']; . "</p>"
}
Here, when there are no records in the database satisfying the WHERE clause in the query, the model returns null and I get error saying $data expects parameter 1 to be array, null given. There are several methods to deal with this situation. But, what would be the best possible way to handle this situation ?
The problem is the foreach needs data provided by the database, but you didn't give them anyone.
So I will do this instead:
Model
function read() {
$this->db->where('name', 'rabin');
$res = $this->db->get('table');
return ($res->num_rows() > 0) ? $query->result_array() : false;
}
Controller
function show() {
// $this->(model_name)->(function);
$result = $this->db_model->read();
if ( $result ) {
// if there has data returns, load view
$array['data'] = $result;
$this->load->view('page', $array);
}
else {
// otherwise, show errors.
// you can handle by yourself
echo "no result!";
}
}
Use the Query Builder always to prevent from SQL Injection.
The Model returns the result_array, or false, so that you can handle the result.
Use $res->row_array() instead if your query result returns only one row. (like the certain one member).
You should rename your model from db to (example)db_model or other. The db will conflict with the system method.
The way to load function from model is $this->model_name->function_name for example, it should be $this->db_model->read().
You should load the model (if it is db_model) like $this->load->model('db_model') in public function __construct() { }.
In your model try out this
function read() {
$this->db->select()->from('table')->where('name', 'rabin');
$sql_stmt = $this->db->get();
return $sql_stmt->result();
}
and then to check you are getting the result - in your controller,
function show() {
$this->load->model("db");
$array= array( 'data' => $this->db->read());
$this->load->view("page", $array);
}
To view the result in your view file do print_r($data);
And then let me know what you get / result
In your view put if than else block with foreach loop in it. Smething like:
<?php if ($data != FALSE): ?>
<?php
foreach($data as $val)
{
"<p>" . echo $val['name']; . "</p>"
"<p>" . echo $val['address']; . "</p>"
}
?>
<?php else: ?>
<?php echo "There is no demanded data."; ?>
<?php endif; ?>
This is much like Benyi's answer with a little twist.
Probably you will eventually want the model to be able to look for names other than 'rabin'. So this shows how to accomplish that by passing a value to the model. Also, this model method always returns something useful to the controller.
function read($name)
{
$noRecords[] = array('name' => "No Results!", 'address' => "");
if(empty($name))
{
return $noRecords;
}
//Such a simple query does not require Query Builder which adds a
//lot of extra processing to get to the same place as this query statement
$sql = "SELECT * from table WHERE name = ?";
//This is a "bound" query that will escape the input to guard against injection attacks
$query = $this->db->query($sql, array($name));
$res = $query->result_array();
if($res->num_rows() > 0)
{
return $query->result_array();
}
else
{
// send the controller an array containing a little something to explain what happened
return $noRecords;
}
//the above if/else could also be expressed with this ternary
// return $res->num_rows() > 0 ? $query->result_array() : $noRecords;
}
The controller is now very light-weight.
function show()
{
$name = 'rabin'; //some data for the model
$array['data'] = $this->db_model->read($name);
$this->load->view('page', $array);
}
Your view is also greatly simplified
<?php foreach($data as $val): ?>
<p><?php echo $val['name']; ?>"</p>"
<p><?php echo $val['address']; ?>"</p>"
<?php endforeach; ?>

GET Multiple MySQL Rows, Form PHP Variables, and Put Into Json Encoded Array

I am trying to GET different rows from different columns in php/mysql, and pack them into an array. I am able to successfully GET a jason encoded array back IF all values in the GET string match. However, if there is no match, the code echos 'no match', and without the array. I know this is because of the way my code is formatted. What I would like help figuring out, is how to format my code so that it just displays "null" in the array for the match it couldn't find.
Here is my code:
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode($fbaddra);
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['addr'];
} else {
$fbaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['addr'];
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
UPDATE: The GET Request
I would like the GET request below to return the full array, with whatever value that didn't match as 'null' inside the array.
domain.com/api/core/engine.php?a=fbaddra&facebook=username&facebookp=pagename
The GET above currently returns null.
Requests that work:
domain.com/api/core/engine.php?a=fbaddra&facebook=username or domain.com/api/core/engine.php?a=fbaddra&facebookp=pagename
These requests return the full array with the values that match, or null for the values that don't.
TL;DR
I need assistance figuring out how to format code to give back the full array with a value of 'null' for no match found in a row.
rather than assigning as 'null' assign null. Your full code as follows :
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode('no match');
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
You can even leave else part altogether.
Check your code in this fragment you not use same names for variables:
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = 'null';
}
$fbaddr not is same as $fpaddr, this assign wrong result to if statement.
It was the mysql query that was the problem.
For those who come across this, and need something similar, you'll need to format your query like this:
** MYSQL QUERY **
if ($_GET['PUTVALUEHERE']) {
$g = $_GET['PUTVALUEHERE'];
$gq = $mysqli->real_escape_string($g);
$q1 = "SELECT * FROM `addrbook` WHERE `facebookp` = '".$gq."' OR `facebook` = '".$gq."'";
}
** PHP CODE **
if($_GET['PUTVALUEHERE']{
echo json_encode($row['addr']);
}

return and echo my array from a function

I have a function that returns either a value into a variable if it is successful or it returns an errors array. see part of it below.
function uploadEmploymentDoc($var, $var2){
$ERROR = array();
if(empty($_FILES['file']['tmp_name'])){
$ERROR[] = "You must upload a file!";
}
//find the extensions
$doctypeq = mysql_query("SELECT * FROM `DocType` WHERE `DocMimeType` = '$fileType'");
$doctype = mysql_fetch_array($doctypeq);
$docnum = mysql_num_rows($doctypeq);
if($docnum == 0){
$ERROR[] = "Unsupported file type";
}
if(empty($ERROR)){
// run my code
return $var;
} else{
return $ERROR;
}
then when I run my code
$result = uploadEmploymentDoc(1, 2);
if($result !=array()){
// run code
} else {
foreach($result as $er){
echo $er."<br>";
}
}
Now my question is this. Why is my function running my code and not showing me an error when I upload an unsupported document type. Am I defining my foreach loop correctly? For some reason I cant get my errors back.
you should write like this-
if(is_array($result)){
foreach($result as $er){
echo $er."<br>";
}
} else {
//your code for handling error
}
You can get more info :http://us2.php.net/is_array
Try use
$result = uploadEmploymentDoc(1, 2);
if(!is_array($result)){
// run code
} else {
foreach($result as $er){
echo $er."<br>";
}
}
Probably will be better add parameter by reference to function for the errors array. From function return "false" if error and value if no error occurred.

Categories