Foreach invalid argument - php

I am creating a search function that will allow a user to search for a house in my database by postcode initially. The function can be seen below, when the function is executed and finds a true statement I get no errors however when I execute the search and I get a no fields been returned I am left with this error:
No Records Found
Warning: Invalid argument supplied for foreach() in /Applications/XAMPP/xamppfiles/htdocs/undergradpad/search.php on line 26
I want it to display No Records Found however I don't know how I should correct the above error.
search.php:
<table width="500" border="1" cellpadding="5">
<tr>
<th width="16" scope="row">id</th>
<td width="95">bedrooms</td>
<td width="140">description</td>
<td width="104">roadname</td>
<td width="71">postcode</td>
</tr>
<?php
require("classes/class.House.inc");
$obj = new House();
$obj->search($_POST['term']);
foreach($obj->data as $val){
extract($val);
?>
<tr>
<td scope="row"><?php echo $id; ?></td>
<td><?php echo $bedrooms; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $roadname; ?></td>
<td><?php echo $postcode; ?></td>
</tr>
<?php
}
?>
</table>
classes/class.House.inc:
<?php
include("connect/class.Database.inc");
class House extends Database {
public function read(){
$query = "SELECT * FROM houses";
$result = $this->mysqli->query($query);
$num_result = $result->num_rows;
if($num_result > 0){
while($rows =$result->fetch_assoc()){
$this->data[]=$rows;
//print_r($rows);
}
return $this->data;
}
}
public function search ($term){
$query = "SELECT * FROM houses WHERE postcode like '%".$this->mysqli->real_escape_string($term)."%'";
$result = $this->mysqli->query($query);
$num_result = $result->num_rows;
if($num_result > 0){
while($rows =$result->fetch_assoc()){
$this->data[]=$rows;
//print_r($rows);
}
return $this->data;
} else{
echo 'No Records Found';
}
}
}
?>

in this variable ($obj->data) you just get null data.
First check if not empty and than use foreach and don't have error if yout method don't return null data
just check if (!empty($obj->data)
{
foreach code
}

$obj is a House object. It has no $data property, even if you use it. The search method sets this property, but only if records are found. If no records are found, the method echoes a value.
I would change it like this: Instead of echoing an error, make the method return false:
public function search ($term){
$query = "SELECT * FROM houses WHERE postcode like '%".$this->mysqli->real_escape_string($term)."%'";
$result = $this->mysqli->query($query);
$data = false;
$num_result = $result->num_rows;
while($row =$result->fetch_assoc()){
$data[]=$row;
}
return $data;
}
Now, the function return an array of false if there is no data. You can now use it like this:
$obj = new House();
if ($data = $obj->search($_POST['term']))
{
foreach($obj->data as $val){
extract($val);
}
}
The changes I made:
- No longer set data as a property, since you also return it. You can still do that, if you like, but I think it's confusing to do both.
- Return false if there's no data.
- Change the variable rows to row, since it only contains one row.

if(is_array($obj->data)){
foreach code
}
else{
no record
}

Related

Calling two methods from table wrapper in a class

I want to create a table which generates data from the database and I need to have update and delete function for each row of data in the table. But i failed to do both update and delete because i put both function in one controller
This is my view file which include the controller to show the data.
<table class="table table-hover">
<tr class="table-active">
<td>Booth ID</td>
<td>Booth Location</td>
<td>Participant ID </td>
<td></td>
<td></td>
</tr>
<tr>
<?php include 'BoothViewController.php'; ?>
</tr>
</table>
This is my controller to display the data in rows. Each row will have update and delete function. The update function will bring the user to another page while delete function is merely remove that row of data.
<?php
require 'boothmodel.php';
$result = viewbooth();
if($result){
while($array = mysqli_fetch_array($result)){
echo "<td>".$array["BoothID"]."</td>";
echo "<td>".$array["Boothlocation"]."</td>";
echo "<td>".$array["ParticipantID"]."</td>";
echo "<td><a href='BoothFormUpdate.php?bid=".$array['BoothID'].
"&blocation=".$array['Boothlocation']."&pid=".$array['ParticipantID']."'>Update</a></td>";
echo "<td><a href='BoothViewController.php?bid=".$array['BoothID'].
"&blocation=".$array['Boothlocation']."&pid=".$array['ParticipantID']."'>Delete</a></td>";
}
return;
}
if(isset($_GET['bid'])){
$selectedbid = $_GET['bid'];
$result = deletebooth($selectedbid);
if($result){
echo "<script language = 'javascript'>";
echo "alert('Booth deleted!');";
echo "window.location.href = 'BoothView.php';";
echo "</script>";
}
}?>
this is my model.
<?php
require 'connection.php';
mysqli_select_db($conn, "ims");
function viewbooth(){
global $conn;
$query = "SELECT * FROM booth";
$result = mysqli_query($conn, $query);
return $result;
}
function updatebooth($bid, $newbloc){
global $conn;
$update = "UPDATE booth
SET Boothlocation='".$newbloc.
"'WHERE BoothID='".$bid."'";
$result = mysqli_query($conn, $update);
return $result;
}
function deletebooth($selectedbid){
global $conn;
$delete = "DELETE FROM booth WHERE BoothID=".$selectedbid;
$result = mysqli_query($conn, $delete);
return $result;
}?>
I know i can simply do the delete function in another controller but im trying to put all in one controller.
You need to create a basic routing mechanism, e.g.
if(isset($_GET['bid'], $_GET['action']))
{
$selectedbid = $_GET['bid'];
$action = $_GET['action'];
switch ($action)
{
case 'delete':
$result = deletebooth($selectedbid);
if($result){
echo "<script language = 'javascript'>";
echo "alert('Booth deleted!');";
echo "window.location.href = 'BoothView.php';";
echo "</script>";
}
break;
case 'update':
// do the updating
break;
}
}
then you can add update and delete links to your items:
Update item
Delete item
Your code hardly resembles the MVC pattern and has many issues. However, the routing idea should work.

Codeigniter - Get_where base from session_userdata

I want to select all the rows that emp id's are match to my session userdata (emp_id). Here's my code. I get so many errors and no row has been selected. Someone help me please. Thanks
Model:
public function get_save_samp($emp_id) {
$query = $this->db->get_where('tblsavesample', array('emp_id' =>
$emp_id));
return $query->row_array();
}
Controller:
public function show() {
$emp_id = $this->session->userdata('emp_id');
$data['save'] = $this->user_model->get_save_samp($emp_id);
$this->load->view('show',$data);
}
Views:
<?php foreach ($save as $row) { ?>
<td style="width: " ><?php echo $row->emp_id ?></td>
<td style="width: " ><?php echo $row->emp_code?></td>
<td style="width: " ><?php echo $row->emp_name ?></td>
<?php }>
Try This
public function get_save_samp($emp_id) {
$query = $this->db->get_where('tblsavesample', array('emp_id' =>
$emp_id));
return $query->result();
}
you can try solution for your problem :
Changes your modal function :
Modal.php
public function get_save_samp($emp_id) {
$this->db->select("*");
$this->db->where('id', $emp_id);
$this->db->get('tblsavesample');
return $query->row();
}
Views:
<?php foreach ($save as $row) {?>
<td style="width: " ><?php echo $row->emp_id ?></td>
<td style="width: " ><?php echo $row->emp_code ?></td>
<td style="width: " ><?php echo $row->emp_name ?></td>
<?php } ?>
row_array() returns the first row only. If you want all the records to be returned, use result_array() instead.
$result = $query->result_array();
return $result;
Link : click
Change your Modal Code like this :
public function get_save_samp($emp_id) {
//$query = $this->db->get_where('tblsavesample', array('emp_id' =>$emp_id));
$this->db->select("*");
$this->db->where_in('id', $emp_id);
$query = $this->db->get('tblsavesample');
return $query->result();
}
And Change your Controller code like this to check what data are we getting inside controller.
public function show()
{
$emp_id = $this->session->userdata('emp_id');
$data['save'] = $this->user_model->get_save_samp($emp_id);
echo "<pre>";
print_R($data['save']);
exit();
$this->load->view('show', $data);
}
row_array() used to return only single record. change your code in model as follows :
public function get_save_samp($emp_id) {
$query = $this->db->get_where('tblsavesample', array('emp_id' =>
$emp_id));
return $query->result_array();
}
and check number of records returned in your controller as follows:
$data['save'] = $this->user_model->get_save_samp($emp_id);
echo $data['save']->num_rows();
if this displays 0, then you have no matching records in your database table.
to test the query, try to execute the same query in mysql

A Better Way for No Results Returned?

I have a very simple search page running a query for one table in a DB. I have the query and fetch working. But if it doesn't find any matches to the term the user put in then I need it to say "No Rows Returned".
Here is my PHP CODE:
<?php
include('./includes/dbConnection.php');
$result = null;
if (isset($_GET['submit'])) {
// connect to database
$conn = dbConnect('localhost', 'db_admin', 'kfor.com', 'receiving');
// query the database
$stmt = $conn->stmt_init();
$searchTerm = "SELECT * FROM inventory WHERE pallet = {$_GET['pallet_id']}";
$result = $conn->query($searchTerm);
}
?>
Here is the PHP displaying the results and errors:
<?php
if ($result != null) {
if (!empty($result)) {
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row['pallet']; ?></td>
<td><?php echo $row['serial']; ?></td>
</tr>
<?php
}
}
} else {
echo "No Results";
}
?>
Is there a better way to display "No Results Returned"? Right now it's just displaying that error upon refresh because $result does equal null.
Thanks for any help!
Remove $result = null;, it's not needed. You can check num_rows returned your query.
<?php
include('./includes/dbConnection.php');
if (isset($_GET['submit'])) {
// connect to database
$conn = dbConnect('localhost', 'db_admin', 'kfor.com', 'receiving');
$_GET['pallet_id'] = addslashes($_GET['pallet_id']);
// query the database
$stmt = $conn->stmt_init();
$searchTerm = "SELECT * FROM inventory WHERE pallet = {$_GET['pallet_id']}";
$result = $conn->query($searchTerm);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row['pallet']; ?></td>
<td><?php echo $row['serial']; ?></td>
</tr>
<?php
}
} else {
echo "No Results Returned";
}
}
?>

Performing query inside active row array

Basically i'm using an mySQLi wrapper i've found online and while trying to use it i've came across a problem i can't see to get past, basically, i'm performing this.
<?php
$res = $DB->Query("SELECT * FROM `table`");
while($row = $DB->Fetch()) {
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $functions->checkStatus($row['arowhere']); ?></td>
</tr>
<?php
}
?>
So when i'm trying to do this $functions->checkStatus($row['arowhere']); it performs a new query inside this function on my table row, it's changing the latest query which is being used for the while($row = $DB->Fetch()) {
public function Query($SQL) {
$this->SQL = $this->mysqli->real_escape_string($SQL);
$this->Result = $this->mysqli->query($SQL);
if ($this->Result == true) {
return true;
} else {
die('Problem with Query: ' . $this->SQL);
}
}
public function Fetch() {
return mysqli_fetch_assoc($this->Result);
}
Is there a solution or maybe someone point me in the correct direction so i can avoid this please.
I can't believe such a wrapper can be found online. As a matter of fact, it's completely, ultimately unusable.
Doing mysqli->real_escape_string($SQL); makes absolutely no sense. It won't protect your query from injection yet it will spoil whatever complex query. As soon as you will try to run a query with WHERE condition it will die from error.
And the following line is also wrong
die('Problem with Query: ' . $this->SQL);
as it's not showing you neither error nor file and line number.
And least this wrapper's problem is one you face - it is using internal variable to hold the result, while it should just return it.
A real mysqli wrapper is SafeMysql, which lets you to add whatever dynamical data via placeholders.
With SafeMysql your code would work:
<?php
$res = $DB->query("SELECT * FROM `table`");
while($row = $db->fetch($res)) {
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $functions->checkStatus($row['arowhere']); ?></td>
</tr>
<?php
}
?>
You could iterate through the rows and add them to a temporary array. You could then reference the rows via this array after other queries have been made. This could have memory implications if there are too many rows being returned by the query, so be careful.
<?php
$res = $DB->Query("SELECT * FROM `table`");
$rows = array();
while($row = $DB->Fetch()) {
array_push( $rows, $row );
}
foreach( $rows as $row ){
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $functions->checkStatus($row['arowhere']); ?></td>
</tr>
<?php
}
unset( $rows ); // destroys the temporary array, freeing the memory it consumed
?>

how to return data from model to controler and controler to views in codeigniter

i am using codeigniter. i have a table to be displayed in a view file. so i have a model where i fire a query to get the data from table.
function my_active_requests()
{
$user_id = $this->session->userdata('user_id');
$this->db->select('id,request_date,required_by_date');
$this->db->where('requested_by',$user_id);
return $this->db->get('requests');
///also tried with
//$query = $this->db->get('requests');
///$number_of_rows = $query->num_rows;
//return $query;
//return $number_of_rows;
//but no result
}
this is the model function.
this is my controller
function my_active_req()
{
$this->bloodline_model->my_active_requests();
//also tried without this//
$query = $this->db->get('requests');
//and this//
$number_of_rows = $query->num_rows;
$this->load->view('my_active_req');
}
and this is my view
<?php foreach ($query->result() as $row) { ?>
<tr>
<td><?php echo $row->id; ?></td>
<td><?php echo $row->request_date; ?></td>
<td><?php echo $row->required_by_date; } ?></td>
</tr>
</table>
but the error is undefined variable $query.
i think , i am not able to return the $query and other data from my model to controller and controller to my view.
Please provide me with the solution.
`
Change this line:
<?php
$this->load->view('my_active_req', array(
'query' => $query
));
The second parameter of the view() loader function allows you to pass variables into the view.
However, you're largely circumventing the purpose of MVC separation. You want the controller to "ask" for information from the model (not just straight from the database; otherwise, what's the point of a model?), and then "pass" it to the view. The controller knows what the view needs to function.
Model
function my_active_requests()
{
$user_id = $this->session->userdata('user_id');
$this->db->select('id,request_date,required_by_date');
$this->db->where('requested_by',$user_id);
$query = $this->db->get('requests');
if($query->num_rows) {
return $this->db->result();
}
return false;
}
Controller
function my_active_req()
{
$results = $this->bloodline_model->my_active_requests();
$this->load->view('my_active_req', array('user_data' => $results));
}
View
<?php
if($user_data) {
foreach ($user_data as $row) { ?>
<tr>
<td><?php echo $row->id; ?></td>
<td><?php echo $row->request_date; ?></td>
<td><?php echo $row->required_by_date; } ?></td>
</tr>
</table>

Categories