Bookmarking App With PHP, JS & MySQL

Simple Bookmarking App With PHP, JS & MySQL


connect.php
------------
<?php
//Step 1: connect database
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
mysql_select_db('table');

?>

demo.php
---------
<?php

// Error reporting:
error_reporting(E_ALL^E_NOTICE);

require "connect.php";
require "functions.php";

$url = 'http://'.$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"]);

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Bookmarking App With PHP, JavaScript &amp; MySQL | Tutorialzine demo</title>

<link rel="stylesheet" type="text/css" href="styles.css" />

</head>

<body>

<h1>Simple Bookmarking App With PHP, JS &amp; MySQL</h1>
<h2><a href="http://tutorialzine.com/2010/04/simple-bookmarking-app-php-javascript-mysql/">Go Back to the Tutorial &raquo;</a></h2>

<div id="main">

    <div class="bookmarkHolder">
   
        <!--    The link contains javascript functionallity which is preserved
                when the user drops it to their bookmark/favorites bar    -->

        <a href="javascript:(function(){var jsScript=document.createElement('script');
jsScript.setAttribute('type','text/javascript');
jsScript.setAttribute('src', '<?php echo $url?>/bookmark.php?url='+encodeURIComponent(location.href)+'&amp;title='+encodeURIComponent(document.title));
document.getElementsByTagName('head')[0].appendChild(jsScript);
})();" class="bookmarkButton">Bookmark this!</a>
       
        <em>jaydeep Gondaliya.</em>
    </div>
   
    <ul class="latestSharesUL">
        <?php
        $sql = 'SELECT * FROM bookmark_app ORDER BY id DESC LIMIT 6';

   
        $retval = mysql_query($sql);
        if(! $retval )
        {
          die('Could not get data: ' . mysql_error());
        }
        while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
        {
            // Shortening the title if it is too long:
            if(mb_strlen($row['title'],'utf-8')>80)
                $row['title'] = mb_substr($row['title'],0,80,'utf-8').'..';
           
            // Outputting the list elements:
            echo '
            <li>
                <div class="title"><a href="'.$row['url'].'" class="bookmrk">'.$row['title'].'</a></div>
                <div class="dt">'.relativeTime($row['dt']).'</div>
            </li>';
        }
        ?>
    </ul>
   
</div>

</body>
</html>
---------
functions.php
--------------
<?php

/* Helper functions */

function validateURL($str)
{
    return preg_match('/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:\/~\+#]*[\w\-\@?^=%&amp;\/~\+#])?/i',$str);
}

function sanitize($str)
{
    if(ini_get('magic_quotes_gpc'))
        $str = stripslashes($str);

    $str = strip_tags($str);
    $str = trim($str);
    $str = htmlspecialchars($str);
    $str = mysql_real_escape_string($str);
   
    return $str;
}


function relativeTime($dt,$precision=2)
{
    if(is_string($dt)) $dt = strtotime($dt);
   
    $times=array(    365*24*60*60    => "year",
                    30*24*60*60        => "month",
                    7*24*60*60        => "week",
                    24*60*60        => "day",
                    60*60            => "hour",
                    60                => "minute",
                    1                => "second");
   
    $passed=time()-$dt;
   
    if($passed<5)
    {
        $output='less than 5 seconds ago';
    }
    else
    {
        $output=array();
        $exit=0;
       
        foreach($times as $period=>$name)
        {
            if($exit>=$precision || ($exit>0 && $period<60)) break;
           
            $result = floor($passed/$period);
            if($result>0)
            {
                $output[]=$result.' '.$name.($result==1?'':'s');
                $passed-=$result*$period;
                $exit++;
            }
            else if($exit>0) $exit++;
        }
               
        $output=implode(' and ',$output).' ago';
    }
   
    return $output;
}

// Defining fallback functions for mb_substr and
// mb_strlen if the mb extension is not installed:

if(!function_exists('mb_substr'))
{
    function mb_substr($str,$start,$length,$encoding)
    {
        return substr($str,$start,$length);
    }
}

if(!function_exists('mb_strlen'))
{
    function mb_strlen($str,$encoding)
    {
        return strlen($str);
    }
}
?>



tabel.sql
--------
--
-- Table structure for table `bookmark_app`
--

CREATE TABLE `bookmark_app` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `hash` varchar(32) collate utf8_unicode_ci NOT NULL default '',
  `url` text collate utf8_unicode_ci NOT NULL,
  `title` text collate utf8_unicode_ci NOT NULL,
  `dt` timestamp NOT NULL default CURRENT_TIMESTAMP,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `hash` (`hash`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

bookmark.php
---------------
<?php

// Error reporting:
error_reporting(E_ALL^E_NOTICE);

require "connect.php";
require "functions.php";

// Setting the content-type header to javascript:
header('Content-type: application/javascript');

// Validating the input data
if(empty($_GET['url']) || empty($_GET['title']) || !validateURL($_GET['url'])) die();

// Sanitizing the variables
$_GET['url'] = sanitize($_GET['url']);
$_GET['title'] = sanitize($_GET['title']);

// Inserting, notice the use of the hash field and the md5 function:
mysql_query("    INSERT INTO bookmark_app (hash,url,title)
                VALUES (
                    '".md5($_GET['url'])."',
                    '".$_GET['url']."',
                    '".$_GET['title']."'
                )");

$message = '';
if(mysql_affected_rows($link)!=1)
{
    $message = 'This URL already exists in the database!';
}
else
{
    $message = 'The URL was shared!';
}



?>

/* JavaScript Code */

function displayMessage(str)
{
    // Using pure JavaScript to create and style a div element
   
    var d = document.createElement('div');
   
    with(d.style)
    {
        // Applying styles:
       
        position='fixed';
        width = '350px';
        height = '20px';
        top = '50%';
        left = '50%';
        margin = '-30px 0 0 -195px';
        backgroundColor = '#f7f7f7';
        border = '1px solid #ccc';
        color = '#777';
        padding = '20px';
        fontSize = '18px';
        fontFamily = '"Myriad Pro",Arial,Helvetica,sans-serif';
        textAlign = 'center';
        zIndex = 100000;
       
        textShadow = '1px 1px 0 white';
       
        MozBorderRadius = "12px";
        webkitBorderRadius = "12px";
        borderRadius = "12px";
       
        MozBoxShadow = '0 0 6px #ccc';
        webkitBoxShadow = '0 0 6px #ccc';
        boxShadow = '0 0 6px #ccc';
    }
   
    d.setAttribute('onclick','document.body.removeChild(this)');
   
    // Adding the message passed to the function as text:
    d.appendChild(document.createTextNode(str));
   
    // Appending the div to document
    document.body.appendChild(d);
   
    // The message will auto-hide in 3 seconds:
   
    setTimeout(function(){
        try{
            document.body.removeChild(d);
        }    catch(error){}
    },3000);
}

<?php

// Adding a line that will call the JavaScript function:
echo 'displayMessage("'.$message.'");';

?>






Share on Google Plus

About quora Questions & Answers A-Z

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment