Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > IT форум > Общие вопросы по программированию, компьютерный форум
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 14.10.2021, 11:07   #1
Nick_1
Новичок
Джуниор
 
Регистрация: 14.10.2021
Сообщений: 2
По умолчанию Не запускается мини приложение

Таблица news в БД test как видно имеется и доступ к ней есть:

https://cloud.mail.ru/public/gJrD/6b5pJkfXa

<?php
$dsn = 'mysql:host=127.0.0.1;dbname=test';
$dbh = new PDO($dsn, 'root', '');
$sth = $dbh->prepare('SELECT * FROM news');
$sth->execute();
$data = $sth->fetchAll();
var_dump($data);

Реузльтат при выводе инфы из БД:
array(3) { [0]=> array(8) { ["id"]=> string(1) "1" [0]=> string(1) "1" ["title"]=> string(50) "Большие слоны идут на север" [1]=> string(50) "Большие слоны идут на се-вер" ["lead"]=> string(0) "" [2]=> string(0) "" ["author_id"]=> string(1) "1" [3]=> string(1) "1" } [1]=> array(8) { ["id"]=> string(1) "2" [0]=> string(1) "2" ["title"]=> string(58) "Метеорит упал рядом с человеком" [1]=> string(58) "Метеорит упал рядом с человеком" ["lead"]=> string(0) "" [2]=> string(0) "" ["author_id"]=> string(1) "2" [3]=> string(1) "2" } [2]=> array(8) { ["id"]=> string(1) "3" [0]=> string(1) "3" ["title"]=> string(65) "Экономика оставляет желать лучшего" [1]=> string(65) "Экономика оставляет желать лучшего" ["lead"]=> string(0) "" [2]=> string(0) "" ["author_id"]=> string(1) "3" [3]=> string(1) "3" } }

Файлы и папки:

index.php

<?php
require __DIR__ . '/templates/news.php';
?>
config.php

<?php
return
[
'host'=>'127.0.0.1',
'db_name'=>'test',
'username'=>'root',
'password'=>''
];
?>

Папка templates:

article.php

<h2>
<?php echo $this->data['record']->getHeadline();?>
</h2>
<p>
<?php echo $this->data['record']->getFullText();?>
</p>


news.php

<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0,
maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Новости</title>
</head>
<body>
<h1>Главные новости</h1>
<hr>

<?php
foreach($this->data['news']->getNews() as $article)
{
$line = new View();
$line->assign('article', $article);
$line->display('newsAll.php');
}
?>
<hr>
</body>
</html>

newsAll.php
<article>
<h2>
<a href="article.php?id=<?php echo $this->data['article']->getId(); ?>">
<?php echo $this->data['article']->getHeadline(); ?>
</a>
</h2>
<p>
<?php echo $this->data['article']->getText(); ?>
</p>
</article>
<hr>

Папка: Classes

Article.php:

<?php

class Article
{
protected $id;
protected $headline;
protected $text;
protected $fullText;
protected $author;
public function __construct($article)
{
$data = explode('|', $article);
$this->id = ($data[0]);
$this->headline = trim($data[1]);
$this->text = mb_substr($data[2], 0, 150) . '...';
$this->fullText = trim($data[2]);
$this->author = trim($data[3]);
}

public function getId()
{
return $this->id; .
} //
public function getHeadline()
{
return $this->headline;
}
public function getText()
{
return $this->text;
}
public function getFullText()
{
return $this->fullText;
}
public function getAuthor()
{
return $this->author;
}

public function getLine()
{
return $this->headline . '|' . $this->text . '|' . $this->author;
}
}

DB.php:

<?php

class DB
{
protected $dbh;

public function __construct()
{
$this->connect();
}
private function connect()
{
$config = include __DIR__ . '/../config.php';
$dsn = 'mysql:host='. $config['host'] . ';dbname='.$config['db_name'].';';
$this->dbh = new PDO ($dsn, $config['username'], $config['password']);
return $this;

public function execute($sql)
{
$sth = $this->dbh->prepare($sql);
$res = $sth->execute();
return $res;
}

public function query($sql, $class)
{
$sth = $this->dbh->prepare($sql);
$res = $sth->execute();
if (false !== $res) {
return $sth->fetchAll(\PDO::FETCH_CLASS, $class);
}
return [];
}
}

$db = new DB;
$sql = 'SELECT * FROM news';
$a = $db->execute($sql);
?>

News.php:

<?php

require __DIR__.'/Article.php';

class News
{

protected $path;
protected $data;

public function __construct($path)
{
$id = 0;
$this->path = $path;
$data = file($path, FILE_IGNORE_NEW_LINES);
foreach ($data as $line) {
$this->data[++$id] = new Article($line);
}
}

public function getData($id)
{
return $this->data[$id];
}

public function getNews()
{
return $this->data;
}

public function append(Article $text)
{
$this->data[] = $text;
}

public function save()
{
$str = implode("\n", $this->data());
file_put_contents($this->path, $str);
}

public function getAll()
{
$data = [];
foreach ($this->getData() as $record) {
$data[] = $record->getLine();
}
return $data;
}
}
?>

View.php:

<?php

class View
protected $data;

public function __construct()
{
}

public function assign(string $name, $value)
{
$this->data = [];
$this->data[$name] = $value;
}

public function display(string $template)
{
echo $this->render($template);
}

public function render(string $template)
{
ob_start();
extract($this->data, EXTR_OVERWRITE);
include $template;
$content = ob_get_contents();
ob_end_clean();
return $content;
}
}
?>

Результат:
https://cloud.mail.ru/public/mhCB/Zqazy2EpS

Т.е.: неустранимая ошибка: Неперехваченная ошибка: использование $ this вне контекста объекта
Изображения
Тип файла: jpg 123.jpg (82.4 Кб, 2 просмотров)
Nick_1 вне форума Ответить с цитированием
Старый 15.10.2021, 16:06   #2
ADSoft
Старожил
 
Регистрация: 25.02.2007
Сообщений: 4,150
По умолчанию

не в ту тему. Есть раздел PHP
ADSoft вне форума Ответить с цитированием
Старый 15.10.2021, 16:08   #3
ForenLi
Форумчанин
 
Регистрация: 02.06.2021
Сообщений: 515
По умолчанию

Код:
class View
protected $data;
Скобка открывающая где?
ForenLi вне форума Ответить с цитированием
Старый 17.10.2021, 20:11   #4
Nick_1
Новичок
Джуниор
 
Регистрация: 14.10.2021
Сообщений: 2
По умолчанию

Цитата:
Сообщение от ForenLi Посмотреть сообщение
Код:
class View
protected $data;
Скобка открывающая где?
Спасибо, исправлю
Nick_1 вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Приложение запускается на эмуляторе с API 25, но не запускается на телефоне с API 19 Donna Lizard Java Мобильная разработка (Android) 6 05.11.2017 14:09
Мини приложение с сокетом Toples C# (си шарп) 10 05.05.2017 22:46
Не запускается приложение не из студии igorbukur C# (си шарп) 3 19.02.2016 10:44
Не запускается консольное приложение (C++) -Андрей- Помощь студентам 28 17.05.2014 13:15
не запускается приложение panuta БД в Delphi 2 16.09.2011 14:42