Lesson 6 - NOO-CMS - Article editor in PHP

PHP Databases for beginners NOO-CMS - Article editor in PHP

In the previous lesson, NOO-CMS - User registration in PHP, we finished up the administration page for our simple content management system in PHP. In today's lesson, we will be adding a user log-in form as well as an article editor.

Signing-in

Let's create a sign-in.php script. The HTML part will be as follows:

<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="style.css" type="text/css" />
        <title>Sign-in to administration</title>
</head>

<body>
        <article>
                <div id="centerer">
                        <header>
                                <h1>Sign in to administration</h1>
                        </header>
                        <section>
                                <?php
                                if (isset($notice))
                                        echo('<p>' . $notice . '</p>');
                                ?>

                                <form method="post">
                                        Name<br />
                                        <input type="text" name="name" /><br />
                                        password<br />
                                        <input type="password" name="password" /><br />
                                        <input type="submit" value="Sign-in" />
                                </form>

                                <p>If you don't have an account yet, <a href="sign-up.php">sign-up</a>.</p>
                        </section>
                        <div class="clear"></div>
                </div>
        </article>
</body>
</html>

HTe code above includes a PHP directive used for error notice printing (if needed) and a form with name and password input fields. The code is almost the same as the registration form and should be easy to understand.

Now insert the following block of PHP above the HTML:

<?php
session_start();
require('Db.php');
Db::connect('127.0.0.1', 'noocms_db', 'root', '');

if (isset($_SESSION['user_id']))
{
        header('Location: administration.php');
        exit();
}

if ($_POST)
{
        $user = Db::queryOne('
                SELECT user_id, admin
                FROM user
                WHERE name=? AND password=SHA1(?)
        ', $_POST['name'], $_POST['password'] . "t&#ssdf54gh");
        if (!$user)
                $notice = 'Invalid name or password.';
        else
        {
                $_SESSION['user_id'] = $user['user_id'];
                $_SESSION['user_name'] = $_POST['name'];
                $_SESSION['user_admin'] = $user['admin'];
                header('Location: administration.php');
                exit();
        }
}
?>

The first couple of lines make the session accessible and establish a connection with the database. If the user is already signed in, we don't display the sign-in page. Instead, we redirect him/her to the administration page and terminate the script.

If the form is sent, we "salt" the password with the same salt we used for signing-in. Using the SHA1() SQL function we will, once again, compute a hash. The script will then try to find users with the given name and hash, we store an error notice in case of failure. If the query is successful, we sign the user in by storing the data provided by the session. Last of all, we redirect him/her to the administration page.

Go ahead and test it out by signing back in. If you are still signed in from last time, sign-out and sign back in again.

Users sign-in in PHP

Assigning admin role

Each and every user has an admin column, which contains either a value of 0 or 1 based on whether a user is an administrator. This value can only be set by an administrator through phpMyAdmin. Let's move to phpMyAdmin and switch the value from 0 to 1 (all you have to do is click on it and change the value).

Administrator privileges in phpMyAdmin

Now sign-out and sign back in again.

Article editor

Great, now let's move on to the article editor! Create an editor.php file and insert the following block of HTML into it:

<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="style.css" type="text/css" />
        <title>Article editor</title>
</head>

<body>
        <article>
                <div id="centerer">
                        <header>
                                <h1>Article editor</h1>
                        </header>
                        <section>
                                <?php
                                if (isset($notice))
                                        echo('<p>' . $notice . '</p>');
                                ?>

                                <form method="post">
                                        <input type="hidden" name="article_id" value="<?= htmlspecialchars($article['article_id']) ?>" /><br />
                                        title<br />
                                        <input type="text" name="title" value="<?= htmlspecialchars($article['title']) ?>" /><br />
                                        URL<br />
                                        <input type="text" name="url" value="<?= htmlspecialchars($article['url']) ?>" /><br />
                                        Description<br />
                                        <input type="text" name="description" value="<?= htmlspecialchars($article['description']) ?>" /><br />
                                        <textarea name="content"><?= htmlspecialchars($article['content']) ?></textarea>
                                        <input type="submit" value="Submit" />
                                </form>
                        </section>
                        <div class="clear"></div>
                </div>
        </article>
        <script type="text/javascript" src="//cdn.tinymce.com/4/tinymce.min.js"></script>
        <script type="text/javascript">
                tinymce.init({
                        selector: "textarea[name=content]",
                        plugins: [
                                "advlist autolink lists link image charmap print preview anchor",
                                "searchreplace visualblocks code fullscreen",
                                "insertdatetime media table contextmenu paste"
                        ],
                        toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
                        entities: "160,nbsp",
                        entity_encoding: "named",
                        entity_encoding: "raw"
                });
        </script>
</body>
</html>

All the code is, is a simple HTML form and an error notice printing condition. Data is filled into the form fields through the $article array. One last thing, the form has a hidden field with the ID of a given article. Based on whether the user is publishing a new article (in which case the hidden field will be empty) or editing an existing article (in which case it would contain the article ID).

At the bottom of the file, things get quite interesting. We load the TinyMCE WYSIWIYG editor, an editor that has the same interface as MS Word. It generates an HTML code based on what we click.

The first script references a content delivery network (CDN), from which we download the TinyMCE. The second contains the configuration needed to use the editor. The way it is set up now means that we chose to create an editor from a textarea named content. The following code sets the plugins and turns-off the encoding that converts accent characters to entities, which causes very nasty problems in countries that use them.

Add the following block of PHP above the HTML code:

<?php
session_start();
if (empty($_SESSION['user_admin']))
        die('Access denied');

require('Db.php');
Db::connect('127.0.0.1', 'noocms_db', 'root', '');

$article = array(
        'article_id' => '',
        'title' => '',
        'content' => '',
        'url' => '',
        'description' => '',
);
if ($_POST)
{
        if (!$_POST['article_id'])
        {
                Db::query('
                        INSERT INTO article (title, content, url, description)
                        VALUES (?, ?, ?, ?)
                ', $_POST['title'], $_POST['content'], $_POST['url'], $_POST['description'], $_POST['keywords']);
        }
        else
        {
                Db::query('
                        UPDATE article
                        SET title=?, content=?, url=?, description=?
                        WHERE article_id=?
                ', $_POST['title'], $_POST['content'], $_POST['url'], $_POST['description'], $_POST['keywords'], $_POST['article_id']);
        }
        header('Location: index.php?article=' . $_POST['url']);
        exit();
}
else if (isset($_GET['url']))
{
        $loadedArticle = Db::queryOne('
                SELECT *
                FROM article
                WHERE url=?
        ', $_GET['url']);
        if ($loadedArticle)
                $article = $loadedArticle;
        else
                $message = 'Article was not found';
}

?>

If a user is not an administrator, we terminate the entire script and print an error message. To check whether an administrator has signed-in, the isset() function will not suffice. In this case, we'll have to use the empty() function. Remember, that there may be a 'user_admin' key in the session, but it must contain a value of 0 to meet the requirements.

After that, we connect to the database and prepare an array with empty values and store it in a variable named $article. We do this to keep the form empty in case a new article is created and also to avoid having PHP notify us of non-existing variables.

If the form was submitted, we check the hidden field. If it's empty, we insert a new article into the database. If there already is a value, we update the article with the given ID. We have yet to use the SQL UPDATE command yet but don't worry, it's very simple. All we'll have to do is set the needed columns using SET. The main thing here is not to forget the WHERE clause. We'll have to specify which rows are to be updated. Every single article would be updated with the new values otherwise!

We redirect to the article after adding or editing it.

If the form wasn't submitted, we check whether there is an article URL in GET. Meaning that we're trying to edit an article, so we try to load data into the $article variable from the actual article through the URL. The data would then be filled into form fields. We print an error message in case of failure.

Now run the editor and insert a new article with the URL set to "home". This article will be our homepage:

TinyMCE article editor in PHP

Make sure you save the article into the database! In the next lesson, NOO-CMS - Displaying articles in PHP, we will add the finishing touches to our NOO-CMS.


 

Download

Downloaded 64x (391.82 kB)
Application includes source codes in language PHP

 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
1 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Activities (6)

 

 

Comments
Display older comments (4)

Avatar
David Capka
ICT.social team
Avatar
David Capka:2/10/2017 6:43

I'll check it again today and let you know.

Reply  +1 2/10/2017 6:43
You can walk through a storm and feel the wind but you know you are not the wind.
Avatar
Tabish Ali
Member
Avatar
Tabish Ali:2/10/2017 6:48

ok thanks .

Reply 2/10/2017 6:48
there is no limit to learn.
Avatar
David Capka
ICT.social team
Avatar
Replies to Tabish Ali
David Capka:2/10/2017 9:18

Do you specify the url parameter in the URL address when trying to save an existing article? The system is not finished here, you can't expect that the editor will work completely in the middle of the course. You'll edit articles in the next lessons.

Reply 2/10/2017 9:18
You can walk through a storm and feel the wind but you know you are not the wind.
Avatar
Tabish Ali
Member
Avatar
Tabish Ali:2/10/2017 9:51

Whenever i try to save the existing article i choose title , description and url same as before. But our update query check (if else check) is on article_id and i am not getting article_id =0 , article_id is empty string so else part (update query) is not executing. This lesson name is "Article editor in PHP" and it has update part so it must update existing articles.

Reply 2/10/2017 9:51
there is no limit to learn.
Avatar
Tabish Ali
Member
Avatar
Tabish Ali:2/10/2017 9:58

oky i move to next lesson and i'll let you know if i have any problem there.

Reply 2/10/2017 9:58
there is no limit to learn.
Avatar
Tabish Ali
Member
Avatar
Tabish Ali:2/10/2017 10:37

i understand , you are right in lesson 7 it is more clear . i got it . thanks :-)

Reply  +1 2/10/2017 10:37
there is no limit to learn.
Avatar
lawrence njoroge:3/10/2017 13:35

help me out i cant fix the error
"
Fatal error: Call to a member function prepare() on null in C:\xampp\htdoc­s\PhpProject1\dbb­.php on line 66"

dbb.php

<?php

/*
 *       _____ _____ _____                _       _
 *      |_   _/  __ \_   _|              (_)     | |
 *        | | | /  \/ | |  ___  ___   ___ _  __ _| |
 *        | | ||      | | / __|/ _ \ / __| |/ _` | |
 *       _| |_| \__/\ | |_\__ \ (_) | (__| | (_| | |
 *      |_____\_____/ |_(_)___/\___/ \___|_|\__,_|_|
 *                   ___
 *                  |  _|___ ___ ___
 *                  |  _|  _| -_| -_|  LICENCE
 *                  |_| |_| |___|___|
 *
 * IT NEWS  <>  PROGRAMMING  <>  HW & SW  <>  COMMUNITY
 *
 * This source code is part of online courses at IT social
 * network WWW.ICT.SOCIAL
 *
 * Feel free to use it for whatever you want, modify it and share it but
 * don't forget to keep this link in code.
 *
 * For more information visit http://www.ict.social/licences
 *
 * A simple database wrapper over the PDO class
 */
class Db
{
        /**
         * @var PDO A database connection
         */
        private static $connection;

        /**
         * @var array The default driver settings
         */
        private static $options = array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
                PDO::ATTR_EMULATE_PREPARES => false,
        );

        /**
         * Connects to the database using given credentials
         * @param string $host Host name
         * @param string $database Database name
         * @param string $user Username
         * @param string $password Password
         */
        public static function connect($host, $database, $user)
        {
                if (!isset(self::$connection)) {
                        $dsn = "mysql:host=$host;dbname=$database";
                        self::$connection = new PDO($dsn, $user,  self::$options);
                }
        }

        /**
         * Executes a query and returns the PDO statement
         * @param array $params An array where the first item represents the query and the other items are its parameters.
         * @return \PDOStatement PDO statement
         */
        private static function executeStatement($params)
        {
                $query = array_shift($params);
                $statement = self::$connection->prepare($query);
                $statement->execute($params);
                return $statement;
        }

        /**
         * Executes a query and returns the number of affected rows.
         * Any other parameters will be passed into the query.
         * @param string $query The query
         * @return int The number of affected rows
         */
        public static function query($query) {
                $statement = self::executeStatement(func_get_args());
                return $statement->rowCount();
        }

        /**
         * Executes a query and returns the value of the first column of the first row.
         * Any other parameters will be passed into the query.
         * @param string $query The query
         * @return mixed The value of the first column of the first row
         */
        public static function querySingle($query) {
                $statement = self::executeStatement(func_get_args());
                $data = $statement->fetch();
                return $data[0];
        }

        /**
         * Executes a query and returns the first row of the result.
         * Any other parameters will be passed into the query.
         * @param string $query The query
         * @return mixed An associative array representing the row or false in no data returned
         */
        public static function queryOne($query) {
                $statement = self::executeStatement(func_get_args());
                return $statement->fetch(PDO::FETCH_ASSOC);
        }

        /**
         * Executes a query and returns all resulting rows as an array of associative arrays.
         * Any other parameters will be passed into the query.
         * @param string $query The query
         * @return mixed An array of associative arrays or false in no data returned
         */
        public static function queryAll($query) {
                $statement = self::executeStatement(func_get_args());
                return $statement->fetchAll(PDO::FETCH_ASSOC);
        }

        /**
         * Inserts data from an associative array into the database as a new row
         * @param string $table The table name
         * @param array $data The associative array where keys preresent columns and values their values
         * @return int The number of affected rows
         */
        public static function insert($table, $data) {
                $keys = array_keys($data);
                self::checkIdentifiers(array($table) + $keys);
                $query = "
                        INSERT INTO `$table` (`" . implode('`, `', $keys) . "`)
                        VALUES (" . str_repeat('?,', count($data) - 1) . "?)
                ";
                $params = array_merge(array($query), array_values($data));
                $statement = self::executeStatement($params);
                return $statement->rowCount();
        }

        /**
         * Executes an update and passes data from an associative array to it
         * @param string $table The table name
         * @param array $data The associative array where keys preresent columns and values their values
         * @param string $condition A string containing the condition (WHERE)
         * @return mixed The number of affected rows
         */
        public static function update($table, $data, $condition) {
                $keys = array_keys($data);
                self::checkIdentifiers(array($table) + $keys);
                $query = "
                        UPDATE `$table` SET `".
                        implode('` = ?, `', array_keys($data)) . "` = ?
                        $condition
                ";
                $params = array_merge(array($query), array_values($data), array_slice(func_get_args(), 3));
                $statement = self::executeStatement($params);
                return $statement->rowCount();
        }

        /**
         * Returns the ID of the last inserted row
         * @return mixed The ID of the last inserted row
         */
        public static function getLastId()
        {
                return self::$connection->lastInsertId();
        }

        /**
         * Quotes a given string to protect it against the SQL injection
         * @param string $string The string
         * @return mixed The quoted string
         */
        public static function quote($string)
        {
                return self::$connection->quote($string);
        }

        /**
         * Checks whether given identifiers don't contain dangerous characters
         * @param array $identifiers The identifiers
         * @throws \Exception
         */
        private static function checkIdentifiers($identifiers)
        {
                foreach ($identifiers as $identifier)
                {
                        if (!preg_match('/^[a-zA-Z0-9\_\-]+$/u', $identifier))
                                throw new Exception('Dangerous identifier in SQL query');
                }
        }
}

editor.php code

<?php
session_start();

require('Dbb.php');

$article = array(
        'article_id' => '',
        'title' => '',
        'content' => '',
        'description' => '',
);
if ($_POST)
{
        if (!$_POST['article_id'])
        {
                Db::query('
                        INSERT INTO article (title, content, description)
                        VALUES (?, ?, ?, ?)
                ', $_POST['title'], $_POST['content'], $_POST['description']);
        }
        else
        {
                Db::query('
                        UPDATE article
                        SET title=?, content=?,  description=?
                        WHERE article_id=?
                ', $_POST['title'], $_POST['content'], $_POST['description'], $_POST['article_id']);
        }
        header('Location: index.php');
        exit();
}
else
?>
<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="style.css" type="text/css" />
        <title>Article editor</title>
</head>

<body>
    <header>
                        <div id="logo"><h1></h1></div>
                <nav>
                        <ul>
                            <li><a href="home.php">Home</a></li>
                                <li><a href="about.php">About us</a></li>
                                <li><a href="members.php">members</a></li>
                                <li><a href="contact.php">Contact</a></li>


                        </ul>
                </nav>
</header>
        <article>
                <div id="centerer">
                        <header>
                                <h1>Article editor</h1>
                        </header>
                        <section>

                                <form method="post">
                                        <input type="hidden" name="article_id" value="<?= htmlspecialchars($article['article_id']) ?>" /><br />
                                        title<br />
                                        <input type="text" name="title" value="<?= htmlspecialchars($article['title']) ?>" /><br />
                                        Description<br />
                                        <input type="text" name="description" value="<?= htmlspecialchars($article['description']) ?>" /><br />
                                        <textarea name="content"><?= htmlspecialchars($article['content']) ?></textarea>
                                        <input type="submit" value="Submit" />
                                </form>
                        </section>
                        <div class="clear"></div>
                </div>
        </article>
        <script type="text/javascript" src="//cdn.tinymce.com/4/tinymce.min.js"></script>
        <script type="text/javascript">
                tinymce.init({
                        selector: "textarea[name=content]",
                        plugins: [
                                "advlist autolink lists link image charmap print preview anchor",
                                "searchreplace visualblocks code fullscreen",
                                "insertdatetime media table contextmenu paste"
                        ],
                        toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
                        entities: "160,nbsp",
                        entity_encoding: "named",
                        entity_encoding: "raw"
                });
        </script>
     <footer>
                        Made by &copy;<a href="http://www.facebook.com/lawnj">lawrence</a>
                </footer>
</body>
</html>
Reply 3/10/2017 13:35
where there is will there is a way
Avatar
IT Man
Member
Avatar
Replies to lawrence njoroge
IT Man:3/10/2017 16:31

You have 4 question marks in INSERT and only 3 variables. So remove 1 question mark. :)
Btw. you can use insert() instead query(). Check the function. :)

Reply 3/10/2017 16:31
Don't be silly and smile!
Avatar
lawrence njoroge:3/11/2017 12:13

more help please
"Warning: array_keys() expects parameter 1 to be array, string given in C:\xampp\htdoc­s\PhpProject1\dbb­.php on line 123

Fatal error: Unsupported operand types in C:\xampp\htdoc­s\PhpProject1\dbb­.php on line 124"
dbb.php

<?php

/*
 *       _____ _____ _____                _       _
 *      |_   _/  __ \_   _|              (_)     | |
 *        | | | /  \/ | |  ___  ___   ___ _  __ _| |
 *        | | ||      | | / __|/ _ \ / __| |/ _` | |
 *       _| |_| \__/\ | |_\__ \ (_) | (__| | (_| | |
 *      |_____\_____/ |_(_)___/\___/ \___|_|\__,_|_|
 *                   ___
 *                  |  _|___ ___ ___
 *                  |  _|  _| -_| -_|  LICENCE
 *                  |_| |_| |___|___|
 *
 * IT NEWS  <>  PROGRAMMING  <>  HW & SW  <>  COMMUNITY
 *
 * This source code is part of online courses at IT social
 * network WWW.ICT.SOCIAL
 *
 * Feel free to use it for whatever you want, modify it and share it but
 * don't forget to keep this link in code.
 *
 * For more information visit http://www.ict.social/licences
 *
 * A simple database wrapper over the PDO class
 */
class Db
{
        /**
         * @var PDO A database connection
         */
        private static $connection;

        /**
         * @var array The default driver settings
         */
        private static $options = array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
                PDO::ATTR_EMULATE_PREPARES => false,
        );

        /**
         * Connects to the database using given credentials
         * @param string $host Host name
         * @param string $database Database name
         * @param string $user Username
         * @param string $password Password
         */
        public static function connect($host, $database, $user)
        {
                if (!isset(self::$connection)) {
                        $dsn = "mysql:host=$host;dbname=$database";
                        self::$connection = new PDO($dsn, $user,  self::$options);
                }
        }

        /**
         * Executes a query and returns the PDO statement
         * @param array $params An array where the first item represents the query and the other items are its parameters.
         * @return \PDOStatement PDO statement
         */
        private static function executeStatement($params)
        {
                $insert = array_shift($params);
                $statement = self::$connection->prepare($insert);
                $statement->execute($params);
                return $statement;
        }

        /**
         * Executes a query and returns the number of affected rows.
         * Any other parameters will be passed into the query.
         * @param string $insert The query
         * @return int The number of affected rows
         */
        public static function query($insert) {
                $statement = self::executeStatement(func_get_args());
                return $statement->rowCount();
        }

        /**
         * Executes a query and returns the value of the first column of the first row.
         * Any other parameters will be passed into the query.
         * @param string $insert The query
         * @return mixed The value of the first column of the first row
         */
        public static function querySingle($insert) {
                $statement = self::executeStatement(func_get_args());
                $data = $statement->fetch();
                return $data[0];
        }

        /**
         * Executes a query and returns the first row of the result.
         * Any other parameters will be passed into the query.
         * @param string $insert The query
         * @return mixed An associative array representing the row or false in no data returned
         */
        public static function queryOne($insert) {
                $statement = self::executeStatement(func_get_args());
                return $statement->fetch(PDO::FETCH_ASSOC);
        }

        /**
         * Executes a query and returns all resulting rows as an array of associative arrays.
         * Any other parameters will be passed into the query.
         * @param string $insert The query
         * @return mixed An array of associative arrays or false in no data returned
         */
        public static function queryAll($insert) {
                $statement = self::executeStatement(func_get_args());
                return $statement->fetchAll(PDO::FETCH_ASSOC);
        }

        /**
         * Inserts data from an associative array into the database as a new row
         * @param string $table The table name
         * @param array $data The associative array where keys preresent columns and values their values
         * @return int The number of affected rows
         */
        public static function insert($table, $data) {
                $keys = array_keys($table);
                self::checkIdentifiers(array($table) + $keys);
                $insert = "
                        INSERT INTO `$table` (`" . implode('`, `', $keys) . "`)
                        VALUES (" . str_repeat('?,', count($data) - 1) . "?)
                ";
                $params = array_merge(array($insert), array_values($data));
                $statement = self::executeStatement($params);
                return $statement->rowCount();
        }

        /**
         * Executes an update and passes data from an associative array to it
         * @param string $table The table name
         * @param array $data The associative array where keys preresent columns and values their values
         * @param string $condition A string containing the condition (WHERE)
         * @return mixed The number of affected rows
         */
        public static function update($table, $data, $condition) {
                $keys = array_keys($data);
                self::checkIdentifiers(array($table) + $keys);
                $insert = "
                        UPDATE `$table` SET `".
                        implode('` = ?, `', array_keys($data)) . "` = ?
                        $condition
                ";
                $params = array_merge(array($insert), array_values($data), array_slice(func_get_args(), 3));
                $statement = self::executeStatement($params);
                return $statement->rowCount();
        }

        /**
         * Returns the ID of the last inserted row
         * @return mixed The ID of the last inserted row
         */
        public static function getLastId()
        {
                return self::$connection->lastInsertId();
        }

        /**
         * Quotes a given string to protect it against the SQL injection
         * @param string $string The string
         * @return mixed The quoted string
         */
        public static function quote($string)
        {
                return self::$connection->quote($string);
        }

        /**
         * Checks whether given identifiers don't contain dangerous characters
         * @param array $identifiers The identifiers
         * @throws \Exception
         */
        private static function checkIdentifiers($identifiers)
        {
                foreach ($identifiers as $identifier)
                {
                    if (!preg_match('/^[a-zA-Z0-9\_\-]+$/u', $identifier)) {
                throw new Exception('Dangerous identifier in SQL query');
            }
        }
        }
}

editor.php
<?php
session_start();

require('Dbb.php');

$article = array(
        'article_id' => '',
        'title' => '',
        'content' => '',
        'description' => '',
);
if ($_POST)
{
        if (!$_POST['article_id'])
        {
                Db::insert('
                        INSERT INTO article (title, content, description)
                        VALUES (?, ?, ?)
                ', $_POST['title'], $_POST['content'], $_POST['description']);
        }
        else
        {
                Db::insert('
                        UPDATE article
                        SET title=?, content=?,  description=?
                        WHERE article_id=?
                ', $_POST['title'], $_POST['content'], $_POST['description'], $_POST['article_id']);
        }
        header('Location: index.php');
        exit();
}
else
?>
<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="style.css" type="text/css" />
        <title>Article editor</title>
</head>

<body>
    <header>
                        <div id="logo"><h1></h1></div>
                <nav>
                        <ul>
                            <li><a href="home.php">Home</a></li>
                                <li><a href="about.php">About us</a></li>
                                <li><a href="members.php">members</a></li>
                                <li><a href="contact.php">Contact</a></li>


                        </ul>
                </nav>
</header>
        <article>
                <div id="centerer">
                        <header>
                                <h1>Article editor</h1>
                        </header>
                        <section>

                                <form method="post">
                                        <input type="hidden" name="article_id" value="<?= htmlspecialchars($article['article_id']) ?>" /><br />
                                        title<br />
                                        <input type="text" name="title" value="<?= htmlspecialchars($article['title']) ?>" /><br />
                                        Description<br />
                                        <input type="text" name="description" value="<?= htmlspecialchars($article['description']) ?>" /><br />
                                        <textarea name="content"><?= htmlspecialchars($article['content']) ?></textarea>
                                        <input type="submit" value="Submit" />
                                </form>
                        </section>
                        <div class="clear"></div>
                </div>
        </article>
        <script type="text/javascript" src="//cdn.tinymce.com/4/tinymce.min.js"></script>
        <script type="text/javascript">
                tinymce.init({
                        selector: "textarea[name=content]",
                        plugins: [
                                "advlist autolink lists link image charmap print preview anchor",
                                "searchreplace visualblocks code fullscreen",
                                "insertdatetime media table contextmenu paste"
                        ],
                        toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
                        entities: "160,nbsp",
                        entity_encoding: "named",
                        entity_encoding: "raw"
                });
        </script>
     <footer>
                        Made by &copy;<a href="http://www.facebook.com/lawnj">lawrence</a>
                </footer>
</body>
</html>

\---

Reply 3/11/2017 12:13
where there is will there is a way
Avatar
IT Man
Member
Avatar
Replies to lawrence njoroge
IT Man:3/11/2017 16:10

insert has only 2 parameters - first is table (String) and then data (array). So you have to change it in this:

Db::insert('article', array(
    'title' => $_POST['title'],
    'content' => $_POST['content'],
    'description' => $_POST['description']
));

For update use normally function query. So for edit article you will use this:

Db::query('
        UPDATE article
        SET title=?, content=?, url=?, description=?
        WHERE article_id=?
', $_POST['title'], $_POST['content'], $_POST['url'], $_POST['description'], $_POST['article_id']);

I hope I helped you and next time you can use forum. :)

Reply 3/11/2017 16:10
Don't be silly and smile!
To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

10 messages from 14 displayed. Show all