Guten Abend alle samt,
ich versuche seit längerem ein Blogsystem zusammen zubasteln der erste Teil von meinem Vorhaben hat geklappt, jedoch scheitert es bedauerlicherweise beim zweiten Teil...
Als News feed wollte ich einen zweiten Blog nehmen und da habe ich den Script des Funktionierenden Blogs genommen und auf meine wünsche angepasst.
Die daten werden erfolgreich aus der Sqlite Datenbank abgerufen jedoch kann ich keine Daten neu eingeben... ich arbeite da nun seit mehreren Tagen dran aber ein Lichtblick lässt sich einfach nicht finden.
Jetzt stellt sich mir die Frage wie ich euch das am dümmsten zeigen soll, es ist relativ komplex...
Vieleicht versteht ihr ja das:
edit-news.php
/lib/edit-news.php
lib/common.php
lib/view-news.php
init.sql
Ich weiß nicht ob das wirklich bei der Hilfe helfen kann würde aber jetzt ungern alle betroffenen Unterseiten hier auflisten.
Ich freue mich über jeden einselnen hilfreichen Kommentar, vielleicht habe ich ja nur etwas gans banales übersehen... Jedoch Suche ich Mittlerweile seit mehreren Tagen und hoffe das wir so etwas gemeinsam finden können.
Mit freundlichen Grüßen
Rico Richter
ich versuche seit längerem ein Blogsystem zusammen zubasteln der erste Teil von meinem Vorhaben hat geklappt, jedoch scheitert es bedauerlicherweise beim zweiten Teil...
Als News feed wollte ich einen zweiten Blog nehmen und da habe ich den Script des Funktionierenden Blogs genommen und auf meine wünsche angepasst.
Die daten werden erfolgreich aus der Sqlite Datenbank abgerufen jedoch kann ich keine Daten neu eingeben... ich arbeite da nun seit mehreren Tagen dran aber ein Lichtblick lässt sich einfach nicht finden.
Jetzt stellt sich mir die Frage wie ich euch das am dümmsten zeigen soll, es ist relativ komplex...
Vieleicht versteht ihr ja das:
edit-news.php
PHP-Code:
<?php
require_once 'lib/common.php';
require_once 'lib/edit-news.php';
require_once 'lib/view-news.php';
session_start();;
// Don't let non-auth users see this screen
if (!isLoggedIn())
{
redirectAndExit('index.php');
}
// Empty defaults
$title = $text = '';
// Init database and get handle
//Database connection
$pdo = getPDO();
$newsId = null;
if (isset($_GET['news_id']))
{
$news = getNewsRow($pdo, $_GET['news_id']);
if ($news)
{
$newsId = $_GET['news_id'];
$title = $news['title'];
$text = $news['text'];
}
}
// Handle the news operation here
$errors = array();
if ($_NEWS)
{
// Validate these first
$title = $_NEWS['news-title'];
if (!$title)
{
$errors[] = 'Die Neuigkeit benötigt einen Titel';
}
$text = $_NEWS['news-text'];
if (!$text)
{
$errors[] = 'Die Neuigkeit benötigt einen Text.';
}
if (!$errors)
{
$pdo = getPDO();
// Decide if we are editing or adding
if ($newsId)
{
editNews($pdo, $title, $text, $newsId);
}
else
{
$userId = getAuthUserId($pdo);
$newsId = addNews($pdo, $title, $text, $userId);
if ($newsId === false)
{
$errors[] = 'News operation failed';
}
}
}
if (!$errors)
{
redirectAndExit('edit-news.php?news_id=' . $newsId);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>A blog application | New News</title>
<?php require 'templates/head.php' ?>
</head>
<body>
<?php require 'templates/top-menu.php' ?>
<?php if (isset($_GET['news_id'])): ?>
<h1>Edit news</h1>
<?php else: ?>
<h1>New news</h1>
<?php endif ?>
<?php if ($errors): ?>
<div class="error box">
<ul>
<?php foreach ($errors as $error): ?>
<li><?php echo $error ?></li>
<?php endforeach ?>
</ul>
</div>
<?php endif ?>
<form method="post" class="post-form user-form">
<div>
<label for="news-title">Title:</label>
<input
id="news-title"
name="news-title"
type="text"
value="<?php echo $title ?>"
/>
</div>
<div>
<label for="news-text">Text:</label>
<textarea
id="news-text"
name="news-text"
rows="12"
cols="70"
><?php echo $text ?></textarea>
</div>
<div>
<input
type="submit"
value="Save post"
/>
<a href="/">Cancel</a>
</div>
<div>
<p>
<?php
$charlist = 'ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ';
echo str_word_count($text, 0, $charlist);?> Wörter</p>
</div>
</form>
</body>
</html>
PHP-Code:
<?php
function addNews(PDO $pdo, $title, $text, $userId)
{
// Prepare the insert query
$sql = "
INSERT INTO
news
(title, text, user_id, created_at)
VALUES
(:title, :text, :user_id, :created_at)
";
$stmt = $pdo->prepare($sql);
if ($stmt === false)
{
throw new Exception('Could not prepare news insert query');
}
// Now run the query, with these parameters
$result = $stmt->execute(
array(
'title' => $title,
'text' => $text,
'user_id' => $userId,
'created_at' => getSqlDateForNow(),
)
);
if ($result === false)
{
throw new Exception('Could not run news insert query');
}
return $pdo->lastInsertId();
}
function editNews(PDO $pdo, $title, $text, $newsId)
{
// Prepare the insert query
$sql = "
UPDATE
news
SET
title = :title,
text = :text
WHERE
id = :news_id
";
$stmt = $pdo->prepare($sql);
if ($stmt === false)
{
throw new Exception('Could not prepare news update query');
}
// Now run the query, with these parameters
$result = $stmt->execute(
array(
'title' => $title,
'text' => $text,
'news_id' => $newsId,
)
);
if ($result === false)
{
throw new Exception('Could not run news update query');
}
return true;
}
PHP-Code:
<?php
/**
* Gets the root path of the project
*
* @return string
*/
function getRootPath()
{
return realpath(__DIR__ . '/..');
}
/**
* Gets the full path for the database file
*
* @return string
*/
function getDatabasePath()
{
return getRootPath() . '/data/data.sqlite';
}
/**
* Gets the DSN for the SQLite connection
*
* @return string
*/
function getDsn()
{
return 'sqlite:' . getDatabasePath();
}
/**
* Gets the PDO object for database acccess
*
* @return \PDO
*/
function getPDO()
{
$pdo = new PDO(getDsn());
// Foreign key constraints need to be enabled manually in SQLite
$result = $pdo->query('PRAGMA foreign_keys = ON');
if ($result === false)
{
throw new Exception('Could not turn on foreign key constraints');
}
return $pdo;
}
/**
* Escapes HTML so it is safe to output
*
* @param string $html
* @return string
*/
function htmlEscape($html)
{
return htmlspecialchars($html, ENT_HTML5, 'UTF-8');
}
function convertSqlDate($sqlDate)
{
/* @var $date DateTime */
$date = DateTime::createFromFormat('Y-m-d H:i:s', $sqlDate);
return $date->format('d M Y, H:i');
}
function getSqlDateForNow()
{
return date('Y-m-d H:i:s');
}
/**
* Gets a list of posts in reverse order
*
* @param PDO $pdo
* @return array
*/
function getAllPosts(PDO $pdo)
{
$stmt = $pdo->query(
'SELECT
id, title, created_at, body, kategorie,
(SELECT COUNT(*) FROM comment WHERE comment.post_id = post.id) comment_count
FROM
post
ORDER BY
created_at DESC'
);
if ($stmt === false)
{
throw new Exception('There was a problem running this query');
}
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
/**
* Converts unsafe text to safe, paragraphed, HTML
*
* @param string $text
* @return string
*/
function convertNewlinesToParagraphs($text)
{
$escaped = htmlEscape($text);
return '<p>' . str_replace("\n", "</p><p>", $escaped) . '</p>';
}
function redirectAndExit($script)
{
// Get the domain-relative URL (e.g. /blog/whatever.php or /whatever.php) and work
// out the folder (e.g. /blog/ or /).
$relativeUrl = $_SERVER['PHP_SELF'];
$urlFolder = substr($relativeUrl, 0, strrpos($relativeUrl, '/') + 1);
// Redirect to the full URL (http://myhost/blog/script.php)
$host = $_SERVER['HTTP_HOST'];
$fullUrl = 'http://' . $host . $urlFolder . $script;
header('Location: ' . $fullUrl);
exit();
}
/**
* Returns all the comments for the specified post
*
* @param PDO $pdo
* @param integer $postId
* return array
*/
function getCommentsForPost(PDO $pdo, $postId)
{
$sql = "
SELECT
id, name, text, created_at, website
FROM
comment
WHERE
post_id = :post_id
";
$stmt = $pdo->prepare($sql);
$stmt->execute(
array('post_id' => $postId, )
);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
function tryLogin(PDO $pdo, $username, $password)
{
$sql = "
SELECT
password
FROM
user
WHERE
username = :username
AND is_enabled = 1
";
$stmt = $pdo->prepare($sql);
$stmt->execute(
array('username' => $username, )
);
// Get the hash from this row, and use the third-party hashing library to check it
$hash = $stmt->fetchColumn();
$success = password_verify($password, $hash);
return $success;
}
/**
* Logs the user in
*
* For safety, we ask PHP to regenerate the cookie, so if a user logs onto a site that a cracker
* has prepared for him/her (e.g. on a public computer) the cracker's copy of the cookie ID will be
* useless.
*
* @param string $username
*/
function login($username)
{
session_regenerate_id();
$_SESSION['logged_in_username'] = $username;
}
/**
* Logs the user out
*/
function logout()
{
unset($_SESSION['logged_in_username']);
}
function getAuthUser()
{
return isLoggedIn() ? $_SESSION['logged_in_username'] : null;
}
function isLoggedIn()
{
return isset($_SESSION['logged_in_username']);
}
/**
* Looks up the user_id for the current auth user
*/
function getAuthUserId(PDO $pdo)
{
// Reply with null if there is no logged-in user
if (!isLoggedIn())
{
return null;
}
$sql = "
SELECT
id
FROM
user
WHERE
username = :username
AND is_enabled = 1
";
$stmt = $pdo->prepare($sql);
$stmt->execute(
array(
'username' => getAuthUser()
)
);
return $stmt->fetchColumn();
}
/*News Blog*/
function getAllNews(PDO $pdo)
{
$stmt = $pdo->query(
'SELECT
id, title, created_at, text
FROM
news
ORDER BY
created_at DESC'
);
if ($stmt === false)
{
throw new Exception('There was a problem running this query');
}
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
PHP-Code:
<?php
/**
* Gets the root path of the project
*
* @return string
*/
function getRootPath()
{
return realpath(__DIR__ . '/..');
}
/**
* Gets the full path for the database file
*
* @return string
*/
function getDatabasePath()
{
return getRootPath() . '/data/data.sqlite';
}
/**
* Gets the DSN for the SQLite connection
*
* @return string
*/
function getDsn()
{
return 'sqlite:' . getDatabasePath();
}
/**
* Gets the PDO object for database acccess
*
* @return \PDO
*/
function getPDO()
{
$pdo = new PDO(getDsn());
// Foreign key constraints need to be enabled manually in SQLite
$result = $pdo->query('PRAGMA foreign_keys = ON');
if ($result === false)
{
throw new Exception('Could not turn on foreign key constraints');
}
return $pdo;
}
/**
* Escapes HTML so it is safe to output
*
* @param string $html
* @return string
*/
function htmlEscape($html)
{
return htmlspecialchars($html, ENT_HTML5, 'UTF-8');
}
function convertSqlDate($sqlDate)
{
/* @var $date DateTime */
$date = DateTime::createFromFormat('Y-m-d H:i:s', $sqlDate);
return $date->format('d M Y, H:i');
}
function getSqlDateForNow()
{
return date('Y-m-d H:i:s');
}
/**
* Gets a list of posts in reverse order
*
* @param PDO $pdo
* @return array
*/
function getAllPosts(PDO $pdo)
{
$stmt = $pdo->query(
'SELECT
id, title, created_at, body, kategorie,
(SELECT COUNT(*) FROM comment WHERE comment.post_id = post.id) comment_count
FROM
post
ORDER BY
created_at DESC'
);
if ($stmt === false)
{
throw new Exception('There was a problem running this query');
}
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
/**
* Converts unsafe text to safe, paragraphed, HTML
*
* @param string $text
* @return string
*/
function convertNewlinesToParagraphs($text)
{
$escaped = htmlEscape($text);
return '<p>' . str_replace("\n", "</p><p>", $escaped) . '</p>';
}
function redirectAndExit($script)
{
// Get the domain-relative URL (e.g. /blog/whatever.php or /whatever.php) and work
// out the folder (e.g. /blog/ or /).
$relativeUrl = $_SERVER['PHP_SELF'];
$urlFolder = substr($relativeUrl, 0, strrpos($relativeUrl, '/') + 1);
// Redirect to the full URL (http://myhost/blog/script.php)
$host = $_SERVER['HTTP_HOST'];
$fullUrl = 'http://' . $host . $urlFolder . $script;
header('Location: ' . $fullUrl);
exit();
}
/**
* Returns all the comments for the specified post
*
* @param PDO $pdo
* @param integer $postId
* return array
*/
function getCommentsForPost(PDO $pdo, $postId)
{
$sql = "
SELECT
id, name, text, created_at, website
FROM
comment
WHERE
post_id = :post_id
";
$stmt = $pdo->prepare($sql);
$stmt->execute(
array('post_id' => $postId, )
);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
function tryLogin(PDO $pdo, $username, $password)
{
$sql = "
SELECT
password
FROM
user
WHERE
username = :username
AND is_enabled = 1
";
$stmt = $pdo->prepare($sql);
$stmt->execute(
array('username' => $username, )
);
// Get the hash from this row, and use the third-party hashing library to check it
$hash = $stmt->fetchColumn();
$success = password_verify($password, $hash);
return $success;
}
/**
* Logs the user in
*
* For safety, we ask PHP to regenerate the cookie, so if a user logs onto a site that a cracker
* has prepared for him/her (e.g. on a public computer) the cracker's copy of the cookie ID will be
* useless.
*
* @param string $username
*/
function login($username)
{
session_regenerate_id();
$_SESSION['logged_in_username'] = $username;
}
/**
* Logs the user out
*/
function logout()
{
unset($_SESSION['logged_in_username']);
}
function getAuthUser()
{
return isLoggedIn() ? $_SESSION['logged_in_username'] : null;
}
function isLoggedIn()
{
return isset($_SESSION['logged_in_username']);
}
/**
* Looks up the user_id for the current auth user
*/
function getAuthUserId(PDO $pdo)
{
// Reply with null if there is no logged-in user
if (!isLoggedIn())
{
return null;
}
$sql = "
SELECT
id
FROM
user
WHERE
username = :username
AND is_enabled = 1
";
$stmt = $pdo->prepare($sql);
$stmt->execute(
array(
'username' => getAuthUser()
)
);
return $stmt->fetchColumn();
}
/*News Blog*/
function getAllNews(PDO $pdo)
{
$stmt = $pdo->query(
'SELECT
id, title, created_at, text
FROM
news
ORDER BY
created_at DESC'
);
if ($stmt === false)
{
throw new Exception('There was a problem running this query');
}
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
Code:
/** * Database creation script */ /* Foreign key constraints need to be explicitly enabled in SQLite */ PRAGMA foreign_keys = ON; DROP TABLE IF EXISTS user; CREATE TABLE user ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username VARCHAR NOT NULL, password VARCHAR NOT NULL, created_at VARCHAR NOT NULL, is_enabled BOOLEAN NOT NULL DEFAULT true ); /* This will become user = 1. I'm creating this just to satisfy constraints here. The password will be properly hashed in the installer */ INSERT INTO user ( username, password, created_at, is_enabled ) VALUES ( "admin", "unhashed-password", datetime('now', '-3 months'), 0 ) ; DROP TABLE IF EXISTS post; CREATE TABLE post ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, title VARCHAR NOT NULL, body VARCHAR NOT NULL, user_id INTEGER NOT NULL, created_at VARCHAR NOT NULL, kategorie VARCHAR NOT NULL, updated_at VARCHAR, FOREIGN KEY (user_id) REFERENCES user(id) ); INSERT INTO post ( title, body, user_id, created_at, kategorie ) VALUES( "Here's our first post", "This is the body of the first post. It is split into paragraphs.", 1, datetime('now', '-2 months', '-45 minutes', '+10 seconds'), "Imkerei" ) ; INSERT INTO post ( title, body, user_id, created_at, kategorie ) VALUES( "Now for a second article", "This is the body of the second post. This is another paragraph.", 1, datetime('now', '-40 days', '+815 minutes', '+37 seconds'), "News" ) ; INSERT INTO post ( title, body, user_id, created_at, kategorie ) VALUES( "Here's a third post", "This is the body of the third post. This is split into paragraphs.", 1, datetime('now', '-13 days', '+198 minutes', '+51 seconds'), "Rezepte" ) ; DROP TABLE IF EXISTS comment; CREATE TABLE comment ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, post_id INTEGER NOT NULL, created_at VARCHAR NOT NULL, name VARCHAR NOT NULL, website VARCHAR, text VARCHAR NOT NULL, FOREIGN KEY (post_id) REFERENCES post(id) ); INSERT INTO comment ( post_id, created_at, name, website, text ) VALUES( 1, datetime('now', '-10 days', '+231 minutes', '+7 seconds'), 'Jimmy', 'http://example.com/', "This is Jimmy's contribution" ) ; INSERT INTO comment ( post_id, created_at, name, website, text ) VALUES( 1, datetime('now', '-8 days', '+549 minutes', '+32 seconds'), 'Jonny', 'http://anotherexample.com/', "This is a comment from Jonny" ) ; /*News Blog*/ DROP TABLE IF EXISTS news; CREATE TABLE news ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, title VARCHAR NOT NULL, text VARCHAR NOT NULL, user_id INTEGER NOT NULL, created_at VARCHAR NOT NULL, updated_at VARCHAR, FOREIGN KEY (user_id) REFERENCES user(id) ); INSERT INTO news ( title, text, user_id, created_at ) VALUES( "News & Aktuelles", "<p style='color: #00aa00'><i>10.06.2018</i> Verfügbar!</p>Es ist wieder soweit! <br>Der feincremige Frühjahrshonig aus der Bärensteinimkerei ist fertig gerührt und abgefüllt.<br> Alle eingegangenen Vorbestellungen werden in kürze bearbeitet.<p> </p>", 1, datetime('now') ) ;
Ich freue mich über jeden einselnen hilfreichen Kommentar, vielleicht habe ich ja nur etwas gans banales übersehen... Jedoch Suche ich Mittlerweile seit mehreren Tagen und hoffe das wir so etwas gemeinsam finden können.
Mit freundlichen Grüßen
Rico Richter
Kommentar