get user data info by class (php) - php

I want to get a row from db and show in my page. Following code doesn't work and my browser hangs. and i don't know how fix it. Please help me.
Class :
public function get_calculate($id)
{
if ($id != 0) {
$stmt_select_calculate = $this->connect()->prepare('SELECT analix_calculate.title,analix_calculate.basis FROM analix_calculate where analix_calculate.id=:calculate_id AND analix_calculate.is_active=1;');
$stmt_select_calculate->bindValue(':calculate_id', $id, PDO::PARAM_STR);
} else {
$stmt_select_calculate = $this->connect()->prepare('SELECT analix_calculate.title,analix_calculate.basis FROM analix_calculate where analix_calculate.is_active=1;');
}
return $stmt_select_calculate->execute();
}
index.php :
<?php
include("../db/Database.php");
$databse = new Database();
$menu = $databse->get_calculate(0);
while ($row_select_calculate = $menu) {
?>
<li>
<a href="#0">
<i class="fa fa-home" aria-hidden="true"></i><?php echo $row_select_calculate['title']?>
</a>
</li>
<?php
}
?>

First of all, $stmt_select_calculate->execute(); returns bool value. You cannot iterate over bool value, it's obvious. So, you should return statement object itself:
public function get_calculate($id)
{
if ($id != 0) {
$stmt_select_calculate = $this->connect()->prepare('SELECT analix_calculate.title,analix_calculate.basis FROM analix_calculate where analix_calculate.id=:calculate_id AND analix_calculate.is_active=1;');
$stmt_select_calculate->bindValue(':calculate_id', $id, PDO::PARAM_STR);
} else {
$stmt_select_calculate = $this->connect()->prepare('SELECT analix_calculate.title,analix_calculate.basis FROM analix_calculate where analix_calculate.is_active=1;');
}
$stmt_select_calculate->execute();
return $stmt_select_calculate;
}
In index.php you should fetch data:
$menu_stmt = $databse->get_calculate(0);
while ($row = $menu_stmt->fetch()) {
?>
<li>
<a href="#0">
<i class="fa fa-home" aria-hidden="true"></i><?php echo $row['title']?>
</a>
</li>
<?php
}

Related

PHP error code: Notice: Trying to get property ... of non-object in C:\xampp\htdocs\testing\index3.php on line 95

I tried to work on the following script;
<?php
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$id = $row["id"];
$fullname = $row["fullname"];
$biography = $row["biography"];
$email = $row["email"];
$facebook = $row["facebook"];
$twitter = $row["twitter"];
$gplus = $row["gplus"];
$linkedin = $row["linkedin"];
echo '<div id="tabs-'.$row['id'].'" aria-labelledby="ui-id-'.$row['id'].'" role="tabpanel" class="ui-tabs-panel ui-corner-bottom ui-widget-content" aria-hidden="true" style="display: none;"><p>'.$row['biography'].'</p>
<div class="icon-bar">
<p>';
if ($view->$linkedin=='') {
# code...
$view = '';
}else{
$view = '<i class="fa fa-linkedin"></i>';
}
echo
'
</p>
</div>
</div>';
}
}
?>
but got the following error:
Notice: Trying to get property 'https://www.linkedin.com/in/data-analyst-project-management-cloud-expert-bigdata/' of non-object in C:\xampp\htdocs\testing\index3.php on line 95...
Can someone please help me out.
I don't see any view object that you have defined.
If you have defined view object then also you code must be
if($view->linkedin == ''){
//code
}
Or if you have not defined view object the code code may be
if($linkedin == ''){
//code
}
I have been able to resolve the issue using
if ($linkedin=='') {
# code...
$view = '';
}else{
echo '<i class="fa fa-linkedin"></i>';
}
Thanks to #catcon,#Suresh Chand

In database table there is no rows means getting error Undefined variable: results using codeigniter

In database table there is no rows means getting error Undefined variable: results using codeigniter,in case there is no row or empty table is there means i want to display view page
controller
$data['breview'] = $this->Profile_model->review();
$this->load->view('supplierreview', $data);
Model
public function review() {
$this->db->select('*');
$this->db->from('reviews');
$this->db->join('supplier_otherdetails', 'supplier_otherdetails.supplierid_fk = reviews.supplier_id');
$this->db->join('customer_registration', 'reviews.customer_id=customer_registration.id');
$this->db->join('sub3_category', 'reviews.product_id=sub3_category.id');
$this->db->where('supplierid_fk', $this->session->id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
$results = $query->result();
}
return $results;
}
view page
<?php
foreach ($breview as $row) {
?>
<div class="reviewsection">
<img src="<?php echo 'data:image;base64,' .$row->product_image; ?>" class="img-circle img-user" alt="" width="50px;" height="50px;"/>
<span class="starfont"><botton class="btn btn-danger"> <?php echo $row->ratings; ?> <span class="fa fa-star starfont"></span></botton> </span>
<div class="content-left">
<p><b>Product Name:<?php echo $row->product_name; ?></b></p>
<p><?php echo $row->review_msg; ?></p>
<?php $buyer_review = strtotime($row->review_date);?>
<?php $date=date('d-F-Y',$buyer_review); ?>
<p>Buyer Name : <?php echo $row->first_name; ?> <?php echo $date ; ?></p>
</div>
</div>
<?php } ?>
$results is not defined.
Please add $results = [];
Here you go:
$results = [];
if ($query->num_rows() > 0) {
$results = $query->result();
}
return $results;
In my model, in most cases, i do the following
public function my_function() {
//$qry = YOUR_QUERY
if ($qry->num_rows() > 0) //or ==1 or whatever, depends on your structure
return $qry->result_array(); // or row_array, depends on your structure
return FALSE;
}
Then in your controller you can check if the result is FALSE or EMPTY like:
$result_from_model = $this->my_model->my_function();
if($result_from_model && !empty($result_from_model)) {
//your code here
}
You can use the following code :
return (is_array($results)?$results:array());
Hope it works.
All the answers given so far are good. Here is yet another way to do it. It's essentially the same as the accepted answer only using a ternary instead of if.
$query = $this->db->get();
return $query->num_rows() > 0 ? $query->result() : array();
}

Problems to iterate objects in array

I have this method below which is responsible for bringing me an array of objects (blog).
public function getListaBlogsById($id) {
$result = array();
try {
$statement = $this->getDb()->prepare('SELECT * FROM Blog WHERE categoria_id = :id');
$statement->bindParam(':id', $id);
$statement->execute();
$result = $statement->fetchAll();
} catch (Exception $ex) {
$ex->getTrace();
}
return $result;
}
And I know that the array is not null. What I want to do is to iterate the objects inside the array in this way:
<?php foreach ($blog_category as $item): ?>
<h2>
<?php echo $item->getTitle(); ?>
</h2>
<p class="lead">
by <?php echo $item->getAuthor(); ?>
</p>
<p><i class="fa fa-clock-o"></i> Postado em
<?php $date = strtotime($item->getDate());
$br_format = date("d/m/Y g:i A", $date);
echo $br_format;
?></p>
<hr>
<a href="<?php echo Utils::createLink('detail-post', array('id' => $item->getId())); ?>">
<img class="img-responsive img-hover" src="../web/img/1850_james_ancestry.JPG" alt=""/>
</a>
<hr>
<p><?php echo $item->getPre(); ?></p>
<a class="btn btn-primary" href="<?php echo Utils::createLink('detail-post', array('id' => $item->getId())); ?>">Leia mais <i class="fa fa-angle-right"></i></a>
<hr>
<?php endforeach; ?>
But the page renders nothing.
Any light will be appreciated.
The object that is used will have been created from strClass() and therefore does not have any get methods associated with it.
So change your script like so in order to access the properties of these objects directly rather than expecting them to have an associated ->getxxx() method.
<a href="<?php echo Utils::createLink('detail-post', array('id' => $item->id)); ?>">
<?php echo $item->title; ?>
</a>
The actual names of the properties will depend on the column names ( and column name case) you have on the table you queried.
You may also need to change this line in your getListaBlogsById($id) funtion to ensure that the data is returned as an object and not an array
From
$result = $statement->fetchAll();
To
$result = $statement->fetchAll(PDO::FETCH_CLASS);
Thanks #RiggsFolly for your help. I solve my problem making some modification as fallows:
public function getListaBlogsById($id) {
try {
$result = array();
$blog = new Blog();
$statement = $this->getDb()->prepare('SELECT * FROM Blog WHERE categoria_id = :id');
$statement->bindParam(':id', $id);
if ($statement->execute()) {
while ($row = $statement->fetch()) {
BlogMapper::map($blog, $row);
$result[$blog->getId()] = $blog;
}
}
} catch (Exception $ex) {
$ex->getTrace();
}
return $result;
}
and
public static function map(Blog $blog, array $properties) {
if (array_key_exists('id', $properties)) {
$blog->setId($properties['id']);
}
if (array_key_exists('blog_author', $properties)) {
$blog->setAuthor($properties['blog_author']);
}
if (array_key_exists('blog_article_title', $properties)) {
$blog->setTitle($properties['blog_article_title']);
}
if (array_key_exists('blog_date_creation', $properties)) {
$blog->setDate($properties['blog_date_creation']);
}
if (array_key_exists('blog_article_pre', $properties)) {
$blog->setPre($properties['blog_article_pre']);
}
if (array_key_exists('blog_article', $properties)) {
$blog->setArticle($properties['blog_article']);
}
if (array_key_exists('categoria_id', $properties)) {
$blog->setCategoria_id($properties['categoria_id']);
}
}

Menu created with MySQL only works within website not outside

I hope somebody can help me, because i got an menu that is auto generated via my MySQL db.
Because i got the menu to work inside the website and with that i mean it works with "test.dk/about" but the a href is empty when it's going out of the website like "http://google.com"...
btw it's just a very simple UL LI menu no dropdown or something.
Here is my script
static function build_menu()
{
$result = mysql_query("SELECT * FROM menu");
$menu = array();
while ($row = mysql_fetch_assoc($result)) {
if ($row["is_external"]) {
$url = $row["url"];
} else if (empty($row["is_external"])) {
$url = get_page_url($row["page_id"]);
}
$menu[] = array("name" => $row["name"], "page_id" => $row["page_id"], "is_external" => $row["url"], "url" => $url);
}
return $menu;
}
static function get_page_url($page_id)
{
$result = mysql_query("SELECT view_id FROM page WHERE id = '$page_id'");
$result = mysql_fetch_assoc($result);
$view_id = $result["view_id"];
$result = mysql_query("SELECT listen_path FROM view WHERE id = '$view_id'");
$result = mysql_fetch_assoc($result);
$listen_path = $result["listen_path"];
return $listen_path;
}
static function render()
{
$result = mysql_query("SELECT * FROM menu"); ?>
<div class="menu">
<ul><?php while ($item = mysql_fetch_assoc($result)) { ?>
<li><?php echo $item["name"] ?>
</li> <?php } ?></ul></div><?php
}
How can i fix it, so it works both internal and external?
<div class="menu"> <ul> <li>Homepage</li> <li>About</li> <li>Develop</li> <li>Support</li>
This should be <li>Support</li>; </ul> </div>
You only check for an external link in the function build_menu(), but this function isn't called anywhere from your render() function.
The render() function only calls get_page_url() which doesn't distinguish between internal and external links.
Href parameter of external URL must start with protocol declaration, so with "http://" in your case.
So change your code in condition inside the function "build_menu", if the URL is external, add "http://" to it, something like this:
$url = 'http://'.$row["url"];
I got it work after a while!
I simply just created an If else statement in the render function
static function render(){
$menu_items = self::get();
?><div class="menu"><ul><?php while ($item = mysql_fetch_assoc($menu_items)) { ?>
<li><a href="<?php
if(empty($item["is_external"]))
{
echo self::get_page_url($item["page_id"]);
}
else if($item["is_external"] = 1)
{
echo $item["url"];
}
?>"><?php echo $item["name"] ?></a>
</li> <?php } ?></ul></div><?php
}

OOP PHP MySQL return multiple rows and variable

I am new w/ OPP and big pardon if my question maybe too simple :)
Table category, navigation, etc contains multiple rows (category : samsung, apple, etc; and navigation : about us, terms, etc) and both stand as Menu in all pages (home, product,etc)
My old php code and work good is below
<div id="categories">
<ul>
<?
$mydbcategories = new myDBC();
$resultcategories = $mydbcategories->runQuery("SELECT * FROM `category`");
while ($rowcategories = $mydbcategories->runFetchArray($resultcategories)) {
echo '<li>'.$rowcategories[title].'</li>';
}
?>
</ul>
</div>
<div id="navigation">
<ul>
<?
$mydbnavigation = new myDBC();
$resultnavigation = $mydbnavigation->runQuery("SELECT * FROM `navigation`");
while ($rownavigation = $mydbnavigation->runFetchArray($resultnavigation)) { echo '<li>'.$rownavigation [title].'</li>';
}
?>
</ul>
</div>
I would like to implement OOP PHP and create class then store in classes.php
<?
class Menu{
var $title;
var $url;
function setMenu($db){
$mydbMenu= new myDBC();
$resultmenu = $mydbMenu->runQuery("SELECT * FROM `$db`");
$resultmenurows = mysqli_num_rows($resultmenu);
while ($rowmenu = $mydbMenu->runFetchArray($resultmenu)){
$this->title = $rowmenu[title];
$this->url = $rowmenu[url];
}
}
function getTitle() { return $this->title;}
function getUrl() { return $this->url;}
}
?>
Then i'm edit my old code with new one below;
<div id="categories">
<ul>
<?
$catmenu = new Menu();
while ($catmenu ->setMenu('category')) {
echo '<li>'.$catmenu->getTitle().'</li>';
}
?>
</ul>
</div>
<div id="navigation">
<ul>
<?
$navmenu = new Menu();
while ($navmenu ->setMenu('category')) {
echo '<li>'.$navmenu ->getTitle().'</li>';
}
?>
</ul>
</div>
I tested and error maybe because there are multiple rows (from table) in the setMenu func.
How can i return this multiple rows ? should i use array ?
Please help me to solve this and any reply really very appreciate
You are coding PHP4 OOP style, this is very outdated. Don't use var, use public, protected, private.
$this->title = $rowmenu[title] in here, title is used as a constant (no quotes), proper: $this->title = $rowmenu['title'], same with $rowcategories[title]
"SELECT * FROM $db" is this correct? Or do you mean SELECT * FROM menu WHERE xxx='" . $db . "', do you catch errors if the lookup fails?
You should also look at PHP design patterns and code style to improve!
Try following PHP code
<?
class Menu {
var $title;
var $url;
function setMenu($db) {
$mydbMenu = new myDBC();
$resultmenu = $mydbMenu->runQuery("SELECT * FROM `$db`");
$resultmenurows = mysqli_num_rows($resultmenu);
$this->title = array();
$this->url = array();
while ($rowmenu = $mydbMenu->runFetchArray($resultmenu)) {
$this->title[] = $rowmenu['title'];
$this->url[] = $rowmenu['url'];
}
}
function getTitle($ind) {
return $this->title[$ind];
}
function getUrl($ind) {
return $this->url[$ind];
}
}
?>
And HTML
<div id="categories">
<ul>
<?
$catmenu = new Menu();
$catmenu->setMenu('category');
$i = 0;
while ($catmenu->getTitle($i)) {
echo '<li>' . $catmenu->getTitle($i) . '</li>';
$i++;
}
?>
</ul>
</div>
<div id="navigation">
<ul>
<?
$navmenu = new Menu();
$navmenu->setMenu('navigation');
while ($navmenu->getTitle($i)) {
echo '<li>' . $navmenu->getTitle($i) . '</li>';
$i++;
}
?>
</ul>
</div>

Categories