Get datas from table and display with OOP - php

How I can get the comments with OOP from my database? Im trying with below code but it displaying the error. Im new using the classes and I git stuck here trying to reselve this issue.
Below is the code in class Comments:
function getComments(){
$komentet = array();
$connect = mysql_connect("localhost","root","") or die(mysql_error());
$select = mysql_select_db("profile") or die(mysql_error());
$id = $_SESSION['id'];
$result = mysql_query("SELECT * FROM posts order by mycoment DESC") or die(mysql_error());
while($row = mysql_fetch_array($result)){
array_push($komentet,$row['mycoment']);
}
return $komentet;
}
With the below code, Im trying to display the datas in my web page but I can not.
<?php
$komentet = $comm->getComments();
foreach($komentet as $cm){
echo "<tr><td>".$cm."</td></tr>";
}
?>
It returning the following error:
Notice: Undefined variable: comm in C:\xampp\htdocs\profile\uprofile.php on line 194
Fatal error: Call to a member function getComments() on null in C:\xampp\htdocs\profile\uprofile.php on line 194
Full classs is the code below:
<?php
class Comments {
public $datetime;
public $comment;
function insertDate(){
$connect = mysql_connect("localhost","root","") or die(mysql_error());
$select = mysql_select_db("profile") or die(mysql_error());
$id = $_SESSION['id'];
$this->datetime = date("F j, Y, g:i a");
$sql = "INSERT INTO posts(userid, mycoment, time) VALUES('$id','$this->comment','$this->datetime')";
if(mysql_query($sql)){
echo "Comment Added";
}else{
echo "Comment Failed";
}
}
function getComments(){
$komentet = array();
$connect = mysql_connect("localhost","root","") or die(mysql_error());
$select = mysql_select_db("profile") or die(mysql_error());
$id = $_SESSION['id'];
$result = mysql_query("SELECT * FROM posts order by mycoment DESC") or die(mysql_error());
while($row = mysql_fetch_array($result)){
array_push($komentet,$row['mycoment']);
}
return $komentet;
}
}

the problem you have is you crate the instance of the class Comments inside of a condition, which does not pass:
require_once('comments.php');
if(isset($_POST['postsomething'])){
$comm = new Comments();
$comm->comment = trim($_POST['mycoment']);
$comm->insertDate();
}
$komentet = $comm->getComments();
foreach($komentet as $cm){
echo "<tr><td>".$cm."</td></tr>";
}
so you should alter it like this:
require_once('comments.php');
$comm = new Comments();
if(isset($_POST['postsomething'])){
$comm->comment = trim($_POST['mycoment']);
$comm->insertDate();
}
$komentet = $comm->getComments();
foreach($komentet as $cm){
echo "<tr><td>".$cm."</td></tr>";
}
I've made a little work for you and refactored the Comments class using mysqli extension and ridding som DRY (Don't Repeat Yourself) breaches. I highly suggest you to stick on mysqli and avoid any code duplication.
class Comments
{
public $datetime;
public $comment;
function insertDate(){
$id = $_SESSION['id'];
$this->datetime = date("F j, Y, g:i a");
$sql = "INSERT INTO posts(userid, mycoment, time) VALUES('$id', '$this->comment', '$this->datetime')";
if($this->getConnection()->query($sql)){
echo "Comment Added";
} else{
echo "Comment Failed";
}
}
function getComments(){
$komentet = array();
$result = $this->getConnection()->query("SELECT * FROM posts order by mycoment DESC");
while($row = $result->fetch_assoc()){
array_push($komentet, $row['mycoment']);
}
return $komentet;
}
private function getConnection(){
if($this->connection === null)
$this->connection = mysqli_connect("localhost", "root", "", "profile") or die(mysqli_error($this->connection));
return $this->connection;
}
/** #var mysqli */
private $connection;
}

Related

Using Php mysql query do not get data from php class, though there are data

class book {
function __construct() {
$conn = mysql_connect('localhost', 'root', '') or die('can nit connect to DB');
mysql_select_db('atomic_project', $conn) or die('can not connect to db');
}
public function listView() {
$allData = array();
$query = "SELECT * FROM `book`";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
$allData [] = $row;
}
return $allData;
}
}
My index page
$listViewObj = new book();
$allData = $listViewObj->listView();
echo "<pre>";
print_r($allData);
echo "<pre>";
Here is my code and the table here is my table data , i can insert data into table but no row is found
i can't understand why no data is shown, please help me
<?php
class book {
public function listView() {
$conn = mysql_connect('localhost', 'root', '') or die('can nit connect to DB');
mysql_select_db('atomic_project', $conn) or die('can not connect to db');
$allData = array();
$query = "SELECT * FROM `book`";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
//echo "<pre>";
//print_r($row);
$allData [] = $row;
}
return $allData;
}
}
book::listView(); //scope resolution operator
?>
or calling function by object
$obj = new book();
$obj->listView();

Unable to correctly return and store my mysqli result

I am trying to return my mysqli result and store it in a static variable so that I can pass it on to another function. As you can see below the second function needs to be able to read the result from the first one. The scope problem should have been fixed with returning and storing it then storing my function within a variable inside the second function:
What am I doing wrong? Why is this not working? It works for things like my database connection.
function profile_info() {
$connection = database();
static $result;
$query = "SELECT id, name, first_name, last_name, birthdate, occupation, status
FROM users";
$result = mysqli_query($connection, $query);
return $result;
}
I then store the returned result within my function below `$result = profile_info():
function users_overview () {
$connection = database();
$result = profile_info();
echo "<div id='users_overview'>";
while($row = mysqli_fetch_array($result)) {
if (!empty($row['status']) && $row['status'] == 'Online') {
$status = "<div class='online'></div>";
}
else {
$status = "<div class='offline'></div>";
}
include 'php/core/age_converter.php';
include 'php/includes/profile_information.php';
}
echo "</div>";
}
users_overview();
Seems two time $connection = database(); is being called when you include the call to profile_info(); from users_overview ()
Check now if it works now,
function profile_info() {
$connection = database();
static $result;
$query = "SELECT id, name, first_name, last_name, birthdate, occupation, status
FROM users";
$result = mysqli_query($connection, $query);
return $result;
}
function users_overview () {
$result = profile_info();
echo "<div id='users_overview'>";
while($row = mysqli_fetch_array($result)) {
if (!empty($row['status']) && $row['status'] == 'Online') {
$status = "<div class='online'></div>";
}
else {
$status = "<div class='offline'></div>";
}
include 'php/core/age_converter.php';
include 'php/includes/profile_information.php';
}
echo "</div>";
}
users_overview();
As you don't want to globally define the variable and you can use the OOPs Concept. Data will be wrap in object. I wrote a code for you.
class user{
private $conn;
private $result;
function __construct(){
$conn1 = new mysqli("localhost", "root", "", "siteData");
$this->setConn($conn1);
}
public function profile_info(){
$query = "SELECT * FROM users";
$num = $this->getConn();
$result = $num->query($query);
return $result;
}
function users_overview () {
$result = $this->profile_info();
while($row = mysqli_fetch_array($result)){
//get your result
}
}
function setConn($conn1){
$this->conn = $conn1;
return $this->conn;
}
function getConn(){
return $this->conn;
}
}
$temp = new user();
$temp->users_overview();

PHP infinite loop issue

I can get the correct code to work, but i want to be able to use objects and methods, which doesn't work. The same entry in the database is repeated until the query crashes. I saw other people that had queries inside of the while statement, but i thought that the method i am using should only query the statement once, but im likely wrong. Thanks.
<?php
include '/functions/MySQL.php';
$MySQL = new MySQL;
$con = mysqli_connect("host","user","password","db");
$result = mysqli_query($con,"SELECT * FROM reportLogger WHERE Moderator='jackginger'");
while($row = mysqli_fetch_array($MySQL->getReports('jackginger'))) {
$time = $row['Time'];
$moderator = $row['Moderator'];
$reason = $row['Reason'];
// Now for each looped row
echo "<tr><td>".$time."</td><td>".$moderator."</td><td>".$reason."</td></tr>";
}
?>
Seperate class
public function __construct(){
$this->con = mysqli_connect("localhost","root","pass","Minecraft");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
public function getUUID($username) {
$result = mysqli_query($this->con,"SELECT UUID FROM loginLogger WHERE Username='" . $username . "'");
return mysqli_fetch_array($result)[0];
}
public function getReports($username) {
$result = mysqli_query($this->con,"SELECT * FROM reportLogger WHERE UUID='" . $this->getUUID($username) . "'");
return $result;
}
Each time you call while($row = mysqli_fetch_array($MySQL->getReports('jackginger'))) you are making a new query, so it's fetching the samething over and over again.
a solution could be:
<?php
include '/functions/MySQL.php';
$MySQL = new MySQL;
$con = mysqli_connect("host","user","password","db");
$result = mysqli_query($con,"SELECT * FROM reportLogger WHERE Moderator='jackginger'");
$store = $MySQL->getReports('jackginger');
while($row = mysqli_fetch_array($store)) {
$time = $row['Time'];
$moderator = $row['Moderator'];
$reason = $row['Reason'];
// Now for each looped row
echo "<tr><td>".$time."</td><td>".$moderator."</td><td>".$reason."</td></tr>";
}
?>

Get the value of return within class

Goodday. The question is, how can I get the return value and pass to my other php file?
myclass.php file
class myClass{
function banner(){
$sql = "Select * From tblBanner";
$query = mysql_query($sql) or die (mysql_error());
$row = mysql_fetch_assoc($query);
$banner = $row;
return $banner;
}
}
my index.php file
include 'myclass.php';
$banner = new myclass;
$ban = $banner->banner;
echo $ban;
This is what im trying to do. Im a newbie so spare with me. Thank you.
Like I already wrote in the comments, $banner->banner would be a property of the class "myClass". But you want to get a method, so you have to use $banner->banner().
myclass.php file
class myClass{
function banner(){
$sql = "Select * From tblBanner";
$query = mysql_query($sql) or die (mysql_error());
$row = mysql_fetch_assoc($query);
$banner = $row;
return $banner;
}
}
my index.php file
include 'myclass.php';
$banner = new myclass;
$ban = $banner->banner();
// example for array:
foreach($ban as $banner) {
echo $banner;
}
// example for string:
echo $ban;
An example for $banner->banner:
myclass.php file
class myClass{
public $banner = 'Banner Property';
function banner(){
$sql = "Select * From tblBanner";
$query = mysql_query($sql) or die (mysql_error());
$row = mysql_fetch_assoc($query);
$banner = $row;
return $banner;
}
}
my index.php file
include 'myclass.php';
$banner = new myclass;
$ban = $banner->banner;
echo $ban;

Errors when adding data to a database with PHP

I have to make a web app that gets information from my database, that gets its info from an API). Then I have to show items under certain conditions.
But when I try to add the data from the API, I got a strange message:
Notice: Trying to get property of non-object in c:\xampp\htdocs\IMP03\inleveropdracht3\libs\php\function.php on line 21
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\IMP03\inleveropdracht3\libs\php\function.php on line 21
Here is my PHP code:
<?php
require_once 'settings.php';
$mysqli = mysqli_connect($db_host, $db_user, $db_password, $db_database);
if (mysqli_connect_error()) {
echo mysqli_connect_error($mysqli) . "We are not able to connect to the online database";
}
jsondecode($mysqli);
if (isset($_GET['club']) && !empty($_GET['club'])) {
jsondecode($mysqli);
} else if (isset($_GET['thuisPoint']) && !empty($_GET['thuisPoint']) && ($_GET['uitPoint']) && ($_GET['uitPoint'])) {
updatePoints($mysqli);
} else {
getWedstrijd($mysqli);
}
function jsondecode($mysqli) {
$apiLink = 'http://docent.cmi.hr.nl/moora/imp03/api/wedstrijden?club=';
// $club = $_GET['club'];
$data = json_decode(file_get_contents($apiLink . "Ajax"));
foreach ($data->data as $info) {
$thuisClub = $info->homeClub;
$uitClub = $info->awayClub;
addWestrijden($mysqli, $thuisClub, $uitClub);
}
}
//querys
function addWestrijden($mysqli, $thuisClub, $uitClub) {
$query = "INSERT INTO wedstrijd VALUES(null, '$thuisClub', '$uitClub')";
$resultAddWedstrijd = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
getWedstrijd($mysqli);
}
function getWedstrijd($mysqli) {
$query = "SELECT * FROM wedstrijd ORDER BY thuisClub DESC";
$resultGetWedstijd = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
while ($result = mysqli_fetch_assoc($resultGetWedstijd)) {
$rows [] = $result;
}
header("Content-Type: application/json");
echo json_encode($rows);
exit;
}
function updatePoints($mysqli) {
$id = $_GET['id'];
$thuisPoints = $_GET['thuisPoint'];
$uitPoints = $_GET['uitPoint'];
$query = "UPDATE wedstrijd "
. "SET thuisPunt = '$thuisPoints', uitPunt = '$uitPoints') "
. "WHERE id = '$id'";
mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
getWedstrijd($mysqli);
}
I did modify it a bit so it would add data from the API. I really would appreciate it if someone could help me.
Change your foreach to:
foreach ($data as $data => $info)

Categories