the data do not display in my view - php

Undefined variable: data in my view
This is a simple display data in the input.
So, why this input isn't display my query result at it?
my view
<input type="text" name="sitename" value="<?php echo $data['sitename']; ?>"><br>
model
public function getData()
{
$query = "SELECT * FROM $this->tablename ORDER BY 'id' DESC LIMIT 1";
if (!$sqli = mysqli_query($this->cxn->connect(),$query))
{
throw new Exception("Error Processing Request");
}
else
{
$num = mysqli_num_rows($sqli);
while ($num > 0)
{
$data = mysqli_fetch_array($sqli);
$num--;
}
return $data;
}
}

Simply because a variable is declared somewhere, doesn't mean it is available everywhere. All variables have scope in which they are accessible. See this: http://php.net/manual/en/language.variables.scope.php for more information on scope.
You need to pass the $data variable into your view. I image you're using some sort of MVC framework since you have a model and a view. If this is the case you can lookup how to pass variables into views in that specific framework. The basic structure of your controller method might look something like this:
//sudo code - not specific to an actual framework
public function controller_method()
{
$data = $model->getData();
$this->template->set('data',$data);
$this->template->load('view');
}
Just search how to do that in your specific framework. Hope that helps!
EDIT
Base on your comment it looks like you're setting data after you load the view. You need to swap the order and call $display = new Display("main"); $data = $display->getData(); before you include'../model/display.php';

If the query returns 0 rows, your while() loop will never execute, so it won't set $data.
Since you're only returning 1 row from the query, you don't need a loop, you can just use an if. Then you can return $data only when it succeeds.
public function getData()
{
$query = "SELECT * FROM $this->tablename ORDER BY 'id' DESC LIMIT 1";
if (!$sqli = mysqli_query($this->cxn->connect(),$query))
{
throw new Exception("Error Processing Request");
}
else
{
if ($data = mysqli_fetch_array($sqli))
{
return $data;
}
else
{
return null;
}
}
}

Related

i want to display value from database in codeigniter but i am getting errror

I want to display a value in view in CodeIgniter but I am getting several errors like trying to get the property on non-object. I think my code is correct but I am getting errors. Below is my code.
controller:
public function trainer($id)
{
$user_record = $this->db->query("select * from usr_data where usr_id=$id")->result();
$data['title'] = 'trainer Dashboard';
$data['user_record'] = null;
$data['active_courses'] = [];
$data['inprogress'] = [];
if(count($user_record)) {
$user_record = $user_record[0];
$data['title'] = ucwords($user_record->firstname).' Dashboard';
$data['user_record'] = $user_record;
$active_courses = $this->base_model->getTrainercourseAll($id);
$data['active_courses'] = $active_courses;
$inprogress = $this->base_model->getstaffinprogress($id);
$data['inprogress'] = $inprogress;
}
$this->load->view('trainer-dashboard', $data);
}
model:
public function getstaffinprogress($user_id) {
$result=$this->executeSelectQuery("select AVG(m.percentage) from object_data o, ut_lp_marks m where o.obj_id=m.obj_id and o.type='crs' and m.status=1 ");
return $result;
}
view:
<h3>Avg inprogress:<?php echo "<span style='color:#ff00ff;font-family:verdana;'>".$inprogress->percentage."</span>";?></h3>
I want to display the column percentage which is coming from database.above code is in the controller, model and view.i thought my controller code is wrong.
Anyone help me to get rid of this error. I want to display a value in view in CodeIgniter but I am getting several errors like trying to get the property on non-object. I think my code is correct but I am getting errors. Below is my code.
Try this in your view file,
if(isset($inprogress)){
echo $inprogress->percentage;
}
Then your code look like this,
<h3>Avg inprogress:<?php if(isset($inprogress)){ echo "<span style='color:#ff00ff;font-family:verdana;'>".$inprogress->percentage."</span>";}?></h3>
Then call the controller function. I think inprogress is not set at the first time.
If it doesn't work, try to var_dump($inprogress) in controller and check value and type.
And try this code in your model. Query also seems not correct
public function getstaffinprogress($user_id) {
$this->db->select_avg('ut_lp_marks.percentage');
$this->db->where('ut_lp_marks.obj_id', $user_id);
$this->db->where('object_data.type', 'crs');
$this->db->where('ut_lp_marks.status', 1);
$this->db->join('object_data', 'object_data.obj_id = ut_lp_marks.obj_id');
$query = $this->db->get('ut_lp_marks');
return $query->result_array();
}
I assume that your db is ut_lp_marks. Then var_dump array and check data is correct first. Then access array element.
public function getstaffinprogress($user_id) {
$result = array();
$query=$this->db->query("select AVG(m.percentage) from object_data o, ut_lp_marks m where o.obj_id=m.obj_id and o.type='crs' and m.status=1 ");
foreach($query->result() as $row){
$result = $row;
}
return $result;
}
Also check $inprogress->percentage exists before print in view.

Efficient way to reuse the same call to the same sql table

So I search for this title hoping someone would have already answered it however, I came across similar topics on other languages but not PHP so maybe this will help others.
I am constantly using this following script to call on the database but how can I create it so that I can make it just once at the top of the class for example and use it in every method on the class page that needs it. Example: An single page may not have all of the data it needs from the same table but if the table contains 50% of the data or more for that page, how can I modify this so that I can just say it once and let the rest of the following scripts display the data it extracted in the first place by calling it all just once?
Here's what I have now.
<?php
if($res = $dbConn->query("SELECT Column FROM Table")){
while($d = $res->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
?>
I want to call on this without the printf(" "); collect and store the data so that I can then call the results while printing or echoing the results with the HTML in other methods. What os the most efficient way? I don't want to make the same call over and over and over... well, you get the point.
Should I use fetch_array or can I still do it with fetch_assoc?
not very sure if it's the answer you want.
you can use include/include_once/require/require_once at the top of the page you want to use the function
for example:
general_function.php:
-----
function generate_form( $dbConn, $sql ) {
if($res = $dbConn->query("SELECT Column FROM Table")) {
while($d = $res->fetch_assoc()) {
printf("Enter HTML here with proper %s", $d['Column']);
}
}
}
and for those pages you want to use the function, just put
include "$PATH/general_function.php";
and call generate_form
Try this:
class QueryStorage {
public static $dbConn = null;
public static $results = [];
public static function setConnection($dbConn) {
self::$dbConn = $dbConn;
}
public static function query($query, $cache = true) {
$result = (array_key_exists($query, self::$results))?
self::$results[$query] : self::$dbConn->query($query);
if($cache) {
self::$results[$query] = $result;
}
return $result;
}
public static function delete($query) {
unset(self::$results[$query]);
}
public function clean() {
self::$results = [];
}
}
usage:
at top somewhere pass connection to class:
QueryStorage::setConnection($dbConn);
query and store it:
$result = QueryStorage::query("SELECT Column FROM Table", true);
if($result){
while($d = $result->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
reuse it everywhere:
$result = QueryStorage::query("SELECT Column FROM Table", true); // it will return same result without querying db second time
Remember: it's runtime cache and will not store result for second script run. for this purposes You can modify current class to make it
work with memcache, redis, apc and etc.
If I understood you correctly, then the trick is to make an associative array and access with its 'key' down the code.
$dataArray = array();
// Add extra column in select query for maintaining uniqness. 'id' or it can be any unique value like username.
if($res = $dbConn->query("SELECT Column,id FROM Table")){
while($d = $res->fetch_assoc()){
$dataArray[$d['id']] = $d['Column'];
}
}
//you have value in the array use like this:
echo $dataArray['requireValueId'];
//or , use 'for-loop' if you want to echo all the values
You need a function which takes in the query as a parameter and returns the result.
Like this:
public function generate_query($sql) {
if($res = $dbConn->query($sql)){
while($d = $res->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
}

recursive function in codeigniter returns 500 error

i have this next recursive function that keep return 500 error
public function get_parent($cat=0){
$ci = &get_instance();
$q= $ci->db->query("SELECT category_id,parent_id FROM tbl_products_categories WHERE category_id = {$cat}");
if($q->num_rows()>0){
$row = $q->row();
if($row->parent_id == 0){
return $row->category_id;
break;
}else if($row->parent_id != 0){
$this->get_parent($row->category_id) ;
}
}
else{
return 0;
}
}
i am calling the function like this:
$cat = 9;
$main_cat =$this->get_parent($cat);
$this->get_parent($row->category_id);
is calling get_parent with the same ID you originally called it with so it keep recursing until you get a stack overflow.
FYI Depending on your database, it should be possible to do what you want in pure SQL without multiple queries.
Edit: Also, you probably want to do
$ci->db->query("SELECT category ... WHERE category_id=?", array($cat));
instead of what you have now because your current query is susceptable to SQL injection if your function is called with anything other than a number.

Why is this php function causing a sever 500 error?

I'm trying to implement these two functions in a separate file functions.php and call it in index.php
function is_field($column, $table, $requested) {
$is_field_query = "SELECT ".$column." FROM ".$table." WHERE ".$column."='".$requested."'";
$is_field_result = $mysqli->query($is_field_query);
$is_true = $is_field_result->num_rows;
$is_field_result->close();
return $is_true;
}
function get_content($column, $table, $requested) {
$get_content_query = "SELECT ".$column." FROM ".$table." WHERE ".$column."='".$requested."'";
$get_content_result = $mysqli->query($get_content_query);
$get_content_row = $get_content_result->fetch_array(MYSQLI_ASSOC);
$get_content_content = $get_content_row["content"];
$get_content_result->close();
return $content;
}
I have tried it over and over again and I have no idea why it wont work. The first one is returning 1 for valid or 0 for invalid. The second retrieves the content from a specific cell in the MySQL table. Any help would be much appreciated.
You're using $mysqli inside the function, but you never pass the MySQLi resource itself. Consider writing your function like this:
function is_field($mysqli, $column, $table, $requested) {
Or, create a class that takes a MySQLi resource and reference it with $this->mysqli inside your function.
Also, code like this may be another issue:
$is_field_result = $mysqli->query($is_field_query);
$is_true = $is_field_result->num_rows;
You're not checking whether $is_field_result is false; therefore, the next statement causes a fatal error, because a property can't be fetched from something that's not an object.
if (($is_field_result = $mysqli->query($is_field_query)) === false) {
die($mysqli->error);
}
$is_true = $is_field_result->num_rows;
It turns out the reason it was not working was I needed to add an extra field into the function to accept the passing of $mysqli from the connection.
function is_field($mysqli, $column, $table, $requested) {
$is_field_query = "SELECT * FROM $table WHERE $column='$requested'";
if (($is_field_result = $mysqli->query($is_field_query)) == false) {
die($mysqli->error);
}
$is_true = $is_field_result->num_rows;
$is_field_result->close();
return $is_true;
}
function get_content($mysqli, $column, $table, $requested) {
$get_content_query = "SELECT * FROM $table WHERE $column='$requested'";
if (($get_content_result = $mysqli->query($get_content_query)) == false) {
die($mysqli->error);
}
$get_content_row = $get_content_result->fetch_array(MYSQLI_ASSOC);
$get_content = $get_content_row["content"];
$get_content_result->close();
return $get_content;
}

Php Display While Loop From Function

I have a question regarding displaying the contents of a function, this function displaying a while loop.
Here is a function within my model:
function get_results($id)
{
$stmt = "select * where ... "
$stmt = $this->BEAR->Database->query($stmt);
$result = '';
while($row = mysqli_fetch_array($stmt))
{
$result .= '<div>';
$result .= $row['name'];
$result .= '</div>';
}
$this->BEAR->Template->setData('loop', $result, FALSE);
}
This is my Controller:
$BEAR->Webprofile->get_results(Template->getData('id'));
And this is my view:
<?php echo $this->getData('loop');?>
This displays the Loop within my view with no problem. But what I wish for is not to have any HTMl within my Model, Is there anyway of doing this (As this can cause a large amount of HTML in my Model). Maybe a way I can set the data within the Model and then get the data within my view.
I tried setting within the Model functions while loop individually like the following:
while($row = mysqli_fetch_array($stmt))
{
$this->BEAR->Template->setData('name', $row['name']);
$this->BEAR->Template->setData('name', $row['age']);
}
Then call the function in the Controller and call each setData, but this only displayed the first result not the full while loop of contents.
Therefore I wish to display all the contents of my while loop in my view (with HTML) but wish my function to just be getting and setting the Data. Can this be done? Any thoughts or guidance would be appreciated.
You need to apply some discipline to your MVC. Your models need to return raw data. It should return only objects or arrays of data. The key is consistency.
Your views need to include all the code to add your html formatting. Having a view that simply calls a model function you wrote that spits out a div or an ordered list, makes the entire concept of the view useless. Your views should provide all the HTML code.
Since you're using PHP, you can easily drop in and out of HTML.
Start with something like this in your model:
function get_results($id)
{
$stmt = "select * where ... "
$stmt = $this->BEAR->Database->query($stmt);
$results = array();
while($row = mysqli_fetch_array($stmt))
{
$results[] = $row['name'];
}
return results;
}
From there, you should be able to figure out that your controller should call this function, and pass the $results into your view/template along with the specific view file for rendering.
function get_results($id)
{
$stmt = "select * where ... "
$stmt = $this->BEAR->Database->query($stmt);
$result = '';
$result = mysqli_fetch_array($stmt);
return $result;
}
Then in your controller:
$this->BEAR->Template->setData('loop', $model->get_results($id), FALSE);
Then in your template
foreach($rows as $row){
....do something with each row
}
full example of how to get the data from the model and then pass to the template
class MyController {
function controller_showResults(){
$model = new Model();
$results = $model->get_results($_GET['id']);
$this->BEAR->Template->setData('loop', $results, FALSE);
}
}
Now the view assuming that the first argument to setData in template is a variable passed to the view and that variable is $results
<?php foreach($loop as $l): ?>
<div><?php echo $l['name'] ?></div>
<?php endforeach; ?>

Categories