Array to string conversion error in PHP in MVC - php

ERROR: Array to string conversion in
/application/views/main_view.php on line 11
My view main_view.php
<?php echo $someval; ?>
my controller
<?php
class Main extends Controller {
function index()
{
$example = $this->loadModel('Example_model');
$something = $example->getSomething(1);
$template = $this->loadView('main_view');
$template->set('someval', $something);
$template->render();
}
}
?>
my model
<?php
class Example_model extends Model {
public function getSomething($id)
{
$id = $this->escapeString($id);
$result = $this->query('SELECT email FROM users WHERE id="1"');
return $result;
}
}
?>
I dont understand why is that a error. the return should be already in String? Any suggestions? Thanks

The result from your query $result is not a string that can be echoed.
$result = $this->query('SELECT email FROM users WHERE id="1"');
I don't know what framework you're using, but you need to look into how to retrieve query results.

As I wrote in a comment above. I guess the
$result = $this->query('SELECT email FROM users WHERE id="1"');
statement does not return a string. It probably returns an array or a result resource. You can print a variable with
var_dump($result);
If it is an array try
$template->set('someval', $something['email']);
If it is an result resource you probably have to fetch the data first. If it is a mysql resource it's something like
$arrayData = mysql_fetch_assoc($result);
If it's neither you have to check the documentation of your framework.

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']);
}
}
}

How to pass variable value to another file via class'

I have my main (user visible) file which displays posts, and I need to set-up pagination.
It would be easy if I fetch DB in the same file (but I want to avoid that), that is why I created a seperate (user hidden) file which contains class' which are then called from main file(blog.php):
BLOG.php(simplified):
<?php
require 'core.php';
$posts_b = new Posts_b();
$posts_bx = $posts_b->fetchPosts_b();
foreach($posts_hx as $posts_hy){
echo $posts_hy['title'];
}
?>
core.php(simplified);
class Posts_b extends Core {
public function fetchPosts_b(){
$this->query ("SELECT posts_id, title FROM posts");
//return
return $this->rows();
}
}
This works like a charm, but now I need to do the count within query, which works fine, and which gives me a variable $pages=5 (handled inside class posts_b - in file core.php),
core.php(simplified-with variable);
class Posts_b extends Core {
public function fetchPosts_b(){
$this->query ("SELECT posts_id, title FROM posts");
$pages=5;
//return
return $this->rows();
}
}
Now I need a way to return this variable value to blog.php (the way I return rows())
Please help, anyone,
Thank you...
A function can only have a single return value.
There are ways to get around this though. You can make your return value be an array that contains all of the values you want. For example:
return array("pages"=>$pages, "rows"=>$this->rows());
Then in your code
require 'core.php';
$posts_b = new Posts_b();
$posts_bx = $posts_b->fetchPosts_b();
$pages = $posts_bx["pages"];
foreach($posts_hx["rows"] as $posts_hy){
echo $posts_hy['title'];
}
?>
Or you can adjust a input parameter provided it was supplied as a reference
public function fetchPosts_b(&$numRows){
$this->query ("SELECT posts_id, title FROM posts");
//return
return $this->rows();
}
In your code
require 'core.php';
$posts_b = new Posts_b();
$pages = 0;
$posts_bx = $posts_b->fetchPosts_b(&$pages);
foreach($posts_hx["rows"] as $posts_hy){
echo $posts_hy['title'];
}
?>
Or you can opt to figure out your pagination outside of the fetchPosts_b method.
$posts_bx = $posts_b->fetchPosts_b();
$pages = floor(count($posts_bx)/50);

Send php variable to a class and run mysql query with Smarty

I would like to send a php variable to a class that runs a mysql query. It is a typical search via html form. I have to use Smarty.
How can I pass the variable "$minta" to the sql query and how to get the result array back to the php to display?
The Smarty tpl file is OK (lista_keres.tpl with the ingatlank variable).
Thank you in advance.
Tuwanbi
The php:
if (isset($_POST['keresoszo'])){
include_once "classes/ingatlan.class.php";
include_once "classes/main.class.php";
include_once "classes/felhasznalo.class.php";
$ingatlan = new Ingatlan();
$felhasznalo = new Felhasznalo();
$minta = $_POST['keresoszo'];
$kereses = new Main();
$kereses->getKeresIngatlan($minta);
$smarty->assign("kapcsolattartok", $ingatlan->getKapcsolattartok());
$smarty->assign("ingatlank", $main->getKeresIngatlan());
$smarty->assign("include_file", lista_keres);
echo $minta;
}
The class:
<?php
class Main{
private $keresoszo;
...
public function getKeresIngatlan($minta){
$this->keresoszo=$minta;
$ret = array();
$sql="SELECT id FROM table WHERE id LIKE '% ".$keresoszo." %'";
$ret = $this->db->GetArray($sql);
return $ret;
}
}
?>
Declaring private $keresoszo; it becomes the class object and can be accessible by
$this->keresoszo in you sql query you have assigned the value to this object but haven't used it
<?php
class Main{
private $keresoszo;
...
public function getKeresIngatlan($minta){
$this->keresoszo=$minta;
$ret = array();
$sql="SELECT id FROM table WHERE id LIKE '% ".$this->keresoszo." %'";
$ret = $this->db->GetArray($sql);
return $ret;
}
}
?>
Here is what how you can get back the results
$kereses = new Main();
$results_set=$kereses->getKeresIngatlan($minta);
var_dump($results_set);// for testing only
$smarty->assign("my_results_set", $results_set);

php pdo in class + best method to display return array

I have the following class:
<?php
class photos_profile {
// Display UnApproved Profile Photos
public $unapprovedProfilePhotosArray = array();
public function displayUnapprovedProfilePhotos() {
$users = new database('users');
$sql='SELECT userid,profile_domainname,photo_name FROM login WHERE photo_verified=0 AND photo_name IS NOT NULL LIMIT 100;';
$pds=$users->pdo->prepare($sql); $pds->execute(array()); $rows=$pds->fetchAll();
$unapprovedProfilePhotosArray = $rows;
echo 'inside the class now....';
foreach($rows as $row) {
echo $row['userid'];
}
}
}
I can display the data successfully from the foreach loop.
This is a class that is called as follows and want to be able to use the array in the display/view code. This why I added the "$unapprovedProfilePhotosArray = $rows;" but it doesn't work.
$photos_profile = new photos_profile;
$photos_profile->displayUnapprovedProfilePhotos();
<?php
foreach($photos_profile->unapprovedProfilePhotosArray as $row) {
//print_r($photos_profile->unapprovedProfilePhotosArray);
echo $row['userid'];
}
?>
What is the best way for me to take the PHP PDO return array and use it in a view (return from class object). I could loop through all the values and populate a new array but this seems excessive.
Let me know if I should explain this better.
thx
I think you're missing the $this-> part. So basically you're creating a local variable inside the method named unapprovedProfilePhotosArray which disappears when the method finishes. If you want that array to stay in the property, then you should use $this->, which is the proper way to access that property.
...
$pds=$users->pdo->prepare($sql); $pds->execute(array()); $rows=$pds->fetchAll();
$this->unapprovedProfilePhotosArray = $rows;
...

Categories