MySQL


Most interactive websites nowadays require data to be presented dynamically and interactively based on input from the user. For example, a customer may need to log into a retail website to check his purchasing history. In this instance, the website would have stored two types of data in order for the customer to perform the check – the customer’s personal login details; and the customer’s purchased items. This data can be stored in two types of storage – flat files or databases.

Flat files are only feasible in very low to low volume websites as flat files have 3 inherent weaknesses:

  1. The inability to index the data. This makes it necessary to potentially read ALL the data sequentially. This is a major problem if there are a lot of records in the flat file because the time required to read the flat file is proportionate to the number of records in the flat file.
  2. The inability to efficiently control access by users to the data
  3. The inefficient storage of the data. In most cases, the data would not be encrypted or compressed as this would exacerbate the problem no. 1 above

The alternative which is, in my opinion, the only feasible method, is to store the data in a database. One of the most prevalent databases in use is MySQL. Data that is stored in a database can easily be indexed, managed and stored efficiently. Besides that, most databases also provide a suite of accompanying utilities that allow the database administrator to maintain the database – for example, backup and restore, etc.

Websites scripted using PHP are very well suited for the MySQL database as PHP has a custom and integrated MySQL module that communicates very efficiently with MySQL. PHP can also communicate with MySQL through the standard ODBC as MySQL is ODBC-compliant, However, this will not be as efficient as using the custom MySQL module for PHP.

The rest of this article is a tutorial on how to use PHP to:

  1. Connect to a MySQL database
  2. Execute standard SQL statements against the MySQL database

Starting a Session with MySQL

Before the PHP script can communicate with the database to query, insert or update the database, the PHP script will first need to connect to the MySQL server and specify which database in the MySQL server to operate on.

The mysql_connect() and mysql_select_db() functions are provided for this purpose. In order to connect to the MySQL server, the server name/address; a username; and a valid password is required. Once a connection is successful, the database needs to be specified.

The following 2 code excerpts illustrate how to perform the server connection and database selection:

@mysql_connect("[servername]", "[username]", "[password]") or die("Cannot connect to DB!");

@mysql_select_db("[databasename]") or die("Cannot select DB!");

The @ operator is used to suppress any error messages that mysql_connect() and mysql_select_db() functions may produce if an error occurred. The die() function is used to end the script execution and display a custom error message.

Executing SQL Statements against a MySQL database

Once the connection and database selection is successfully performed, the PHP script can now proceed to operate on the database using standard SQL statements. The mysql_query() function is used for executing standard SQL statements against the database. In the following example, the PHP script queries a table called tbl_login in the previously selected database to determine if a username/password pair provided by the user is valid.

Assumption:

The tbl_login table has 3 columns named login, password, last_logged_in. The last_logged_in column stores the time that the user last logged into the system.

// The $username and $passwd variable should rightly be set by the login form
// through the POST method. For the purpose of this example, we’re manually coding it.
$username = “john”;
$passwd = “mypassword”;

// We generate a SELECT SQL statement for execution.
$sql="SELECT * FROM tbl_login WHERE login = '".$username."' AND password = '".$passwd."'";

// Execute the SQL statement against the currently selected database.
// The results will be stored in the $r variable.
$r = mysql_query($sql);

// After the mysql_query() command executes, the $r variable is examined to
// determine of the mysql_query() was successfully executed.
if(!$r) {
    $err=mysql_error();
    print $err;
    exit();
}

// If everything went well, check if the query returned a result – i.e. if the username/password
// pair was found in the database. The mysql_affected_rows() function is used for this purpose.
// mysql_affected_rows() will return the number of rows in the database table that was affected
// by the last query
if(mysql_affected_rows()==0){
    print "Username/password pair is invalid. Please try again.";
}
else {

// If successful, read out the last logged in time into a $last variable for display to the user
    $row=mysql_fetch_array($r);
    $last=$row["last_logged_in"];
    print “Login successful. You last logged in at ”.$last.”.”;

}

The above example demonstrated how a SELECT SQL statement is executed against the selected database. The same method is used to execute other SQL statements (e.g. UPDATE, INSERT, DELETE, etc.) against the database using the mysql_query() and mysql_affected_rows() functions.

About The Author

This PHP scripting article is written by John L. John L is the Webmaster of The Ultimate BMW Blog! (http://www.bimmercenter.com).

The Ultimate BMW Blog!

daboss@bimmercenter.com

One of the great promises that actually came true when our Internet-enabled world reached the twenty-first century is efficient customer-to-business interaction. Each day, I find a new way to go through life’s errands without ever waiting on hold for a bank teller, a pharmacist, or an insurance agent. I do it all online.

Internet savvy consumers are coming to expect such web empowerment. And while these information transactions usually require some sort of private data traveling the ether, you, as the webmaster, bear the burden of keeping that data away from those who have no right to it.

Since retina scans and brain wave signatures are still properties of James Bond flicks, we’re stuck using plain old boring passwords.

Is this really secure?

Let’s get this out of the way first. The only truly secure computer is one that’s unplugged. Kind of like “the only safe car is the one that sits in your garage.” Life is a risk/reward proposition and, let’s face it, this (probably) isn’t Fort Knox, we’re securing.

The security measures listed here are suitable for garden-variety data. I’ve used these schemes to write back-end website administration pages for online shopping carts. I’ve used them to write “partner” pages where retailers can download ads and sales data from wholesalers. I wouldn’t use them to secure credit card numbers, social security numbers, or nuclear launch codes.

So what are PHP, MySQL, and session variables?

PHP is a programming language used (in this case) to write HTML. MySQL is a database. Session variable are used by web servers to track information from one page on a domain to another. This article isn’t a how-to for either technology. If you aren’t very comfortable with them, you could just copy and paste the code samples in this article and build yourself a basic password protected website. You could also just read the Cliff’s notes for Pride and Prejudice and get a C+ in literature class. Your choice.

Let’s get started with sessions

It’s often been said that the web is “stateless”, meaning that each web page is entirely independent, needing no other page to exist, and taking no information from the previous page. This is great for anonymous surfing from one site to the next, but it stinks for password protection. Consumers want password protected information, but they don’t want to enter their password on every page. So we turn to our web server to keep track of a user while he’s on our site.

Ex. 1.

<?php

session_start();

?>

<!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”" xml:lang=”en” lang=”en”>

<head><title>Dan McConkey’s Free Web Marketing Guide</title></head>

<body>

<p>Dan McConkey’s Free Web Marketing Guide</p>

</body>

</html>

end Ex. 1

session_start() is a PHP function that looks to see if a session has already been started then does one of two things:

1. If a session has been started, it does nothing.

2. If a session has not been started, it begins one.

It is important to note that session_start() must occur before any other PHP on the page, if you want it to work. Begin every password-protected page with it. Validation

Now let’s think basic validation. What sorts of things do we need to accomplish?

* First, we need to check to see if the user has already logged in, so we don’t ask for a password on every page. If our user has already logged in, we pass him or her through to the secure content.

* If the user hasn’t already logged in, we need him or her to do so. So we need to write a log-in form.

* We need next to compare log-in form results with a known list of usernames and passwords. If the user checks out, we pass him or her along to the secure content.

* If the user doesn’t check out, we direct him or her back to the log-in screen.

* Lastly, we need to provide the user the ability to log out.

So let’s start with a basic frame-work that we’ll fill in later.

Ex. 2

<?php

// start session if not already started

session_start();

// check to see if user just logged out

if ( $log_out )

{

}

function write_log_in( $text )

{

} // end write_log_in function

function verify()

{

// check to see if they’re already logged in

// if yes, return true

// if no, check to see if visitor has just tried to log on

// if yes, verify password

// if it worked, return true

// if it didn’t, send them back to log-in

// if the user didn’t just log-in, (s)he needs to

} // end verify function

?>

<!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”" xml:lang=”en” lang=”en”>

<head><title>Dan McConkey’s Free Web Marketing Guide</title></head>

<body>

<p>Dan McConkey’s Free Web Marketing Guide</p>

<?php

// check for valid user

if ( verify() )

{

// begin secure content

echo “<p>Clatu, verata, nicto</p>”;

// end secure content

} // end if ( verify() )

?>

</body>

</html>

End Ex. 2

As I said, this is just a frame-work. I like to start all my projects this way. It allows me to get a grand view of what I’m doing before getting mired down in the details.

Basically, so far, all we’ve done is place some secret content inside an if statement. If the user is valid, we show the content, if not, we don’t. Writing a log-in form

The first thing we should flesh out is our log-in function. This is a basic form, with no bells and whistles, so it should be pretty straight forward.

Ex 3

function write_log_in( $text )

{

echo ”

<p>$text</p>

<form method=’post’ action=”>

<p>User ID: <input type=’text’ name=’user_name /></p>

<p>Password: <input type=’password’ name=’password’ /></p>

<p><input type=’submit’ value=’Log In’></p>

</form>

“;

} // end write_log_in function

End Ex. 3

No problems, right? All this is is PHP writing a basic HTML log-in form. Two things are worth noting:

1. The method attribute to the <form> tag is ‘post’. We could have used ‘get’, but that would add our user name and password to the URL as varibles. ie our_url?user_name=bob&password=truck64 . This shows the password–in plain text– right there in the URL. Why spend all this time on security if you’re just going to put peoples’ passwords out for display?

‘post’ is much more secure, forcing the server to keep track of form data, rather that the URL. Any time you can keep information out of the URL, you’re one step closer to a secure web page.

2. Next you want to look at the action attribute to the <form> tag. Leaving it blank tells the server that you plan to process these form results with this same page.

Checking the log-in values

Now let’s flesh out our frame-work a little more.

Ex. 4

<?php

// start session if not already started

session_start();

// check to see if user just logged out

if ( $log_out )

{

}

function write_log_in( $text )

{

} // end write_log_in function

function verify()

{

// check to see if they’re already logged in

// if yes, return true

// check to see if visitor has just tried to log on

$user_name = $_POST["user_name"];

$password = $_POST["password"];

if ( $user_name && $password )

{

// verify password and log in to database

$db = mysql_pconnect( “localhost”, “$user_name”, “$password” );

if ( $db )

{

// register session variable and exit the verify function

$valid_user = $user_name;

$_SESSION['valid_user'] = $valid_user;

return true;

}

else

{

// bad user and password

$text = “User Name and Password did not match”;

write_log_in( $text );

}

}

else

{

// if the user didn’t just log-in, (s)he needs to

}

} // end verify function

?>

<!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”" xml:lang=”en” lang=”en”>

<head><title>Dan McConkey’s Free Web Marketing Guide</title></head>

<body>

<p>Dan McConkey’s Free Web Marketing Guide</p>

<?php

// check for valid user

if ( verify() )

{

// begin secure content

echo “<p>Clatu, verata, nicto</p>”;

// end secure content

} // end if ( verify() )

?>

</body>

</html>

End Ex. 4

First, we’ll check whether the user has just tried to log in.

$_POST is a PHP superglobal array that keeps track of data sent to a page via a <form method=’post’> tag. In the log-in function, we named our inputs user_name and password, so we can access the user input by calling $_POST["user_name"] and $_POST["password"].

We next run an if ( $user_name && $password ) statement to see if both $_POST["user_name"] and $_POST["password"] hold values. If they do, the user just tried to log in.

Our next section of code is the part that actually checks whether the user name and password are correct. Here, we use MySQL’s User table (part of the mysql database) to keep track of our users. This is, perhaps, the best route, as MySQL is already set up to control access permissions. However, this can present problems when you want to keep the database connection open across pages. Also, some hosting companies won’t give you grant access (let you make new users) to the mysql database.

In those cases, you can accomplish much the same thing by setting up your own users table in your database. You would then need to write an SQL query that compares user names and passwords. That would look something like this:

Ex. 5

$select = “select user_name from users

where user_name=’$user_name’

and password=PASSWORD( ‘$password’ )”;

$query = mysql_query( $select );

if ( mysql_num_rows( $query ) == 1 )

{

// validated user and password

End Ex 5

Getting back to our validation using MySQL’s built in features, we know that the user name and password checked out because the connection attempt returned true.

Registering a session variable

Now that we know our user name and password check out, we need to store that information and allow our user to continue surfing our protected area without logging in each and every page. Looking back at example four, we notice another of PHP’s superglobal variables: $_SESSION.

$_SESSION is an array that holds all of our session variables. By setting the valid_user session variable, we can later make a call to ession_is_registered( “valid_user” ) to see if our user has already logged in successfully.

Logging out

The last thing we have to attend to is allowing our users to log out of our system. In this case, we’ve used a simple link inside our protected area.

Ex 6

<?php

// start session if not already started

session_start();

// check to see if user just logged out

if ( $log_out )

{

session_unregister( “valid_user” );

session_destroy();

session_start();

}

function write_log_in( $text )

{

} // end write_log_in function

function verify()

{

} // end verify function

?>

<!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”" xml:lang=”en” lang=”en”>

<head><title>Dan McConkey’s Free Web Marketing Guide</title></head>

<body>

<p>Dan McConkey’s Free Web Marketing Guide</p>

<?php

// check for valid user

if ( verify() )

{

echo “<p><a href=’?log_out=1′>Log out</a></p>”;

// begin secure content

echo “<p>Clatu, verata, nicto</p>”;

End Ex 6

First, looking in the HTML body, we see a simple HTML link that adds a variable to the URL. In this case, the variable name is log_out and its value is 1. We use 1 as a value because it’s easy to store in a URL, but really any value greater than zero will work.

Once we pass a log-out request to the page, we need to process it. That’s what the if( $log_out) part is for.

The if statement checks if a log-out request was passed. Once it sees that one was, it unregisters the valid_user session variable, then it destroys the session entirely.

Ironically, it starts a new session right back up. That’s in case the user decides to log in later (without closing the browser window), or log in as a different user. The final code

Putting it all together we get this:

Ex. 7

<?php

// start session if not already started

session_start();

// check to see if user just logged out

if ( $log_out )

{

session_unregister( “valid_user” );

session_destroy();

session_start();

}

function write_log_in( $text )

{

echo ”

<p>$text</p>

<form method=’post’ action=”>

<p>User ID: <input type=’text’ name=’user_name /></p>

<p>Password: <input type=’password’ name=’password’ /></p>

<p><input type=’submit’ value=’Log In’></p>

</form>

“;

} // end write_log_in function

function verify()

{

// check to see if they’re already logged in

if ( session_is_registered( “valid_user” ) ) return true;

// check to see if visitor has just tried to log on

$user_name = $_POST["user_name"];

$password = $_POST["password"];

if ( $user_name && $password )

{

// verify password and log in to database

$db = mysql_pconnect( “localhost”, “$user_name”, “$password” );

if ( $db )

{

// register session variable and exit the verify function

$valid_user = $user_name;

$_SESSION['valid_user'] = $valid_user;

return true;

}

else

{

// bad user and password

$text = “User Name and Password did not match”;

write_log_in( $text );

}

}

else

{

// user must log in

$text = “This is a secure server. Please log in.”;

write_log_in( $text );

}

} // end verify function

?>

<!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”" xml:lang=”en” lang=”en”>

<head><title>Dan McConkey’s Free Web Marketing Guide</title></head>

<body>

<p>Dan McConkey’s Free Web Marketing Guide</p>

<?php

// check for valid user

if ( verify() )

{

echo “<p><a href=’?log_out=1′>Log out</a></p>”;

// begin secure content

echo “<p>Clatu, verata, nicto</p>”;

// end secure content

} // end if ( verify() )

?>

</body>

</html>

End Ex. 7

That’s a pretty hefty code block to put at the head of every web page. Typically, I would put my verify() and write_log_in()functions into a seperate file and reference them with an include() function. That provides the added benifit of updating your entire website by editing one file only.

Hope that helps.

Copyright (C) 2005 Dan McConkey

About The Author

Dan McConkey is a freelance web marketing professional, working in and around Charlotte, NC. In the web, Dan has found an amazing potential for lead generation for businesses. Using traditional advertising theories, appropriate technologies, and a little common sense, your electronic marketing campaigns can easily be your most effective.

Dan maintains Dan McConkey’s Free Web Marketing Guide at http://www.dmcconkey.com

dmcconkey@yahoo.com

Many of site owners still don’t realize all advantages of database driven web sites and don’t use all abilities they give. So when do you need a database driven web site and how it will make your web-life better?

What is a database driven web site?

Database driven web site is one that uses database for collecting and storing information. What information it can be? Various. Email addresses, contact info, clients list, products list, listings of real estate property, trade offers, images, and links, etc.

How does it work?

For example, you have a static HTML web site for your business with posted information about the company, products or services, clients, and there is contact form.

If you have strong HTML skills you update your site without problems each time you need it. Otherwise you hire a webmaster or use maintenance services of a web design company. You write info in text document, send it to your webmaster, he manually inserts it to the site.

You store your products, clients, and contacts info in Word or Excel files.

Probably you store emails that you receive from contact form in Word or Excel files. Is it handful and easy? Is there an alternative?

In the database driven web site all information is stored in table format of databases on the server, script generates pages that are showed on the site as usual HTML ones.

Usually database driven web sites have admin panel with user-friendly interface where you can manage the site content, i.e. add, edit, or delete info by yourself, create new pages or delete old ones. You can update your site easily each time you need it.

Requests sent form contact form can be saved in database for further use, you can edit them, group, and sort.

You can create pictures gallery on your site and update it easily.

You can have news box at your site and update it easily each time you need it.

Is it expensive?

No, if you order the site from a web design/development company that has good experience in database driven web sites design that means elaborated and tested development process, time and cost saving methods which give high-quality work within short timeline and at affordable price.

Ask your web design company do they make database driven web sites, if yes, look at the examples of such previous works, ask references of the customers – are they satisfied with their web sites? – and if the price is acceptable move forward to your new web site. Or search for another web development company using the same criteria for choice.

What else you should know?

Probably, you will need to change hosting plan or even hosting provider to host your new database driven web site. Usually there are such requirements for hosing:

· Must support PHP/MySQL or ASP/MSSQL
· At least 75-100 Mb of disk space
· Must have Database Client
· Must have Mail server

About The Author

Julia Ramyalg
Marketing Director of IT-Inventors – professional offshore web site design and development company
http://www.it-inventors.com

Visit our site to order Affordable database driven web site design – clients database, online gallery, online albums, news, newsletters, products and services listings, and more.

Prices start from $50

julia@it-inventors.com

What is SQL? SQL stands for Structured Query Language and is the lingua franca in the database world. SQL is a standard that is used by all database vendors and programmers to define, extract and access the information that is stored in databases. SQL began life as an IBM creation but was standardized by the American National Standards Institute (ANSI) and the International Organization for Standardization (ISO) as ANSI/ISO SQL in 1988. Since then ANSI/ISO SQL standard continued to evolve. The ANSI-SQL group has since published three standards over the years:

  1. SQL89 (SQL1)
  2. SQL92 (SQL2)
  3. SQL99 (SQL3)

SQL is a query language. It is English-like and easy to use. However, although there are more than 90 SQL reserved words, most programmers seldom use more than the following handful of commands – SELECT, INSERT, UPDATE, DELETE, FROM, WHERE, HAVING, BETWEEN, LIKE, OR, AND, NOT, IN, ORDER, GROUP and BY.

For example, if you had a database table named “employees” and you wanted to retrieve all records where the employee has the last name “goodman”, you would use the following SQL statement:

SELECT * FROM employees WHERE lastname = 'goodman';

There are many different categories of SQL statements but the basic ones which all programmers should be familiar with are the SQL statements that:

  1. Create tables and manipulate their definitions
  2. Query the table data
  3. Manipulate the table data

SQL is predominantly used by 2 types of users – programs and humans (keying in the commands through a database client) – to pass instructions to databases. SQL commands can be keyed into a database client like the MySQL Query Browser or the SQL Server Enterprise Manager and executed to either return a result or modify records in the database. SQL can also be used in conjunction with programming language or scripting language like Microsoft Visual Basic or PHP to communicate with the database.

Although SQL is a world standard, it is unfortunate that most database vendors have come up with different dialects and variations. This is because every database vendor wants to differentiate their database products from the crowd. One good example is Microsoft SQL Server’s TRANSACT-SQL. TRANSACT-SQL is a superset of SQL and is designed for use only with Microsoft SQL Server. Although it does make programming much easier for software developers, it is not compliant with other databases like Oracle or MySQL – making TRANSACT-SQL programs non database-portable. As such, although many of these features are powerful and robust, it is good practice to exercise caution and limit your SQL use to be compliant with the ANSI/ISO SQL standards and ODBC-Compliant.

Courtesty of SQLPrimer.comhttp://www.sqlprimer.com.

About The Author

John L

For more information, please contact the Webmaster of SQLPrimer.comhttp://www.sqlprimer.com.

editor@sqlprimer.com

 

PIM Team Case Study

This article could be very usefull for the owers of web service businesses. If you are offering e-commerse, hosting, live support or ticketing web based services you have probably met the discussed problem many times in your work. My intend with this article is to help you solving this trouble and save your valued time.

Supporting multiple instanses of a web based application can be very time consuming and frustrating, especially if the app is in development stage or is being updated often. Here in PIM Team we met such a problem, trying to perform constant upgrades on an application running simultanteously on about 50 different domains.

Problem You know, if you make just one change and don’t transfer it on the other instanses it can cause big errors and stop your scripts from working. But (as in our case) opening 50 control panels and going to the MySQL administration and running manually these ALTER TABLE or CREATE TABLE statements was a cumbersome task, taking all of our time.

Solution All the instances of our app were running on one physical server, which definitely was a facilitation. But you can implement similar solution even if your ap is running on different servers – you just need to allow connection to the master host – the one which will run the Synhronizer – the script i will describe below. Our Synchronizer is actually a simple PHP script which is started manually and have one only purpose – to synchronize all 50 databases with one “master” database. In our case we needed that script to synchronize only the DB structure, but not the content. But if you understand the simple logic of the script, you can easy extend it to copy/synchronize your content if this is you case.

Implementation First, you need to select all the tables and their fields from the master database:

//select tables from the master $q=”SHOW TABLES FROM master_database”; $tabs=$DB->aq($q); //$DB is a database fetching object, you can use the built PHP functions to select from mysql if you prefer

$tables=array();

foreach($tabs as $tab) { //select fields $q=”SHOW FIELDS FROM $tab[0]“; $fields=$DB->aq($q); array_push($tables,array(“name”=>$tab[0],”fields”=>$fields)); }

You see how our script fills an array $tables with all the table names and itself containing another array – with the table fields.

Secondly, you need a list with the databases or domains where the instances of the synchronized application are running. Once having that list, you can browse thru it with “foreach” or another cycle.

Now we are going to select all the tables in the database on each target domain. (Of course you need to connect to its database, and disconnect from master one! We already did our job in selecting the tables from the master database :)

In the same way as above, you need to select the tables from the target domain. Then below, just compare the tables:

foreach($tables as $table) //browse thru master tables { $found=false; foreach($dtables as $dtable) { if($dtable[name]==$table[name]) $found=$dtable; } if(is_array($found)) { //table exists, check fields foreach($table[fields] as $field) { $ffound=false; foreach($found[fields] as $dfield) { if($field[Field]==$dfield[Field]) $ffound=true; } if(!$ffound) { //alter table add field if($field[Key]=='PRI') $primary=" PRIMARY KEY "; else $primary=''; $q="ALTER TABLE `$table[name]` ADD `$field[Field]` $field[Type] NOT NULL $field[Extra] $primary"; $DB->q($q); } } else { //table does not exists, create $q="CREATE TABLE `$table[name]`("; foreach($table[fields] as $cnt=>$field) { if($field[Key]=='PRI') $primary=" PRIMARY KEY "; else $primary=''; $q.="`$field[Field]` $field[Type] NOT NULL $field[Extra] $primary "; if($cnt<(sizeof($table[fields])-1)) $q.=", "; } $q.=")"; $DB->q($q); } } }

And that’s all! You may need to work a little on this code, but the logic is here provided for your needs. Feel free to use the ideas for your own applications.

admin@pimteam.net
Author’s URL:
Bobby Handzhiev is software developer and manager of PIM Team Bulgaria.
PHP Calendar Scripts
High Yield Weekly Digest

If you’ve been using MySQL database to store your important data, it is imperative that you make a backup of your data to prevent any loss of data. This article shows you how to backup and restore data in your MySQL database. This process can also be used if you have to move your data to a new server.

Backing up your database

The quickest and easiest way to backup and restore your database would be to use MySQLDump. If you’ve got shell or telnet access to your server, you can backup MySQL data by issuing the mysqldump command. The syntax for the command is as follows.

mysqldump -u [uname] -p [pass] [dbname] > [backupfile.sql] [uname] – this is your database username [pass]- this is the password for your database [dbname] – the name of your database [backupfile.sql] – the filename for your database backup

To backup your database ‘Customers’ with the username ’sadmin’ and password ‘pass21′ to a file custback.sql, you would issue the command

mysqldump -u sadmin -p pass21 Customers > custback.sql

Issuing this command will backup the database to custback.sql. This file can be copied to a safe location or a backup media and stored. For more information on MySQLDump, you can check out : http://www.mysql.com/doc/en/mysqldump.html

Restoring your database

If you have to re-build your database from scratch, you can easily restore the mysqldump file by issuing the following command. This method will not work if the tables already exist in your database.

mysql – u sadmin -p pass21 Customers < custback.sql

If you need to restore existing databases, you’ll need to use MySQLImport. The syntax for mysqlimport is

mysqlimport [options] database textfile1

To restore your previously created custback.sql dump back to your Customers Database, you’d issue

mysqlimport -u sadmin -p pass21 Customers custback.sql

For more information on MySQLImport, you can check out : http://www.mysql.com/doc/en/mysqlimport.html

About The Author

Vinu Thomas is a consultant on Webdesign and Internet Technologies. His website is http://www.vinuthomas.com. You can discuss about this article or any PHP/MYSQL related issues in our Discussion Forums: http://www.vinuthomas.com/forum2.html