How to handle empty array in codeigniter? - php

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

Related

How do you make sure an array is empty in PHP?

Im writing a page in HTML/PHP that connects to a Marina Database(boats,owners etc...) that takes a boat name chosen from a drop down list and then displays all the service that boat has had done on it.
here is my relevant code...
if(isset($_POST['form1'])){//if there was input data submitted
$form1 = $_POST['form1'];
$sql1 = 'select Status from ServiceRequest,MarinaSlip where MarinaSlip.SlipID = ServiceRequest.SlipID and BoatName = "'.$form1.'"';
$form1 = null;
$result1 = $conn->query($sql1);
$test = 0;
while ($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$values1[] = array(
'Status' => $row['Status']
);
$test = 1;
}
echo '<p>Service Done:</p><ol>';
if($test = 1){
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
echo '</ol>';
}else{
echo 'No service Done';
}
the issue im having is that some of the descriptions of sevice are simply Open which i do not want displayed as service done, or there is no service completed at all, which throws undefined variable: values1
how would I stop my script from adding Open to the values1 array and display a message that no work has been completed if values1 is empty?
Try this
$arr = array();
if (empty($arr))
{
echo'empty array';
}
We often use empty($array_name) to check whether it is empty or not
<?php
if(!empty($array_name))
{
//not empty
}
else
{
//empty
}
there is also another way we can double sure about is using count() function
if(count($array_name) > 0)
{
//not empty
}
else
{
//empty
}
?>
To make sure an array is empty you can use count() and empty() both. but count() is slightly slower than empty().count() returns the number of element present in an array.
$arr=array();
if(count($arr)==0){
//your code here
}
try this
if(isset($array_name) && !empty($array_name))
{
//not empty
}
You can try this-
if (empty($somelist)) {
// list is empty.
}
I often use empty($arr) to do it.
Try this instead:
if (!$values1) {
echo "No work has been completed";
} else {
//Do staffs here
}
I think what you need is to check if $values1 exists so try using isset() to do that and there is no need to use the $test var:
if(isset($values1))
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
Or try to define $values1 before the while:
$values1 = array();
then check if it's not empty:
if($values1 != '')
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
All you have to do is get the boolean value of
empty($array). It will return false if the array is empty.
You could use empty($varName) for multiple uses.
For more reference : http://php.net/manual/en/function.empty.php

Query not assigned into the variable / Not going into the condition

I was doing this code for my project and it seems that I can't get the values of the query into $currentRow. All that saved into the variable $currentrow is 22 which is the number rows in the database. I want to have access to all the query results. Please help. Here's the code.
public function getBSIConfig(){
$conn = oci_connect("472proj","system","//localhost/XE");
$sql = oci_parse($conn,"SELECT conf_id, conf_key, conf_value FROM bsi_configure");
oci_execute($sql);
echo "0";
while($currentRow = oci_fetch_all($sql,$res)){
echo "1.5";
echo $currentRow;
if($currentRow["conf_key"]){
echo "1";
if($currentRow["conf_value"]){
$this->config[trim($currentRow["conf_key"])] = trim($currentRow["conf_value"]);
echo "2";
}else{
$this->config[trim($currentRow["conf_key"])] = false;
echo "3";
}
}
}
}
And the output is only:
0
1.5
22
The results from this function are stored in the 2nd argument, rather than returned directly. See if this works for you:
$results = array();
$numResults = oci_fetch_all($sql, $results);
foreach ($results as $result) {
if ($result["conf_key"]) {
// etc ...
}
}
Read this http://php.net/manual/en/function.oci-fetch-all.php , you might get an idea what's wrong.

PHP MySQLi get the row using foreach

I have this function that i created for getting the rows of data from mysqli database.
I try to used foreach but the only i got was something like i attached the image please view.
oops sorry i can't post image it required me 10 reputation to do that.
below :
Yes these is what i got 1 2 x M M n O O X
my codes below with form and php
## FOR SHORTHAND DATABASE
if ( !function_exists( 'hs_debugSQL' ) ) {
function hs_debugSQL($hs_db, $string, $debug=0) {
if ($debug == 1)
print $string;
if ($debug == 2)
error_log($string);
$result = mysqli_query($hs_db, $string);
if ($result == false) {
error_log("SQL error: ".mysqli_error($hs_db)."\n\nOriginal query: $string\n");
// Remove following line from production servers
die("SQL error: ".mysqli_error($hs_db)."\b<br>\n<br>Original query: $string \n<br>\n<br>");
}
return $result;
}
}
## FOR SELECT SQL
if ( !function_exists( 'hs_getrows' ) ) {
function hs_getrows($sql, $debug=0) {
$result = hs_debugSQL($sql, $debug);
if($lst = mysqli_fetch_array($result)) {
mysqli_free_result($result);
return $lst;
}
mysqli_free_result($result);
return false;
}
}
form
<label for="message_title">Send to Admin <span class="red">*</span></label>
<input id="name" name="user_to" class="text" />
<select name="user_to">
<?php
global $hs_db;
$get_list_admin = hs_getrows( $hs_db, "SELECT * FROM hs_users WHERE user_control = 'admin' " );
foreach ( $get_list_admin as $keys ) {
echo '<option value="'.$keys['user_login'].'">'.$keys['user_login'].'</option>';
}
?>
</select>
connection from mysqli is fine as you can see i can get the data from mysqli.
but when i used foreach to retrieve the data it only show 1 number and sometimes 1 character.
i like to learn what is wrong with my codes for foreach.
thank you.
EXPLANATION
The problem is here:
if($lst = mysqli_fetch_array($result)) {
mysqli_free_result($result);
return $lst;
}
mysqli_fetch_array returns row by row, you should loop through the result and returning the array. Something like this
$lst = array();
while ($lst = mysqli_fetch_array($result)){
$lst[] = $row;
}
mysqli_free_result($result);
return $lst;
EDITED:
Well, i see another extrange thing
hs_debugSQL($sql, $debug);
and in the form
hs_getrows( $hs_db,....)
Your are calling the function hs_debugSQL with the SQL you want to execute i guess but in your function the first param is the database link, and the second the SQL you want to execute. You should change this to match the params for the function.
And you are calling the function hs_getrows with the database link in the first param and in function declaration you expect the $sql so you should change this.
I can't help but think that these 'helper' functions are making things more complicated than they should be. There's more than one problem here, but here's a crucial one:
This function:
function hs_debugSQL($hs_db, $string, $debug=0) {
requires $hs_db, a dtabase connection resource, be passed in, while this code:
function hs_getrows($sql, $debug=0) {
$result = hs_debugSQL($sql, $debug); // where is $hs_db?
if($lst = mysqli_fetch_array($result)) {
mysqli_free_result($result);
return $lst;
}
mysqli_free_result($result);
return false;
fails to provide a that key argument. Of course, further up the sequence of calls we find that $hs_db has been submitted, but has now been called $sql and the query seems to be missing.
Simplify! Get rid of these unhelpful functions, clarify what you are trying to do and make something work. Then if you feel the need to encapsulate some of this again, go ahead and do so knowing that the code basically works.
If you want to use a real helper
<?php
$sql = "SELECT user_login FROM hs_users WHERE user_control = 'admin'";
$admin_list = $hs_db->getCol($sql);
?>
<label for="message_title">Send to Admin <span class="red">*</span></label>
<input id="name" name="user_to" class="text" />
<select name="user_to">
<?php foreach ($admin_list as $admin): ?>
<option value="<?=$admin?>"><?=$admin?></option>
<?php endforeach ?>
</select>

Codeigniter Count / If

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.

Yii: Customize the results of CAutoComplete

I need to make a dropdown list using CAutoComplete. Everything is set and works fine, here is my code of the action:
<?php
public function actionSuggestCharacter() {
if(Yii::app()->request->isAjaxRequest && isset($_GET['q'])) {
$name = $_GET['q'];
$criteria = new CDbCriteria;
$criteria->condition='`Character` LIKE :keyword';
$criteria->params=array(':keyword'=>"$name%");
$criteria->limit = 5;
$suggestions = zCharacter::model()->findAll($criteria);
$returnVal = '';
foreach($suggestions as $suggestion) {
$returnVal .= $suggestion->Character."\n";
}
if (isset($suggestion)) {
echo $returnVal;
}
$criteria->condition='`Character` LIKE :keyword';
$criteria->params=array(':keyword'=>"%$name%");
$criteria->limit = 5;
$suggestions = zCharacter::model()->findAll($criteria);
$returnVal = '';
foreach($suggestions as $suggestion) {
$returnVal .= $suggestion->Character."\n";
}
if (isset($suggestion)) {
echo $returnVal;
}
}
}
?>
What this code does is that it shows the first 5 matches with the keyword at the beginning and the next 5 matches are with the keyword in any place.
Example. Let's say a user types in the input field "pdd" (doesn't really matter, could be any text), so the results returned by autocomplete will look like:
1. pddtext...
2. pddtext...
3. pdd_some_other_text
4. pdd_text
5. pdd_text
1. text_text_pdd
2. text_pdd_text
3. etc...
The problem is I need to separate these two blocks by some kind of line (<hr> or <div> with the border). How can I do this?
Thank you.
Can't you do something like this?
<?php
public function actionSuggestCharacter() {
if(Yii::app()->request->isAjaxRequest && isset($_GET['q'])) {
...
if (isset($suggestion)) {
echo $returnVal;
}
echo "Hey this is the delimiter\n";
$criteria->condition='`Character` LIKE :keyword';
....
}
}
?>
And then on the client side check for this string and when you encounter ""Hey this is the delimiter" replace it with your separator.

Categories