Convert PHP 5.6 news script to 7.2 - php

I have a PHP 5.6 compatible script. Now in my server i have to change to php7.2, but this script get error everywhere.I want to convert it myself but my knowledge does not reach much. I have been advancing little by little with several tutorials but I have already been stuck without being able to continue.
I need help to do it myself. This is just an example of the code, but by solving this, I think I will be able to convert the whole site.
The error:
[01-Nov-2018 09:16:58 UTC] PHP Fatal error: Uncaught Error: Call to a member function query() on null in /home/xxxx/public_html/incs/generales/fullnews.php:433
Stack trace:
#0 /home/xxxx/public_html/news.php(16): FullNewsInc->getFullNews('18880', 'fullnews')
#1 {main}
thrown in /home/xxxx/public_html/incs/generales/fullnews.php on line 433
the news.php page
<?php
require_once './db.php'; $db = new DB_Sql(); $db2 = new DB_Sql();
include_once './fullnews.php';
$fullnewsinc = new FullNewsInc($db);
$newsId = $_REQUEST['newsId'];
$system = $_REQUEST['system'];
$cat = $_REQUEST['categorie'];
?>
<section id="main-content" itemscope itemtype="https://schema.org/Article">
<div id="latest">
<section class="noticias">
<div class="clearfix"></div>
<?php $fullnewsinc->getFullNews($newsId, 'fullnews'); ?>
</section>
<aside class="sidebar">
</aside>
</div> <!-- END Latest -->
<div class="clearfix"></div>
</section>
This is the function in fullnews.php
<?php
class FullNewsInc {
var $db;
public function __construct()
{
// Constructor's functionality here, if you have any.
}
public function FullNewsInc(&$db) {
$this->db = &$db; self::__construct();
}
function getFullNews($newsId = '', $template = 'theme_fullnews') {
$sql = "SELECT x FROM";
$this->db->query($sql);
while($this->db->next_record()) {
$newsId = $this->db->f("newsId");
$subject = $this->db->f("subject");
$shortNews = $this->db->f("shortNews");
$longNews = $this->db->f("longNews");
$iconId = $this->db->f("iconId");
$source = $this->db->f("source");
include "./theme/".$template.".tpl.php";
}
}
}?>
This is the db.php
<?php
if (!class_exists('DB_Sql')){
class DB_Sql {
public function __construct()
{
// Constructor's public functionality here, if you have any.
}
public $Host = "xxx";
public $Database = "xxxx";
public $User = "xxx";
public $Password = "xxxxx";
public $Auto_Free = 1;
public $Debug = 0;
public $Halt_On_Error = "no"; // "yes", "no", "report"
public $Record = array();
public $Row;
public $Errno = 0;
public $Error = "";
public $Link_ID = 0;
public $Query_ID = 0;
public function DB_Sql($query = "") {
$this->query($query);self::__construct();
}
public function link_id() {
return $this->Link_ID;self::__construct();
}
public function query_id() {
return $this->Query_ID;self::__construct();
}
public function connect($Database = "", $Host = "", $User = "", $Password = "") {
if ("" == $Database)
$Database = $this->Database;
if ("" == $Host)
$Host = $this->Host;
if ("" == $User)
$User = $this->User;
if ("" == $Password)
$Password = $this->Password;
if ( 0 == $this->Link_ID ) {
$this->Link_ID=#mysqli_connect($Host, $User, $Password, $Database);
if (!$this->Link_ID) {
$this->halt("connect failed - Please check your database settings.");
die;
}
if (!#mysqli_select_db($Database,$this->Link_ID)) {
$this->halt("cannot use database ".$this->Database." - Please check your database settings.");
die;
}
}
return $this->Link_ID;
}
public function free() {
#mysql_free_result($this->Query_ID);
$this->Query_ID = 0;self::__construct();
}
public function query($Query_String) {
if ($Query_String == "") {
return 0;
}
if (!$this->connect()) {
return 0;
}
# New query, discard previous result.
if ($this->Query_ID) {
$this->free();
}
if ($this->Debug)
printf("Debug: query = %s<br />\n", $Query_String);
$this->Query_ID = #mysqli_connect($Query_String,$this->Link_ID);
$this->Row = 0;
$this->Errno = mysql_errno();
$this->Error = mysql_error();
if (!$this->Query_ID) {
$this->halt("Invalid SQL: ".$Query_String);
}
return $this->Query_ID;self::__construct();
}
public function next_record() {
if (!$this->Query_ID) {
$this->halt("next_record called with no query pending.");
return 0;
}
$this->Record = #mysqli_fetch_array($this->Query_ID);
$this->Row += 1;
$this->Errno = mysql_errno();
$this->Error = mysql_error();
$stat = is_array($this->Record);
if (!$stat && $this->Auto_Free) {
$this->free();
}
return $stat;self::__construct();
}
public function affected_rows() {
return #mysql_affected_rows($this->Link_ID);self::__construct();
}
public function num_rows() {
return #mysql_num_rows($this->Query_ID);self::__construct();
}
public function num_fields() {
return #mysql_num_fields($this->Query_ID);self::__construct();
}
public function nf() {
return $this->num_rows();self::__construct();
}
public function np() {
print $this->num_rows();self::__construct();
}
public function f($Name) {
return $this->Record[$Name];self::__construct();
}
public function p($Name) {
print $this->Record[$Name];self::__construct();
}
public function halt($msg) {
$this->Error = #mysqli_error($this->Link_ID);
$this->Errno = #mysqli_errno($this->Link_ID);
if ($this->Halt_On_Error == "no")
return;
$this->haltmsg($msg);
if ($this->Halt_On_Error != "report")
die("Session halted.");self::__construct();
}
public function haltmsg($msg) {
printf("<b>Database error:</b> %s<br />\n", $msg);
printf("<b>MySQL Error</b>: %s (%s)<br />\n",
$this->Errno,
$this->Error);self::__construct();
}
}
}
The theme_fullnews tamplate:
<article>
<header>
<h1 itemprop="name" ><?php echo $subject; ?></h1>
<h2 itemprop="articleSection"><?php echo $shortNews; ?></h2>
<span itemprop="datePublished" content=" <?php echo $newDate; ?>"> <?php echo time_elapsed_string($timestamp); ?> </span>
</div>
</header>
<section>
<?php $longNews); ?>
</section>
</article>

What's happening here is that you have functions inside your class with the same name as the class. PHP is warning you that the ability to do this is going to be removed in future.
For example, you have your php class
<?php
class FullNewsInc {
public function __construct( )
{
// Constructor's public functionality here, if you have any.
}
/**
Some code here
**/
public function FullNewsInc($db){
$this->db = &$db;
}
/**
More code here
**/
}
The class and method name match, so you would need to change your PHP class to use the __construct method, which you've written, but it is currently blank.
class FullNewsInc {
public function __construct( $db )
{
// Constructor's public functionality here, if you have any.
$this->db = &$db;
}
/**
Some code here
**/
//The FullNewsInc method has been deleted. The code contained within was moved to the __construct
/**
More code here
**/
}
There is more information available on the php.net site http://php.net/manual/en/language.oop5.decon.php

Related

How to display a logged in user name in my oop php project?

When I try to display a username from my logged in user in my project, I get this error Undefined variable: user_id in C:\xampp\htdocs\login1\index.php on line 2
Query Failed!!!You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1 . Here is my code:
index.php:
<?php require_once("includes/header.php"); ?>
<?php $user = User::find_user_by_id($user_id); ?>
<?php
if (!$session->is_signed_in()) {
redirect("login.php");
}
?>
<div class="row">
<div class="col-md-12">
<h1>Home</h1>
<h1>Hello, <?php echo $user->username; ?></h1>
</div>
<?php require_once("includes/footer.php"); ?>
user.php:
class User
{
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
private function has_the_attribute($the_attribute)
{
$object_properties = get_object_vars($this);
return array_key_exists($the_attribute, $object_properties);
}
public static function instantation($the_record)
{
$the_object = new self;
foreach ($the_record as $the_attribute => $value) {
if ($the_object->has_the_attribute($the_attribute)) {
$the_object->$the_attribute = $value;
}
}
return $the_object;
}
public static function find_this_query($sql)
{
global $database;
$result_set = $database->query($sql);
$the_object_array = [];
while ($row = mysqli_fetch_array($result_set)) {
$the_object_array[] = self::instantation($row);
}
return $the_object_array;
}
public static function find_all_users()
{
return self::find_this_query("SELECT * FROM users");
}
public static function find_user_by_id($user_id)
{
global $database;
$the_result_array = self::find_this_query("SELECT * FROM users WHERE id=$user_id");
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
public static function verify_user($username, $password)
{
global $database;
$username = $database->escape_string($username);
$password = $database->escape_string($password);
$sql = "SELECT * FROM users WHERE ";
$sql .= "username = '{$username}' ";
$sql .= "AND password = '{$password}'";
$the_result_array = self::find_this_query($sql);
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
}
$user = new User();
session.php:
<?php
class Session
{
private $signed_in = false;
public $user_id;
public $message;
public function __construct()
{
session_start();
$this->check_the_login();
$this->check_message();
}
public function login($user)
{
if ($user) {
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->signed_in = true;
}
}
public function logout()
{
unset($_SESSION['user_id']);
unset($this->user_id);
$this->signed_in = false;
}
private function check_the_login()
{
if (isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->signed_in = true;
} else {
unset($this->user_id);
$this->signed_in = false;
}
}
public function is_signed_in()
{
return $this->signed_in;
}
public function message($msg="")
{
if (!empty($msg)) {
$_SESSION['message'] = $msg;
} else {
return $this->message;
}
}
public function check_message()
{
if (isset($_SESSION['message'])) {
$this->message = $_SESSION['message'];
unset($_SESSION['message']);
} else {
$this->message = "";
}
}
}
$session = new Session();

How to dynamically display user name from the database after log in?

I need to dynamically display user name from logged in user in my OOP PHP project. I can display it when I type right id from the database but it shows error when I try to define property $user_id in my function find_by_id. I need help on how to define $user_id variable. Here is my code:
index.php
<?php $user = User::find_by_id($user_id); ?>
<h1>Hello, <?php echo $user->username; ?></h1>
user.php
<?php
class User
{
protected static $db_table = "users";
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
private function has_the_attribute($the_attribute)
{
$object_properties = get_object_vars($this);
return array_key_exists($the_attribute, $object_properties);
}
public static function instantation($the_record)
{
$the_object = new self;
foreach ($the_record as $the_attribute => $value) {
if ($the_object->has_the_attribute($the_attribute)) {
$the_object->$the_attribute = $value;
}
}
return $the_object;
}
public static function find_this_query($sql)
{
global $database;
$result_set = $database->query($sql);
$the_object_array = [];
while ($row = mysqli_fetch_array($result_set)) {
$the_object_array[] = self::instantation($row);
}
return $the_object_array;
}
public static function find_all()
{
return self::find_this_query("SELECT * FROM " . static::$db_table . " ");
}
public static function find_by_id($user_id)
{
global $database;
$the_result_array = self::find_this_query("SELECT * FROM " . self::$db_table . " WHERE id = $user_id");
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
public static function verify_user($username, $password)
{
global $database;
$username = $database->escape_string($username);
$password = $database->escape_string($password);
$sql = "SELECT * FROM " . self::$db_table . " WHERE ";
$sql .= "username = '{$username}' ";
$sql .= "AND password = '{$password}'";
$the_result_array = self::find_this_query($sql);
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
}
$user = new User();
session.php
<?php
class Session
{
private $signed_in = false;
public $user_id;
public $message;
public function __construct()
{
session_start();
$this->check_the_login();
$this->check_message();
}
public function login($user)
{
if ($user) {
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->signed_in = true;
}
}
public function logout()
{
unset($_SESSION['user_id']);
unset($this->user_id);
$this->signed_in = false;
}
private function check_the_login()
{
if (isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->signed_in = true;
} else {
unset($this->user_id);
$this->signed_in = false;
}
}
public function is_signed_in()
{
return $this->signed_in;
}
public function message($msg="")
{
if (!empty($msg)) {
$_SESSION['message'] = $msg;
} else {
return $this->message;
}
}
public function check_message()
{
if (isset($_SESSION['message'])) {
$this->message = $_SESSION['message'];
unset($_SESSION['message']);
} else {
$this->message = "";
}
}
}
$session = new Session();
For the sake of marking this as accepted, what you need to do is actually pass the user ID of the and not just an uninitialised variable, if your instance you are storing it in the session so I presume it would be:
<?php $user = User::find_by_id($_SESSION['user_id']); ?>
Note: To make your templating cleaner, you can use the shorthand syntax for echo:
<h1>Hello, <?= $user->username; ?></h1>
Another thing to note is that you have built a Session class, however you are still for some reason accessing the data through $_SESSION which doesn't make sense, make some setters / getters for it. Finally, sessions are something that you'll be using a lot therefore it would be worth making that class static.
Reading Material
echo

How to get everything outside the database with foreach and class

I have a problem. I want some data out my database.
I have two page's a categorie.php here I want that he shows everything out the database. And I have a second page. Here are my classes. I have trying a foreach on the categorie.php but if I do that, than shows he 1 thing out the database 4 times the same and not the another data.
Below you can see my code.
I hope that you can help me.
Thank you.
This is my categorie.php
<?php
require_once '../app/functions/second.php';
require_once '../app/db/dbpassword.php';
require_once 'include/head.php';
if (isset($_GET['categorie']) && !empty($_GET['categorie'])) {
$id = $_GET['categorie'];
$dbh = new PDO("mysql:host=$host; dbname=$dbname;", $usernamedb,
$passworddb);
$cate = new Categorie($dbh);
$cate->loadCate($id);
// $page->loadId($id);
$categorie = $cate->getCategorie();
$titel = ucwords($categorie);
?>
<h2 class="center_h2"><?= $titel ?></h2>
<?php foreach ($cate as $key) {
$titelart = $cate->getTitel();
$beschrijving = $cate->getBeschrijving();
$plaatje = $cate->getImage();
$id = $cate->getId();
var_dump($titelart);
} ?>
<?php
} else {
echo "Dit bericht is verwijderd of is verplaats.";
}
require_once 'include/footer.php';
?>
This is my class page
<?php
class Categorie {
protected $dbh;
public function __construct($new_dbh){
$this->dbh = $new_dbh;
}
public function loadCate($cate){
$query = $this->dbh->prepare('SELECT * FROM schilderijen WHERE categorie=?');
$query->execute(array($cate));
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
$this->id = $row->id;
$this->categorie = $row->categorie;
$this->titel = $row->titel;
$this->beschrijving = $row->beschrijving;
$this->plaatje = $row->plaatje;
}
}
public function getId(){
return $this->id;
}
public function getCategorie(){
return $this->categorie;
}
public function getTitel(){
return $this->titel;
}
public function getBeschrijving(){
return $this->beschrijving;
}
public function getImage(){
return $this->plaatje;
}
}
?>
Ok so you have a problem with the use of your class. In the while after your SQL request, you apply the value the instance variable like $this->id = $row->id; but this variable will be rewrite with the next row value.
Use a static function for your SQL request and return an array of Categorie like that :
class Categorie {
protected $id, $categorie, $title, $beschrijving, $plaatje;
public function __construct($id, $categorie, $title, $beschrijving, $plaatje){
$this->id = $id;
$this->categorie = $categorie;
$this->title = $title;
$this->beschrijving = $beschrijving;
$this->plaatje = $plaatje;
}
public static function loadCate($dbh, $cate){
$query = $dbh->prepare('SELECT * FROM schilderijen WHERE categorie=?');
$query->execute(array($cate));
$res = array();
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
$res[] = new Categorie($row->id, $row->categorie, $row->titel, $row->beschrijving, $row->plaatje);
}
return $res;
}
public function getId(){
return $this->id;
}
public function getCategorie(){
return $this->categorie;
}
public function getTitle(){
return $this->title;
}
public function getBeschrijving(){
return $this->beschrijving;
}
public function getImage(){
return $this->plaatje;
}
}
And you can use it like that:
$categories = Categorie::loadCate($dbh, $id);
foreach($categories as $categorie){
var_dump($categorie->getTitle());
}

PHP - What is wrong? Learning MVC - Beginner

Hy,
i started learning PHP and i created a simple MVC Style Codebase.
The Script just generates a random number and displays this numer. I also write a function to display the number shown before but it does not work. The value is empty. Can you help me out, i have no clue whats wrong and there is no php error thrown.
view.php
<?php
class View
{
private $model;
private $view;
public function __construct()
{
$this->model = new Model();
}
public function output()
{
echo 'Current Entry: ';
echo $this->model->getData();
echo '<br />';
echo 'Update';
echo '<br />';
echo 'Last';
}
public function getModel()
{
return $this->model;
}
}
controller.php
<?php
class Controller
{
private $model;
private $view;
public function __construct($view)
{
$this->view = $view;
$this->model = $this->view->getModel();
}
public function get($request)
{
if (isset($request['action']))
{
if ($request['action'] === 'update')
{
for ($i = 0; $i<6; $i++)
{
$a .= mt_rand(0,9);
}
$this->model->setData($a);
}
elseif ($request['action'] === 'preview')
{
$this->model->setLast();
}
else
{
$this->model->setData('Wrong Action');
}
}
else
{
$this->model->setData('Bad Request');
}
}
}
model.php
<?php
class Model
{
private $data;
private $last;
public function __construct()
{
$this->data = 'Default';
}
public function setData($set)
{
if ( ! (($set == 'Wrong Action') && ($set == 'Bad Request')))
{
$this->last = $this->data;
}
$this->data = $set;
}
public function getData()
{
return $this->data;
}
public function setLast()
{
$this->data = $this->last;
}
public function getLast()
{
return $this->last;
}
}
index.php
<?php
require_once 'controller.php';
require_once 'view.php';
require_once 'model.php';
$view = new View();
$controller = new Controller($view);
if (isset($_GET) && !empty($_GET)) {
$controller->get($_GET);
}
$view->output();
Are there any other, bad mistakes in the Script?
Any input very welcome! :)
The problem with your code is that PHP does not preserve variable values between requests, therefore, when you set your $model->last value here:
$this->last = $this->data;
It gets reset on your next request.
You may want to store $last value in a session or a cookie instead. Something like:
$_SESSION['last'] = $this->data;
And then when you are instantiating your model you could initialize it with a value stored in a session if available:
index.php - add session_start() at the beginning
model.php:
public function __construct()
{
$this->data = isset($_SESSION['last']) ? $_SESSION['last'] : 'Default';
}
public function setData($set)
{
$this->data = $set;
if ( ! (($set == 'Wrong Action') && ($set == 'Bad Request')))
{
$_SESSION['last'] = $this->data;
}
}
controller.php
elseif ($request['action'] === 'preview')
{
//Remove this
//$this->model->setLast();
}

How can I complete my dropdown with database data?

I'm building an application based on Slim Framework, and I already have some working code. To return a JSON response with a list of projects, I wrote the following:
Controller class (controllerProyectos.php)
<?php
require "transferController/transferProyectos.php";
class NombreProyecto {
public function getProyectos() {
$list = array();
foreach ($this->fillObject() as $sKey => $oValue) {
$list[] = array(
'id' => $oValue->getId(),
'nombre_proyecto' => $oValue->getNombre(),
'state' => $oValue->getState(),
);
}
return $list;
}
private function fillObject() {
$aObjects = array();
for ($i = 0; $i < 5; $i++) {
$oTransfer = new TransferProyeCtr();
$oTransfer->setId($i);
$oTransfer->setNombre("proyecto " . $i);
$oTransfer->setState(1);
$aObjects[] = $oTransfer;
}
return $aObjects;
}
}
Front controller (index.php)
<?php
require "vendor/autoload.php";
$sPathApi = "/api/sistemaTareas/";
$app = new \Slim\Slim();
$app->get($sPathApi . $sVersion . 'proyectos', function () {
require "controller/controllerProyectos.php";
$oProyecto = new NombreProyecto();
header('Content-Type: application/json');
echo json_encode($oProyecto->getProyectos());
exit();
});
Model class (transferProyectos.php)
<?php
class TransferProyeCtr {
private $sNombre;
private $iId;
private $iState;
public function getNombre() {
return $this->sNombre;
}
public function setNombre($nombre) {
$this->sNombre = $nombre;
}
public function getId() {
return $this->iId;
}
public function setId($Id) {
$this->iId = $Id;
}
public function getState() {
return $this->iState;
}
public function setState($state) {
$this->iState = $state;
}
}
As you can see I'm using some mockup data in the controller. When I do an AJAX request to my application, I get the following result in a dropdown:
- proyecto 1
- proyecto 2
- proyecto 3
- proyecto 4
- proyecto 5
So far everything is working as expected. But I'd like to return real data from the database in that controller.
I wrote a function (inside bdconnection.php file) to open the database connection:
<?php
function connect_db() {
$server = 'localhost';
$user = 'root';
$pass = '123asd';
$database = 'bd_actividades';
$connection = new mysqli($server, $user, $pass, $database);
return $connection;
}
I think that in my controller I need something like:
public function getPro() {
require "sistema/bdconnection.php";
$sql = "select pro_nombre FROM act_proyecto";
try {
$db = connect_db();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
} catch(PDOException $e) {
echo json_encode($e->getMessage());
}
}
And replace $oTransfer->setNombre("proyecto " . $i); for $oTransfer->setNombre($users);, but I'm not sure.
Just to give you guys a little more detail about my application, here will go the files structure and database data:

Categories