RSS RSS

Open URL Link into tab window

By , March 23, 2011 6:45 am


To enable the URL link to open into another new tab window we need to add target=’_blank’ before the href where required. I have change view_bookmarks.php to include this.

Finding duplicate records in MySQL

By , February 5, 2011 1:53 pm


I have added a new function to the add bookmarks & category form to look for duplicate URL’s in the database, and stop them being added into the bookmarks table

First step is to move if(empty($errors)) from above the main query to insert the bookmark into the table to below the input validation section. We then add the test for unique URL just below the if(empty($errors))

if(empty($errors)) {

// checks for duplicate URL

$q = "SELECT bmarks_id FROM b_marks WHERE baddy='$ba'";
$stmt = mysqli_query ($dbc, $q);

if (mysqli_num_rows($stmt) == 0) {

//check if new category is being entered.

This will check the database table for a match of URL’s, if one is found we echo the below which is inserted as the last item when confirming the results of the query, otherwise the query will run.

} else {
echo '<p>URL has already been entered</p>';
}

As you can see I have changed the layout & formated the forms (you can only see this if you login which is just me at the min), I will post all the new files soon once I have cleaned it all up.

Security update to edit_bmarks script

By , June 11, 2010 9:00 am

I have omitted a basic security script on edit_bmarks.php file. I failed to start a session and a script to direct the user if someone accessed the url direct. you could have entered this bookmarks/edit_bmark.php?id=27 and have access to it without logging in!! so please amend the script with the below at the very start


<?php # Script 0.5 - edit_bmark.php
// Allows user to edit current bookmark
// If no session value is present, redirect the user:
session_start(); // Access the existing session.

if (!isset($_SESSION['user_id'])) {
require_once ('includes/login_functions.inc.php');
$url = absolute_url();
header("Location: $url");
exit();
}

Also if you used this script for editing the bookmarks, it would have not worked correctly. I have now fixed it so please download source file right hand click and save as here.

Bookmarks PHP Pagination update

By , April 27, 2010 6:20 pm

I have updated the view_bookmarks.php. script so that the pagination now works correctly once you have selected a category. This will of course only show once you have more than 10 records within a category as the $display is hard coded in at 10.

1) After the $display insert the below, this will check for a category id within the URL.


// check for category in URL
if (isset($_GET['cid']) && is_numeric($_GET['cid']) ) {
$cid = (int) $_GET['cid'];
}

2) Then after the // already determined.
if (isset($_GET[‘p’]) && is_numeric($_GET[‘p’])) {
$pages = $_GET[‘p’]; we need to include an else.


} else { // need to determine

if ($cid > 0) {

and a variable to check that the category id is greater than zero.

3) We need to write another mysql query to count the number of rows per category selected, then another else if no category is selected.


// Count number of records per category
$q = "SELECT COUNT(cat_id) FROM b_marks WHERE cat_id = $cid";
$r = @mysqli_query ($dbc, $q);
$row = @mysqli_fetch_array ($r, MYSQLI_NUM);
$records = $row[0];

} else {

4) Finally we need to edit the echo() statements that create the links so that the category value is passed. We add name=value ( ‘&cid=’ . $cid .) pair at the end of each statement. (PS: I had to remove some of the HTML from the below code for it to show, not sure why?)


// if it's not first page make a previous button:

if ($current_page !=1) {
href="view_bookmarks.php?s='. ($start - $display) . '&p=' . $pages '&cid=' . $cid . '">Previous;
}

// make all the numbered pages:

for ($i = 1; $i <= $pages; $i++) {
if ($i !=$current_page) {
echo ' herf="view_bookmarks.php?s='. (($display*($i - 1))). '&p=' . $pages .
'&cid=' . $cid . '">' .$i. ';
} else {
echo '<li>' .$i .'</li>';
}
} // end of FOR loop.

// If it's not the last page, make a Next button:
if ($current_page != $pages) {
echo'
href="view_bookmarks.php?s='. ($start + $display) . '&p=' . $pages .
'&cid=' . $cid . '">Next

I have a few more things in the pipeline to upgrade the bookmark app, so more coming soon ish!!!

Create RSS feed with PHP

By , March 27, 2010 11:40 am

In this tutorial we shall be looking how to make an RSS feed using php & xml for the bookmark application.

1) First create the below


<?php # script 0.5 - bmarks_rss.php

2) Then we need to send the content-type header


// This will create an RSS feed.

header('Content-type: text/xml');

This page will have a .php extension as it’s a php page that must be handled correctly by the Web server.

3) Create the initial RSS code:


echo '<?xml version="1.0"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<atom:link href="http://dev.basshead.info/phpdev/bmarks_rss.php" rel="self" type="application/rss+xml" />
<title>Bookmarks by Basshead</title>
<description>New bookmarks added by Basshead!!</description>
<link>http://dev.basshead.info/phpdev/</link>';

4) Connect to the database


require_once ('../mysqli_connect_bm.php');

This may be different depending how you have set-up your database connection.

5)Define the query


$q = "SELECT bmarks_id, bname, baddy, bmdesc, added_date
FROM b_marks
ORDER BY b_marks.added_date DESC
LIMIT 50";

You must have date column within your b_marks table, if you do not have one then please create one before moving on. Again this query may change if your database structure is different.

6) Retrieve the results


$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQL_NUM)) {

7) Print each record


echo '<item>
<title>' . htmlentities($row[1]) . '</title>
<description>' . htmlentities($row[3]) . '</description>
<link>' . $row[2] . '</link>
<guid>' . $row[2] . '</guid>
<pubDate>' . date('r', strtotime ($row[4])) . '</pubDate>
</item>
';

} // End of while loop

This is the most important part of the script. The title is the bookmark name, then the description which is run through the htmlentities() function as xml does not allow many characters that may appear. Next is the link to the bookmark URL then guid which is not required but a good idea as it’s a unique identifier for each item.
Finally the pubDate which needs to be an exact format, but using php date() function and the :r makes a shortcut to the process. I have also added strtotime to help with the date format. This was a problem area for me so you may not need that.

8 ) Last but by no means least complete the channel and rss element

// complete channel and rss element

echo '</channel>
</rss>
';

?>

Then test it out in an application that supports RSS feeds.

Created an RSS feed

By , February 9, 2010 10:53 am

Created RSS feed for the bookmark application that I have been building. You can access it via this link here, I will create a icon etc for it soon and also look out for the tutorial on “Creating RSS Feed”

mysql & php bookmark application – tutorial – Part 3

By , February 3, 2010 8:51 pm


We are carrying on with the bookmarks application. In this tutorial we shall be adding add & edit bookmarks. Just follow the example below and the comments will explain what each script does. Now let get started.

1 – Add New Bookmark

This will allow you add a new bookmark & new category if one is not avaiable.


<?php # Script 0.5 - add_bm_cat.php
session_start(); // Access the existing session.

// If no session value is present, redirect the user:
if (!isset($_SESSION['user_id'])) {
require_once ('includes/login_functions.inc.php');
$url = absolute_url();
header("Location: $url");
exit();
}

$page_title = 'Add new Bookmarks';

include ('includes/header.html');

// connect to db
require_once ('../mysqli_connect_bm.php');

if (isset($_POST['submitted'])) {

$errors = array();

// check for bookmark name

if (!empty($_POST['bname'])) { $bn =trim($_POST['bname']);
} else {
$errors[] = 'Please enter URL title';
}

// check for URL

if (!empty($_POST['baddy'])) { $ba =trim($_POST['baddy']);
} else {
$errors[] = 'Please enter URL address';
}

// check for description

if (!empty($_POST['bmdesc'])) { $bm =trim($_POST['bmdesc']);
} else {
$errors[] = 'Please enter description';
}

//check if new category is being entered.

if(isset($_POST['category']) && ($_POST['category'] == 'new') )
{

// validate category

if (!empty($_POST['cat_name'])) {
$cn = trim($_POST['cat_name']);

// add new category to db

$q = 'INSERT INTO category (cat_name) VALUES (?)';

$stmt = mysqli_prepare($dbc, $q);

mysqli_stmt_bind_param($stmt, 's', $cn);

mysqli_stmt_execute($stmt);

if(mysqli_stmt_affected_rows($stmt) == 1) {
echo '<p>new category added. </p>';
$ci = mysqli_stmt_insert_id($stmt);

} else {

$errors[]='New category could not be added!';
}
mysqli_stmt_close($stmt);

// Complete category conditional

} else { // no category name
$errors[] ='Please enter the category name';

}

} elseif ( isset($_POST['category'])&&($_POST['category'] == 'existing')
&&($_POST['existing'] > 0) )
{

$ci = (int) $_POST['existing'];
} else { // no catergory selected.

$errors[]= 'Please enter Category';

}

// insert into DB b_marks

if(empty($errors)) {
$q = 'INSERT INTO b_marks (bname, baddy, bmdesc, cat_id)
VALUES (?, ?, ?, ?)';

$stmt = mysqli_prepare($dbc, $q);

mysqli_stmt_bind_param($stmt, 'sssi', $bn, $ba, $bm, $ci);

mysqli_stmt_execute($stmt);

// confirm results of the query.

if (mysqli_stmt_affected_rows ($stmt) ==1)
{
echo '<p> The bmark is added. </p>';
}else{
echo '<p>error system overload aahh</p>';
}

// Complete the conditionals

mysqli_stmt_close($stmt);
} // end of $errors if
} // end of submission if

?>

<h2>Enter a new Bookmark</h2>
<form action="add_bm_cat.php" method="post">
<p>Bookmark Name: <input type="text" name="bname" size="15" maxlength="20" value="
<?php if (isset($_POST['bname'])) echo $_POST['bname']; ?>" /></p>

<p>URL Address: <input type="text" name="baddy" size="50" maxlength="80" value="
<?php if (isset($_POST['baddy'])) echo $_POST['baddy']; ?>" /></p>

<p>Description: <textarea name="bmdesc" cols="40" rows="5" >
<?php if (isset($_POST['bmdesc'])) echo $_POST['bmdesc']; ?> </textarea></p>

<div>Category:
<p><input type="radio" name="category" value ="existing"
<?php if (isset($_POST['category']) && ($_POST['category']=='existing'))
echo 'checked="checked"'; ?> />
Exisitng =>
<select name="existing"><option>Select One</option>

// Retrive Category

<?php $q = "SELECT cat_id, (cat_name) FROM category ORDER BY cat_name ASC";

$r = mysqli_query ($dbc, $q);

if (mysqli_num_rows($r) > 0) {
while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {

echo "<option value=\"$row[0]\"";

if (isset($_POST['existing']) && ($_POST['existing'] == $row[0]) )
echo ' selected="selected"';
echo ">$row[1]</option>\n";

}

} else {

echo '<option>Please add a new category. </option>';

}

mysqli_close($dbc);

?>

</select></p>

<p><input type="radio" name="category" value ="new"
<?php if (isset($_POST['category']) && ($_POST['category']=='new'))
echo 'checked="checked"'; ?> />
New =>
Category Name: <input type="text" name="cat_name" size="15" maxlength="25"
value="<?php if(isset($_POST['cat_name']))
echo $_POST['cat_name']; ?>"
</p>
</div>

<div align="center"><input type="submit" name="submit" value="Submit" /></div>
<input type="hidden" name="submitted" value="TRUE" />

</form>

<?php
include ('includes/footer.html');
?>

2 – Edit Bookmarks
In this script you will be able to edit current bookmarks or delete them, also added to this which has not been included within the previous tutorial in view_bookmarks.php is pagination of listed records.

<?php # script 0.5 - edit_view_bookmarks.php

session_start(); // Access the existing session.

// If no session value is present, redirect the user:
if (!isset($_SESSION['user_id'])) {
require_once ('includes/login_functions.inc.php');
$url = absolute_url();
header("Location: $url");
exit();
}

//Set the page title and include the html header:

$page_title = 'Edit & View the Bookmarks';

include ('includes/header.html');

require_once ('../mysqli_connect_bm.php');

// Number of records to display

$display = 10;

// Determine how many pages

if (isset($_GET['p']) && is_numeric($_GET['p'])) { // already determined.

$pages = $_GET['p'];

} else { // need to determine

// Count number of records
$q = "SELECT COUNT(bmarks_id) FROM b_marks";
$r = @mysqli_query ($dbc, $q);
$row = @mysqli_fetch_array ($r, MYSQLI_NUM);
$records = $row[0];

// Calculate the number of pages
if ($records > $display) { //more than one page
$pages = ceil ($records/$display);
} else {
$pages =1;
}
} // end of p if

// determine where in the database to start results.

if (isset($_GET['s']) && is_numeric ($_GET['s'])) {
$start = $_GET['s'];
} else {
$start = 0;
}

// Define the query

$q = "SELECT category.cat_id,
cat_name, bmarks_id, bname, baddy, bmdesc FROM category, b_marks
WHERE
category.cat_id = b_marks.cat_id
ORDER BY
category.cat_name ASC,
b_marks.bname ASC
LIMIT $start, $display";

// check for category in URL

if (isset($_GET['cid']) && is_numeric($_GET['cid']) ) {
$cid = (int) $_GET['cid'];

// overwrite the query
if ($cid > 0) {

$q = "SELECT category.cat_id,
cat_name, bmarks_id, bname, baddy, bmdesc FROM category, b_marks
WHERE
category.cat_id = b_marks.cat_id
AND b_marks.cat_id = $cid
ORDER BY
category.cat_name ASC,
b_marks.bname ASC
LIMIT $start, $display";

}
}

$r = @mysqli_query ($dbc, $q); // Run the query.

// Count the number of returned rows:
$num = mysqli_num_rows($r);

if ($num > 0) { // If it ran OK, display the records.

// Table header.
echo '<table id="mytable" cellspacing="0" summary="The List of Bookmarks">
<tr>
<th scope="col" abbr="Edit">Edit</th>
<th scope="col" abbr="Category">Category</th>
<th scope="col" abbr="URL Link">URL Link</th>
<th scope="col" abbr="Description">Description</th>
<th scope="col" abbr="Delete">Delete</th>
</tr>
';

// Fetch and print all the records:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee'); // Switch the background color.

echo '<tr bgcolor="' . $bg . '">
<td>Edit</td>
<td>' . $row['cat_name'] . '</td>
<td>' . $row['bname'] . '</td>
<td>' . $row['bmdesc'] . '</td>
<td>Delete</td>
</tr>
';
}

echo '</table>'; // Close the table.

mysqli_free_result ($r); // Free up the resources.

} else { // If no records were returned.

echo '<p class="error">There are currently no listed bookmarks.</p>';

}
// make the links to other pages, if required.
if ($pages > 1) {
// add some spacing and start a paragraph
echo '<br /><p>';
// determine what page the script is on:
$current_page = ($start/$display) +1;

// if it's not first page make a previous button:

if ($current_page !=1) {
echo 'Previous ';
}

// make all the numbered pages:

for ($i = 1; $i <= $pages; $i++) {
if ($i !=$current_page) {

echo '' .$i. '';
} else {

echo $i . ' ';

}
} // end of FOR loop.

// If it's not the last page, make a Next button:
if ($current_page != $pages) {
echo 'Next';
}

echo '</p>'; // close the paragraph.

} // End of links section.
echo '</div>';

//*make category summary list*

// Define the query
echo '<div id="sidebar">';
$q = "SELECT category.cat_id, cat_name FROM category ORDER BY cat_name ASC";

// check for category in URL

if (isset($_GET['cid']) && is_numeric($_GET['cid']) ) {
$cid = (int) $_GET['cid'];

}
$r = @mysqli_query ($dbc, $q); // Run the query.

// Table header.
echo '<table id="mytable2" cellspacing="0" summary="Select Category">
<tr>
<th scope="col" abbr="Category">Category</th>
</tr>
';

// Fetch and print all the records:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee'); // Switch the background color.

echo "<tr bgcolor={$bg}>
<td>{$row['cat_name']}</td>
</tr>";

}

echo '</table>'; // Close the table.

mysqli_close($dbc); // Close the database connection.

include ('includes/footer.html');
?>

The above also includes a sidebar to select links based on category, also I have changed the CSS layout so the change must be reflected in view_bookmarks.php. So to save the effort please download updated files from here. Right hand click and save as CSS FileFooterHeaderView Bookmarks also images from here. Please remember to change the URL links within the header so that the links work. Any problems, questions or bugs then leave a comment.

Next tutorial will be creating RSS feed. I have started work on this and is close to completion.

Update: mysql & php bookmark application – tutorial – Part 2

By , January 14, 2010 1:41 pm

I had hope to get part 2 of the tutorial up before the end of 2009, but this did not happen. I have been working on this project so have made some improvements to it. please visit phpdev for what the current bookmark application looks like and works. Still many thing to do but it’s getting they.
Please look out for Part 2 in the next couple of weeks.

mysql & php bookmark application – tutorial – Part 1

By , November 9, 2009 7:42 pm


In this tutorial we are going to create a basic bookmark/links application using php & mysql. It’s aimed and beginners but does require a good understanding of html, css, php & mysql, website structure and that you have access to localhost running a web server or external service.

Now the first part is to create the database, we are going to create three tables. 1) b_marks 2) category 3) user.

Log into your preferred mysql interface.
1) Create the database

CREATE DATABASE bookmarks;
USE bookmarks;

2) Create the b_marks table to store the bookmarks/URL links.

CREATE TABLE `bookmarks`.`b_marks`(
`bmarks_id` int(10) unsigned NOT NULL auto_increment,
`bname` varchar(100) NOT NULL,
`baddy` varchar(500) NOT NULL,
`bmdesc` longtext NOT NULL,
`cat_id` int(10) NOT NULL,
`user_id` int(10) default NULL,
PRIMARY KEY (`bmarks_id`)
) ENGINE=MyISAM AUTO_INCREMENT=26 DEFAULT CHARSET=latin1;

3) Create category table to store the category list.

CREATE TABLE `bookmarks`.`category` (
`cat_id` int(10) unsigned NOT NULL auto_increment,
`cat_name` varchar(50) NOT NULL,
PRIMARY KEY (`cat_id`),
UNIQUE KEY `cat_name` (`cat_name`)
) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=latin1;

4) Create users table as you will need to log in to enter & edit the bookmarks.

CREATE TABLE `bookmarks`.`users` (
`user_id` mediumint(8) unsigned NOT NULL auto_increment,
`username` varchar(30) NOT NULL,
`pass` char(40) NOT NULL,
`first_name` varchar(20) NOT NULL,
`last_name` varchar(40) NOT NULL,
`email` varchar(80) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

Once the above has been created you will need to add a user to the users database,

INSERT INTO users (username, pass, first_name, last_name, email)
VALUES (‘username’, SHA1(‘password’),’yourfn’, ‘yourlast’, ’email@email.com’);

Now the above database has been completed we can start with building the application, the list below is the order of files that need to be created. You do not have to follow the order but that’s how I did it.

1) mysqli_connect_bm.php // To enable connection to your bookmarks database.

<?php # mysqli_connect_bm.php

// This file contains the database access information.
// This file also establishes a connection to MySQL
// and selects the database.
// Set the database access information as constants:

DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', 'pass');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'bookmarks');

// Make the connection:

$dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );

?>

Once the above is created save as mysqli_connect_bm.php and place it outside of the web document directory.

2) Create Header


<?php # script 0.5 - header.html

session_start();

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

<title><?php echo (isset($page_title)) ? $page_title : 'Bookmarks!'; ?></title>

<link rel="stylesheet" href="/phpdev/includes/style.css" type="text/css" media="screen" />

</head>

<body>

<div id="header">

<h3>Bookmarks of Basshead</h3>
<h4>List of handy bookmarks</h4>

</div>

<div id="navigation">
<ul>

// using sessions to enable different links based on whether a user is logged in or not
<?php
if ( (isset($_SESSION['user_id'])) && (!strpos($_SERVER['PHP_SELF'], 'logout.php')) ) {
echo '<li><a href="/phpdev/edit_view_bookmarks.php">Edit/View Bookmarks</a></li>';
echo '<li><a href="/phpdev/add_bm_cat.php">Add New Bookmark</a></li>';
echo '<li><a href="/phpdev/logout.php">Logout</a></li>';

} else {

echo '<li><a href="/phpdev/view_bookmarks.php">View Bookmarks</a></li>';
echo '<li><a href="/phpdev/login.php">Login</a></li>';

}

?>
</ul>
</div>
<div id="content">
</code markup="none">
</div>
Save the file as header.html and place it in your includes directory

<strong>3) Create the footer</strong>
<div class="box">
<code>
</div>

<div id="footer">

<p>Copyright &copy; <a href="#">Dev.Basshead</a> 2008 | Designed by <a href="http://www.basshead.info/">basshead</a> Valid <a href="http://jigsaw.w3.org/css-validator/">
<img style="border:0;width:44px;height:15px"
src="http://jigsaw.w3.org/css-validator/images/vcss-blue"
alt="Valid CSS!" /></a>
</div>

</body>

</html>

Save the file as footer.html and place it in your includes directory

4) Create login functions page that will be used in the login & logout process

<?php # login_functions.inc.php

// This page defines two functions used by the login/logout process.

/* This function determines and returns an absolute URL.
* It takes one argument: the page that concludes the URL.
* The argument defaults to view_bookmarks.php.
*/

function absolute_url ($page = 'view_bookmarks.php') {

//URL is http:// plus the host name plus the current directory

$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);

// remove any trailing slashes:

$url = rtrim($url, '/\\');

// Add the page

$url .= '/' . $page;

// Return the URL

return $url;

} // End of absolute_url() function.

/*This function validates the form data (the email address and password).
* If both are present, the database is queried.
* The function requires a database connection.
* The functions returns an array of information,
*/

function check_login($dbc, $email = '', $pass = '') {

$errors = array(); // Initialize error array.

// Validates the email address and password:

if (empty($email)) {

$errors[] = 'You forgot to enter your email address dude. ';

} else {

$e = mysqli_real_escape_string ($dbc, trim($email));

}

if (empty($pass)) { $errors[] = 'You forgot to enter your password. ';

} else {

$p = mysqli_real_escape_string($dbc, trim($pass));

}

// no errors run the db query

if (empty($errors)) {
$q = "SELECT user_id, first_name FROM users WHERE email='$e' AND
pass=SHA1('$p')";

$r = @mysqli_query ($dbc, $q);

// Check results of query

if (mysqli_num_rows($r) == 1) {

// fetch the record:

$row = mysqli_fetch_array ($r, MYSQLI_ASSOC);

// return true and the record

return array(true, $row);

} else {

$errors[] = 'The email address and password entered do not match those on file.';

}

// Complete conditional & functions

} // End of empty($errors) IF.

return array(false, $errors);

} // End of check_login() function

?>

Save the file as login_functions.inc.php and place it in your includes directory

5) Create the login page that will enable you to login & include the login form.

<?php # login_page_inc.php

$page_title = 'Login';

include ('includes/header.html');

// print error messages
if (!empty($errors)) { echo '<h2>Error!</h2>
<p class="error">The following error(s) occurred:<br />';
foreach ($error as $msg) { echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p>';
}

?>

<h2>Login</h2>

<form action="login.php" method="post">
<p>Email Address: <input type="text" name="email" size="20" maxlength="80" /></p>

<p>Password: <input type="password" name="pass" size="20" maxlength="20" /></p>

<p><input type="submit" name="submit" value="Login" /></p>

<input type="hidden" name="submitted" value="TRUE" />

</form>

<?php
// Include the footer
include('includes/footer.html');
?>

Save the file as login_page.inc.php and place it in your includes directory

6) Create the CSS file, this you can edit to your delight as this is basic and still work in progress.

/* general */
a {
color:#777;
text-decoration:none;
}

a:hover {
color:#333;
text-decoration:none;
}

/* body */
body {
background:#fafafa;
color:#003300;
font:0.8em Arial, Helvetica, "bitstream vera sans", sans-serif;
}

/* header */
#header {
border-bottom:1px solid #999;
height:80px;
margin:0 auto;
width:751px;
}
#header h1 {
color:#888;
font-size:300%;
letter-spacing:-3px;
text-align:right;
padding:5px;
margin-bottom:-20px;
}
#header h2 {
color:#CCC;
font-size:200%;
letter-spacing:-2px;
text-align:right;
}

/* navigation */
#navigation {
background:#fafafa;
border-right:1px solid #999;
margin:0 auto;
width:750px;
height:40px;
list-style:none;
}
#navigation li {
border-left:1px solid #999;
float:left;
width:149px;
list-style:none;
}
#navigation a {
color:#555;
display:block;
line-height:40px;
text-align:center;
}
#navigation a:hover {
background:#e3e3e3;
color:#555;
}
#navigation .active {
background:#e3e3e3;
color:#777;
}

/* content */
#content {
height:auto;
margin:0 auto;
padding:0 0 20px;
width:751px;
}
#content h1 {
border-bottom:1px dashed #999;
font-size:1.8em;
padding:20px 0 0;
}
#content p {
padding:20px 20px 0;
}

/* footer */
#footer {
border-top:1px solid #999;
height:50px;
margin:0 auto;
padding:10px;
text-align:center;
width:751px;
}

/* error */

.error {
font-weight: bold;
color: #C00
}

Save the file as style.css and place it in your includes directory

Now the next steps are to create view bookmarks page & the final process to enable login & logout functions. This will require four more files.

7) View bookmarks – This script will enable you to view all the bookmarks by name, category and with description. You will also will be able to click on the URL and send you to your website. Added to this script is pagination so that you are direct to another page if rows listed are greater than 10 (This will be updated in future tutorial to include a drop down menu to enable you to select how many rows are listed on the page). The final feature is to sort by category, by clicking on a category name you will list all bookmarks for that category (Again more updates to this function in future tutorials).

<?php # view_bookmarks.php

//Set the page title and include the html header:

$page_title = 'View the Bookmarks';

include ('includes/header.html');

require_once ('../mysqli_connect_bm.php');

// Number of records to display

$display = 10;

// Determine how many pages

if (isset($_GET['p']) && is_numeric($_GET['p'])) { // already determined.

$pages = $_GET['p'];

} else { // need to determine

// Count number of records
$q = "SELECT COUNT(bmarks_id) FROM b_marks";
$r = @mysqli_query ($dbc, $q);
$row = @mysqli_fetch_array ($r, MYSQLI_NUM);
$records = $row[0];

// Calculate the number of pages
if ($records > $display) { //more than one page
$pages = ceil ($records/$display);
} else {
$pages =1;
}
} // end of p if

// determine where in the database to start results.

if (isset($_GET['s']) && is_numeric ($_GET['s'])) {
$start = $_GET['s'];
} else {
$start = 0;
}

// Define the query

$q = "SELECT category.cat_id,
cat_name, bname, baddy, bmdesc FROM category, b_marks
WHERE
category.cat_id = b_marks.cat_id
ORDER BY
category.cat_name ASC,
b_marks.bname ASC
LIMIT $start, $display";

// check for category in URL

if (isset($_GET['cid']) && is_numeric($_GET['cid']) ) {
$cid = (int) $_GET['cid'];

// overwrite the query
if ($cid > 0) {

$q = "SELECT category.cat_id,
cat_name, bname, baddy, bmdesc FROM category, b_marks
WHERE
category.cat_id = b_marks.cat_id
AND b_marks.cat_id = $cid
ORDER BY
category.cat_name ASC,
b_marks.bname ASC
LIMIT $start, $display";

}
}

$r = @mysqli_query ($dbc, $q); // Run the query.

// Count the number of returned rows:
$num = mysqli_num_rows($r);

if ($num > 0) { // If it ran OK, display the records.

// Print how many bookmarks there are:
echo "<p>There are currently $num Bookmarks Listed.</p>\n";

// Table header.
echo '<table align="center" cellspacing="3" cellpadding="3" width="100%">
<tr><td align="left"><b>Category</b></td>
<td align="left"><b>URL Link</b></td>
<td align="left"><b>Description</b></td>
</tr>
';

// Fetch and print all the records:

$bg = '#eeeeee'; // set the initial background colour

while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee'); // Switch the background color.

echo "\t
<tr bgcolor={$bg}>
<td align=\"left\"><a href=\"view_bookmarks.php?cid={$row['cat_id']}
\">{$row['cat_name']}</a></td>
<td align=\"left\"><a href={$row['baddy']}>{$row['bname']}</td>
<td align=\"left\">{$row['bmdesc']}</td>
</tr>\n";
}

echo '</table>'; // Close the table.

mysqli_free_result ($r); // Free up the resources.

} else { // If no records were returned.

echo '<p class="error">There are currently no listed bookmarks.</p>';

}

mysqli_close($dbc); // Close the database connection.

// make the links to other pages, if required.
if ($pages > 1) {
// add some spacing and start a paragraph
echo '<br /><p>';
// determine what page the script is on:
$current_page = ($start/$display) +1;

// if it's not first page make a previous button:

if ($current_page !=1) {
echo '<a href="view_bookmarks.php?s=' . ($start - $display) . '&p=' . $pages .
'">Previous</a> ';
}

// make all the numbered pages:

for ($i = 1; $i <= $pages; $i++) {
if ($i !=$current_page) {

echo '<a href="view_bookmarks.php?s=' . ($start + $display) . '&p=' . $pages .
'">Next</a>';
} else {

echo $i . ' ';

}
} // end of FOR loop.

echo '</p>'; // close the paragraph.

} // End of links section.

include ('includes/footer.html');
?>

Save the file in your root web directory as view_bookmarks.php

8) Login function, this script will call for the login_functions.inc.php file and then redirect to loggedin.php if logged in.

<?php # login.php

if (isset($_POST['submitted'])) {

require_once ('includes/login_functions.inc.php');
require_once ('../mysqli_connect_bm.php');
list ($check, $data) = check_login($dbc, $_POST['email'], $_POST['pass']);

if ($check) { // OK!

// Set the session data:.
session_start();
$_SESSION['user_id'] = $data['user_id'];
$_SESSION['first_name'] = $data['first_name'];

// Redirect:
$url = absolute_url ('loggedin.php');
header("Location: $url");
exit();

} else { // Unsuccessful!
$errors = $data;
}

mysqli_close($dbc);

} // End of the main submit conditional.

include ('includes/login_page.inc.php');
?>

Save in root directory as login.php

9) The loggdein script is used to redirect you from login.php file with a message and also redirect if accessed in error.

<?php # loggedin.php

// The user is redirected here from login.php.

session_start(); // Start the session.

// If no session value is present, redirect the user:
if (!isset($_SESSION['user_id'])) {
require_once ('includes/login_functions.inc.php');
$url = absolute_url();
header("Location: $url");
exit();
}

$page_title = 'Logged In!';
include ('includes/header.html');

// Print a customized message:
echo "<h2>Logged In!</h2>
<p>You are now logged in, {$_SESSION['first_name']}!</p>";

include ('includes/footer.html');
?>

Save in root directory as loggedin.php

10) Now for the logout script. this will log you out and clear the session data

<?php - logout.php
// This page lets the user logout.

session_start(); // Access the existing session.

// If no session variable exists, redirect the user:
if (!isset($_SESSION['user_id'])) {

require_once ('includes/login_functions.inc.php');
$url = absolute_url();
header("Location: $url");
exit();

} else { // Cancel the session.

$_SESSION = array(); // Clear the variables.
session_destroy(); // Destroy the session itself.
setcookie ('PHPSESSID', '', time()-3600, '/', '', 0, 0); // Destroy the cookie.

}

// Set the page title and include the HTML header:
$page_title = 'Logged Out!';
include ('includes/header.html');

// Print a customized message:
echo "<h2>Logged Out!</h2>
<p>Goodbye you are now logged out!</p>";

include ('includes/footer.html');
?>

Save in root directory as logout.php

Now you should be able test all this out and login/logout. You cannot view any bookmarks as we have yet to do that script, but I think this will do it for this tutorial. So hopefully this will all work and check back soon for the final part. Once the final tutorial is complete you should have a complete bookmark/URL application. I will then add more tutorials as I develop it myself with more functions and more pleasing to the eye.

If you notice any errors, problems then please let me know as I’m a beginner at all this.

PHP & Mysql Bookmarks app

By , October 1, 2009 8:33 pm

Please look out for my tutorial on how to build your own bookmarks/links application using php & mysql coming soon

The first stage is close to completion, so hopefully within two weeks or so the first part of the tutorial will be up, then I will add extra parts to it as it’s developed

Persephone Theme by Themocracy