Webmaster общности: Predpriemach.com | SearchEngines.bg

    Обикновенна система за новини

    Автор: SandPrince

    Ето едно уроче с което ще си направите обикновена и проста , но функционална система за новини. на изглед не е кой знае какво но вие можете да си я оформите както искате и да си добавите каквито искате екстри!!! идеята е да схванете принципа!
    Урока е преведен специално за Web-Tourist

    какво ще ни трябва:
    Таблица в БД – News_sql.sql
    config.php , add_news.php, index.php, read_more.php, edit_news.php, delete_news.php

    Започваме с кода за таблицата в БД

    CREATE TABLE `news` (
    `newsid` int(11) NOT NULL auto_increment,
    `dtime` datetime default NULL,
    `title` varchar(255) default NULL,
    `text1` text,
    `text2` text,
    PRIMARY KEY (`newsid`)
    ) TYPE=MyISAM AUTO_INCREMENT=1 ;

    Продължаваме със създаването на документа config.php който служи за осъществяване на връзка с БД

    <?php
    // Set Mysql Variables
    //Change the following
    $dbhost="localhost"; /попълвате си хоста
    $dbusername="user"; /попълвате си usera с който се логвате
    $dbpassword="pass"; /попълвате паролата
    $dbname="news_sysem"; / попълвате си името на БД
    
    // Don't touch here anything.
    // Connect to Mysql
    $connect = mysql_connect($dbhost, $dbusername, $dbpassword);
    //Select the correct database.
    mysql_select_db($dbname,$connect) or die ("Could not select database");
    ?>

    Следва да създадем файла add_news.php чрез който добавяме новините

    <title>hotnews</title>
    <?php
    include("config.php");
    
    
    if($submit)
    {//begin of if($submit).
    // Set global variables to easier names
    $title = $_POST['title'];
    $text1 = $_POST['text1'];
    $text2 = $_POST['text2'];
    
    //check if (title) field is empty then print error message.
    if(!$title){ //this means If the title is really empty.
    echo "Error: News title is a required field. Please fill it.";
    exit(); //exit the script and don't do anything else.
    }// end of if
    
    //run the query which adds the data gathered from the form into the database
    $result = mysql_query("INSERT INTO news (title, dtime, text1, text2)
    VALUES ('$title',NOW(),'$text1','$text2')",$connect);
    //print success message.
    echo "<b>Thank you! News added Successfully!<br>You'll be redirected to Home Page after (4) Seconds";
    echo "<meta http-equiv=Refresh content=4;url=index.php>";
    }//end of if($submit).
    
    
    // If the form has not been submitted, display it!
    else
    {//begin of else
    
    ?>
    <br>
    <h3>::Add News</h3>
    
    <form method="post" action="<?php echo $PHP_SELF ?>">
    
    Title: <input name="title" size="40" maxlength="255">
    <br>
    Text1: <textarea name="text1" rows="7" cols="30"></textarea>
    <br>
    Text2: <textarea name="text2" rows="7" cols="30"></textarea>
    <br>
    <input type="submit" name="submit" value="Add News">
    </form>
    <?
    }//end of else
    
    
    ?>
    

    Сега е ред на файла index.php на който се визуализират новините

    <title>News----By: maaking.com</title>
    <?php
    // load the configuration file.
    include("config.php");
    //load all news from the database and then OREDER them by newsid
    //you will notice that newlly added news will appeare first.
    //also you can OREDER by (dtime) instaed of (news id)
    $result = mysql_query("SELECT * FROM news ORDER BY newsid DESC",$connect);
    //lets make a loop and get all news from the database
    while($myrow = mysql_fetch_array($result))
    {//begin of loop
    //now print the results:
    echo "<b>Title: ";
    echo $myrow['title'];
    echo "</b><br>On: <i>";
    echo $myrow['dtime'];
    echo "</i><hr align=left width=160>";
    echo $myrow['text1'];
    // Now print the options to (Read,Edit & Delete the news)
    echo "<br><a href=\"read_more.php?newsid=$myrow[newsid]\">Read More...</a>
    || <a href=\"edit_news.php?newsid=$myrow[newsid]\">Edit</a>
    || <a href=\"delete_news.php?newsid=$myrow[newsid]\">Delete</a><br><hr>";
    }//end of loop
    ?>
    <!-- here you have the right to go Home or Add News. It's HTML not PHP -->
    <br><br>
    <a href=index.php>Home</a> <a href=add_news.php>Add News</a>

    Сега следва ред и на файла read_more.php с който ще прочитате цялата статия

    <title>News Details...</title>
    <?php
    include("config.php");
    
    $result = mysql_query("SELECT * FROM news WHERE newsid='$newsid' ",$connect);
    while($myrow = mysql_fetch_assoc($result))
    {
    echo "<b>";
    echo $myrow['title'];
    echo "</b><br>On: <i>";
    echo $myrow['dtime'];
    echo "</i><hr>";
    echo $myrow['text1'];
    echo " ";
    echo $myrow['text2'];
    echo "<br><br><a href=\"javascript:self.history.back();\"><-- Go Back</a>";
    }
    ?>

    Разбира се ще добавим и функция за редактиране на новините и това става с файла edit_news.php

    <title>Edit News</title>
    
    <?php
    include("config.php");
    
    if($submit)
    {
    
    $title = $_POST['title'];
    $text1 = $_POST['text1'];
    $text2 = $_POST['text2'];
    
    
    
    $result = mysql_query("UPDATE news SET title='$title', text1='$text1', text2='$text2' WHERE newsid='$newsid' ",$connect);
    
    echo "<b>Thank you! News UPDATED Successfully!<br>You'll be redirected to Home Page after (4) Seconds";
    echo "<meta http-equiv=Refresh content=4;url=index.php>";
    }
    elseif($newsid)
    {
    
    $result = mysql_query("SELECT * FROM news WHERE newsid='$newsid' ",$connect);
    while($myrow = mysql_fetch_assoc($result))
    {
    $title = $myrow["title"];
    $text1 = $myrow["text1"];
    $text2= $myrow["text2"];
    ?>
    <br>
    <h3>::Edit News</h3>
    
    <form method="post" action="<?php echo $PHP_SELF ?>">
    <input type="hidden" name="newsid" value="<? echo $myrow['newsid']?>">
    
    Title: <input name="title" size="40" maxlength="255" value="<? echo $title; ?>">
    <br>
    Text1: <textarea name="text1" rows="7" cols="30"><? echo $text1; ?></textarea>
    <br>
    Text2: <textarea name="text2" rows="7" cols="30"><? echo $text2; ?></textarea>
    <br>
    <input type="submit" name="submit" value="Update News">
    </form>
    <?
    }//end of while loop
    
    }//end else
    ?>
    

    Ииииии накрая остана само файла с който се трият новините – delete_news.php

    <title>hotnews</title>
    <?php
    include("config.php");
    
    $result = mysql_query("DELETE FROM news WHERE newsid='$newsid' ",$connect);
    
    echo "<b>News Deleted!<br>You'll be redirected to Home Page after (4) Seconds";
    //header("location: index.php");
    echo "<meta http-equiv=Refresh content=4;url=index.php>";
    ?>

    Оставете коментар