www.Tutorialsforu.info

Free Tutorials Cave

  • Increase font size
  • Default font size
  • Decrease font size
Your Ad Here



MySql General

Create New MySQL Database

E-mail Print
Current revision posted to MySQL Tutorials by admin on 12/19/2008 7:22:08 PM

You need to use mysqladmin to create MySQL database. The command is simple just write mysqladmin in a dos window followed by the database name you want to create

C:>mysqladmin create petstore

C:>mysql
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 3 to server version: 4.0.18-nt

Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

mysql> SHOW databases;
+----------+
| Database |
+----------+
| mysql    |
| petstore |
| test     |
+----------+
2 rows in set (0.00 sec)

mysql>

You can also type the query in mysql> prompt like this

mysql> CREATE database petstore;
Query OK, 1 row affected (0.00 sec)

To show available databases in mysql use the command show databases on mysql> prompt. Now use the database by typing USE petstore and then type SHOW tables to see what tables are available in the database

mysql> USE petstore;
Database changed
mysql> SHOW tables;
Empty set (0.00 sec)

Next I will show you how to create table in mysql database


Read Full Article
 

Add New MySQL User

E-mail Print
Current revision posted to MySQL Tutorials by admin on 12/19/2008 7:20:35 PM

For adding a new user to MySQL you just need to add a new entry to user table in database mysql. Below is an example of adding new user phpcake with SELECT, INSERT and UPDATE privileges with the password mypass the SQL query is :

mysql> use mysql;
Database changed

mysql> INSERT INTO user (host, user, password, select_priv, insert_priv, update_priv) VALUES ('localhost', 'phpcake', PASSWORD('mypass'), 'Y', 'Y', 'Y');
Query OK, 1 row affected (0.20 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 1 row affected (0.01 sec)

mysql> SELECT host, user, password FROM user WHERE user = 'phpcake';
+-----------+---------+------------------+
| host      | user    | password         |
+-----------+---------+------------------+
| localhost | phpcake | 6f8c114b58f2ce9e |
+-----------+---------+------------------+
1 row in set (0.00 sec)

 

When adding a new user remember to encrypt the new password using PASSWORD() function provided by MySQL. As you can see in the above example the password mypass is encrypted to 6f8c114b58f2ce9e.

Notice the the FLUSH PRIVILEGES statement. This tells the server to reload the grant tables. If you don't use it then you won't be able to connect to mysql using the new user account (at least until the server is reloaded).

You can also specify other privileges to a new user by setting the values of these columns in user table to 'Y' when executing the INSERT query :

  • Select_priv
  • Insert_priv
  • Update_priv
  • Delete_priv
  • Create_priv
  • Drop_priv
  • Reload_priv
  • Shutdown_priv
  • Process_priv
  • File_priv
  • Grant_priv
  • References_priv
  • Index_priv
  • Alter_priv

I think you can guess what those privileges serve by reading it's name


Read Full Article
 

Starting MySQL

E-mail Print
Current revision posted to MySQL Tutorials by admin on 12/19/2008 7:18:19 PM

Before starting the MySQL client make sure the server is turned on. If you run Windows 9x start the mysqld.exe or if you run Windows 2000/XP run the mysqld-nt.exe

 

The --console option tells mysqld-nt not to remove the console window. if you are running Windows NT/2000/XP it's better to install MySQL as a service. That way mysql server will be automatically started when you start Windows.

Use mysqld-nt --install to install mysqld as a service and mysqld-nt --remove to remove mysqld from the service list

Once the server is on, open another DOS window and type mysql, you should see something like this

C:>mysql
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 3 to server version: 4.0.18-nt

Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

mysql>

Or if you need to specify a user name and password you can start mysql like this :

C:>mysql -h localhost -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 4 to server version: 4.0.18-nt

Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

mysql>

You can also specify the database you want to use. If you already have a database named petstore you can start mysql as

C:>mysql petstore
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 5 to server version: 4.0.18-nt

Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

mysql>

Once you're done you can end mysql client by typing quit or exit at the mysql> prompt

mysql> exit
Bye

C:>

Note : If you get this kind of error message when trying to run mysql from the DOS window

C:>mysql
'mysql' is not recognized as an internal or external command,
operable program or batch file.

that means you haven't set the path to mysql bin directory. To solve the problem you can add the following line to your autoexec.bat file :

path=%path%;c:mysqlbin

assuming that you install MySQL in c:mysql. Or if you're using Windows XP you can go to :

Start->Settings->Control Panel->System->Advanced->Environment Variables

Chose Edit on the System Variables section and add c:mysqlbin to the path environment variable.


Read Full Article
 

User Authentication : Storing User ID's and Passwords In a MySQL Database

E-mail Print
Current revision posted to MySQL Tutorials by admin on 12/18/2008 8:49:09 PM

A more common method of authenticating a user is by checking the database to see if the submitted user id and password combination exist. To use this kind of authentication we must first build the database table. The sql code to build it is shown below. We also add two user accounts for testing the login script

 

CREATE TABLE tbl_auth_user (
user_id VARCHAR(10) NOT NULL,
user_password CHAR(32) NOT NULL,

PRIMARY KEY (user_id)
);

INSERT INTO tbl_auth_user (user_id, user_password) VALUES ('theadmin', PASSWORD('chumbawamba'));
INSERT INTO tbl_auth_user (user_id, user_password) VALUES ('webmaster', PASSWORD('webmistress'));

We will use the same html code to create login form created in previous example. We will only need to modify the login process a bit. The login script's content is shown below :

<?php
// we must never forget to start the session
session_start();

$errorMessage = '';
if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) {
   include 'library/config.php';
   include 'library/opendb.php';

   $userId = $_POST['txtUserId'];
   $password = $_POST['txtPassword'];

   // check if the user id and password combination exist in database
   $sql = "SELECT user_id
           FROM tbl_auth_user
           WHERE user_id = '$userId'
                 AND user_password = PASSWORD('$password')";

   $result = mysql_query($sql)
             or die('Query failed. ' . mysql_error());

   if (mysql_num_rows($result) == 1) {
      // the user id and password match,
      // set the session
      $_SESSION['db_is_logged_in'] = true;

      // after login we move to the main page
      header('Location: main.php');
      exit;
   } else {
      $errorMessage = 'Sorry, wrong user id / password';
   }

   include 'library/closedb.php';
}
?>

 

// ... same html login form as previous example

Instead of checking the user id and password against a hardcoded info we query the database if these two exist in the database using the SELECT query. If we found a match we set the session variable and move to the main page. Note that the session name is prefixed by 'db_' to make it different than the previous example.

For the next two scripts ( main.php and logout.php ) the code is similar to previous one. The only difference is the session name. Here is the code for these two

<?php
session_start();

// is the one accessing this page logged in or not?
if (!isset($_SESSION['db_is_logged_in'])
   || $_SESSION['db_is_logged_in'] !== true) {

   // not logged in, move to login page
   header('Location: login.php');
   exit;
}

?>

// ... some html code here

 

<?php
session_start();

// if the user is logged in, unset the session
if (isset($_SESSION['db_is_logged_in'])) {
   unset($_SESSION['db_is_logged_in']);
}

// now that the user is logged out,
// go to login page
header('Location: login.php');
?>


Read Full Article
 

Content Management System ( CMS ) using PHP and MySQL

E-mail Print
Current revision posted to MySQL Tutorials by admin on 12/18/2008 8:42:48 PM

A Content Management System ( CMS ) is used to add, edit, and delete content on a website. For a small website, such as this, adding and deleting a page manually is fairly simple. But for a large website with lots of pages like a news website adding a page manually without a content management system can be a headache.

A CMS is meant to ease the process of adding and modifying new content to a webpage. The pages content are stored in database, not in the file server.

This tutorial will present an example of a simple content management system. You will be able to add, edit and delete articles using HTML forms.

For the database table we'll call it the news table. It consist of three columns :

  • id : The article's id
  • title : The title of an article
  • content : The article itself

 

First we need to create a script to add an article. It is just a form where a user can enter the article's title and content.

Example :  

 

<form method="post">
<table width="700" border="0" cellpadding="2" cellspacing="1" align="center">
<tr>
<td width="100">Title</td>
<td><input name="title" type="text"></td>
</tr>
<tr>
<td width="100">Content</td>
<td><textarea name="content" cols="50" rows="10"></textarea></td>
</tr>
<tr>
<td width="100">&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td colspan="2" align="center"><input name="save" type="submit" value="Save Article"></td>
</tr>
</table>
</form>
Whe an article is added the script just insert the article into the database. An article id is automatically generated by MySQL because the id column was created with AUTO_INCREMENT parameter .

<?php
if(isset($_POST['save']))
{
   $title   = $_POST['title'];
   $content = $_POST['content'];

   if(!get_magic_quotes_gpc())
   {
      $title   = addslashes($title);
      $content = addslashes($content);
   }
   include 'library/config.php';
   include 'library/opendb.php';

   $query = " INSERT INTO news (title, content) ".
            " VALUES ('$title', '$content')";
   mysql_query($query) or die('Error ,query failed');

   include 'library/closedb.php';

   echo "Article '$title' added";
}
?>

 

Now that we have the script to add articles let's create another script to view those articles. The script is list the title of articles available in database as clickable links. The article link have the article id appended like this

http://www.php-mysql-tutorial.com/examples/cms/article1.php?id=3

One possible implementation of article1.php is presented below :

Example : 

<?php
include 'library/config.php';
include 'library/opendb.php';

// if no id is specified, list the available articles
if(!isset($_GET['id']))
{
   $self = $_SERVER['PHP_SELF'];

   $query = "SELECT id, title FROM news ORDER BY id";
   $result = mysql_query($query) or die('Error : ' . mysql_error());

   // create the article list
   $content = '<ol>';
   while($row = mysql_fetch_array($result, MYSQL_NUM))
   {
      list($id, $title) = $row;
      $content .= "<li><a href="$self?id=$id">$title</a></li>rn";
   }

   $content .= '</ol>';

   $title = 'Available Articles';
} else {
   // get the article info from database
   $query = "SELECT title, content FROM news WHERE id=".$_GET['id'];
   $result = mysql_query($query) or die('Error : ' . mysql_error());
   $row = mysql_fetch_array($result, MYSQL_ASSOC);

   $title = $row['title'];
   $content = $row['content'];
}

include 'library/closedb.php';
?>

// ... more code here

When article1.php is first called the $_GET['id'] variable is not set and so it will query the database for the article list and save the list in the$content variable as an ordered list. The variable $title and $content will be used later when we print the result page. Take a look at the code below :

Example : 

<?php

// ... previous code

?>
<html>
<head>
<title>
<?php echo $title; ?>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">

// ... some css here to make the page look nicer

</style>
</head>
<body>
<table width="600" border="0" align="center" cellpadding="10" cellspacing="1" bgcolor="#336699">
<tr>
<td bgcolor="#FFFFFF">
<h1 align="center"><?php echo $title; ?></h1>
<?php
echo $content;

// when displaying an article show a link
// to see the article list
if(isset($_GET['id']))
{
?>
<p>&nbsp;</p>
<p align="center"><a href="<?php echo $_SERVER['PHP_SELF']; ?>">Article List</a></p>
<?php
}
?>
</td>
</tr>
</table>
</body>
</html>

If you click on an article link the script will fetch the article's title and content from the database, save it to $title and $content variable and print the HTML file . At the bottom of the page we place a code to show the link to the article list which is the file itself without any query string ( $_SERVER['PHP_SELF'] )

With this implementation each article request involve one database query. For a heavy load website with lots of articles using the above implementation can cause a very high amount of database-request. So we need a better cms solution to reduce the load.

One feasible solution is to implement caching ( cache ) which load an article from the database only once when the article was first requested. The article is then saved to a cache directory as a regular HTML file. Subsequent request to the article will no longer involve any database request. The script just need to read the requested article from the cache directory.

Example : 

<?php
include 'library/config.php';
include 'library/opendb.php';

$cacheDir = dirname(__FILE__) . '/cache/';

if (isset($_GET['id'])) {
   $cacheFile = $cacheDir . '_' . $_GET['id'] . '.html';
} else {
   $cacheFile = $cacheDir . 'index.html';
}

if (file_exists($cacheFile))
{
   header("Content-Type: text/html");
   readfile($cacheFile);
   exit;
}

// ... more code coming

?>

 

First we need to specify the cache directory where all cache files are located. For this example the cache directory is located in the same place as the article2.php script. I mean if article2.php is stored in C:/webroot then the cache dir is in C:/webroot/cache/

The script thent check if the article was already in the cache. An article is saved into the cache directory using a filename generated from it's id. For example if you request the article using a link like this :

http://www.php-mysql-tutorial.com/examples/cms/article2.php?id=3

Then the cache file for the article is

_3.html

This filename is just an underscore ( _ ) followed by the article id. In case article2.php is called like this :

http://www.php-mysql-tutorial.com/examples/cms/article2.php

no id is defined so we make the cache file name as index.html

If the cache file is found , the content is read and printed using readfile() and the script terminate. When the article is not found in the cache then we need to look in the database and get the page content from there.

Example : 

<?php

// ... previous code

if(!isset($_GET['id']))
{
   $self   = $_SERVER['PHP_SELF'];

   $query  = "SELECT id, title FROM news ORDER BY id";
   $result = mysql_query($query) or die('Error : ' . mysql_error());

   $content = '<ol>';
   while($row = mysql_fetch_array($result, MYSQL_NUM))
   {
      list($id, $title) = $row;
      $content .= "<li><a href="$self?id=$id">$title</a></li>rn";
   }

   $content .= '</ol>';

   $title = 'Available Articles';
} else {
   // get the article info from database
   $query  = "SELECT title, content FROM news WHERE id=".$_GET['id'];
   $result = mysql_query($query) or die('Error : ' . mysql_error());
   $row    = mysql_fetch_array($result, MYSQL_ASSOC);

   $title = $row['title'];
   $content = $row['content'];
}

include 'library/closedb.php';

// ... still more code coming

?>

As you can see above the process of fetching the article list and content is the same as article1.php. But before showing the page we have to start output buffering so we can save the content of the generated HTML file.

See the code below. Just before printing the html we callob_start() to activate output buffering. From this point no output is sent from the script to the browser. So in the code example below anything between <html> and </html> tag is not sent to the browser but stored in an internal buffer first.

After the closing html tag we useob_get_contents() to get the buffer content and store int in a temporary variable, $buffer. We then call ob_end_flush() which stop the output buffering ( so the page is now sent to the browser ).

Example :  

<?php

// ... previous code

ob_start();
?>
<html>

// ... same html code as article1.php

</html>
<?php

// get the buffer
$buffer = ob_get_contents();

// end output buffering, the buffer content
// is sent to the client
ob_end_flush();

// now we create the cache file
$fp = fopen($cacheFile, "w");
fwrite($fp, $buffer);
fclose($fp);
?>

 

 

Now that we have the file content we can write the cache file using the filename generated earlier ( using underscore plus the article id ). From now on any request to the article will no longer involve a database query. At least until the article is updated.


Read Full Article
 


Page 2 of 5

Subscribe By Email

Enter your email address:

Delivered by FeedBurner

Translate

Donate

Development & maintainance needs time & money.
With your donation you can help us to keep this project alive
Donate:
  Monthly Monthly
Currency
Amount