MySql General

Add New MySQL User

Print E-mail
MySql General
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

Print E-mail
MySql General
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

Print E-mail
MySql General
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

Print E-mail
MySql General
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
 

Uploading Files To MySQL Database

Print E-mail
MySql General
Current revision posted to MySQL Tutorials by admin on 12/18/2008 8:41:52 PM

Using PHP to upload files into MySQL database sometimes needed by some web application. For instance for storing pdf documents or images to make som kind of online briefcase (like Yahoo briefcase).

For the first step, let's make the table for the upload files. The table will consist of.

  1. id : Unique id for each file
  2. name : File name
  3. type : File content type
  4. size : File size
  5. content : The file itself

 

For column content we'll use BLOB data type. BLOB is a binary large object that can hold a variable amount of data. MySQL have four BLOB data types, they are :

  • TINYBLOB
  • BLOB
  • MEDIUMBLOB
  • LONGBLOB

Since BLOB is limited to store up to 64 kilobytes of data we will use MEDIUMBLOB so we can store larger files ( up to 16 megabytes ).

CREATE TABLE upload (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
type VARCHAR(30) NOT NULL,
size INT NOT NULL,
content MEDIUMBLOB NOT NULL,
PRIMARY KEY(id)
);

Uploading a file to MySQL is a two step process. First you need to upload the file to the server then read the file and insert it to MySQL.

For uploading a file we need a form for the user to enter the file name or browse their computer and select a file. The input type="file" is used for that purpose.

 

Example : upload.php
Source code : upload.phps

<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">

</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>

An upload form must have encytype="multipart/form-data" otherwise it won't work at all. Of course the form method also need to be set to method="post". Also remember to put a hidden input MAX_FILE_SIZE before the file input. It's to restrict the size of files.

After the form is submitted the we need to read the autoglobal $_FILES. In the example above the input name for the file is userfile so the content of $_FILES are like this :

$_FILES['userfile']['name']
The original name of the file on the client machine.

$_FILES['userfile']['type']
The mime type of the file, if the browser provided this information. An example would be "image/gif".

$_FILES['userfile']['size']
The size, in bytes, of the uploaded file.

$_FILES['userfile']['tmp_name']
The temporary filename of the file in which the uploaded file was stored on the server.

$_FILES['userfile']['error']
The error code associated with this file upload. ['error'] was added in PHP 4.2.0


Example : upload.php 

 

<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName  = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];

$fp      = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);

if(!get_magic_quotes_gpc())
{
    $fileName = addslashes($fileName);
}

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

$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";

mysql_query($query) or die('Error, query failed');
include 'library/closedb.php';

echo "<br>File $fileName uploaded<br>";
}
?>

Before you do anything with the uploaded file. You should not assume that the file was uploaded successfully to the server. Always check to see if the file was successfully uploaded by looking at the file size. If it's larger than zero byte then we can assume that the file is uploaded successfully.

PHP saves the uploaded file with a temporary name and save the name in $_FILES['userfile']['tmp_name']. Our next job is to read the content of this file and insert the content to database. Always make sure that you use addslashes() to escape the content. Using addslashes() to the file name is also recommended because you never know what the file name would be.

That's it now you can upload your files to MySQL. Now it's time to write the script to download those files.

 

 

Downloading Files From MySQL Database

When we upload a file to database we also save the file type and length. These were not needed for uploading the files but is needed for downloading the files from the database.

The download page list the file names stored in database. The names are printed as a url. The url would look like download.php?id=3. To see a working example click here. I saved several images in my database, you can try downloading them.

Example :  

<html>
<head>
<title>Download File From MySQL</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

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

$query = "SELECT id, name FROM upload";
$result = mysql_query($query) or die('Error, query failed');
if(mysql_num_rows($result) == 0)
{
echo "Database is empty <br>";
}
else
{
while(list($id, $name) = mysql_fetch_array($result))
{
?>
<a href="download.php?id=<?php=$id;?>"><?php=$name;?></a> <br>
<?php
}
}
include 'library/closedb.php';
?>
</body>
</html>

 

When you click the download link, the $_GET['id'] will be set. We can use this id to identify which files to get from the database. Below is the code for downloading files from MySQL Database.

Example :  

<?php
if(isset($_GET['id']))
{
// if id is set then get the file with the id from database

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

$id    = $_GET['id'];
$query = "SELECT name, type, size, content " .
         "FROM upload WHERE id = '$id'";


$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) =                                  mysql_fetch_array($result);

header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;

include 'library/closedb.php';
exit;
}

?>

Before sending the file content using echo first we need to set several headers. They are :

  1. header("Content-length: $size")
    This header tells the browser how large the file is. Some browser need it to be able to download the file properly. Anyway it's a good manner telling how big the file is. That way anyone who download the file can predict how long the download will take.
  2. header("Content-type: $type")
    This header tells the browser what kind of file it tries to download.
  3. header("Content-Disposition: attachment; filename=$name");
    Tells the browser to save this downloaded file under the specified name. If you don't send this header the browser will try to save the file using the script's name (download.php).

After sending the file the script stops executing by calling exit.

NOTE :
When sending headers the most common error message you will see is something like this :

Warning: Cannot modify header information - headers already sent by (output started at C:Webrootlibraryconfig.php:7) in C:Webrootdownload.php on line 13

This error happens because some data was already sent before we send the header. As for the error message above it happens because i "accidentally" add one space right after the PHP closing tag ( ?> )  in config.php file. So if you see this error message when you're sending a header just make sure you don't have any data sent before calling header(). Check the file mentioned in the error message and go to the line number specified


Read Full Article
 
« StartPrev1234NextEnd »

Page 2 of 4

Subscribe By Email

Enter your email address:

Delivered by FeedBurner

Donate

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

Translate

Earn For Skills

Copyright @ 2010 | Tutorialsforu.info | Developed by Open Source Coders | Add your link.