<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Webcodez - The database of web programming tutorials &#187; MySql</title>
	<atom:link href="http://www.webcodez.net/tag/mysql/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.webcodez.net</link>
	<description>Archive of tutorials on php,mysql,Javascript,html,css and other coding languages as well as code-snippets.</description>
	<lastBuildDate>Tue, 18 May 2010 16:43:49 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>PHP Tutorials &#8211; The Roundup</title>
		<link>http://www.webcodez.net/php-mysql/php-tutorials-the-roundup/</link>
		<comments>http://www.webcodez.net/php-mysql/php-tutorials-the-roundup/#comments</comments>
		<pubDate>Tue, 18 May 2010 16:11:58 +0000</pubDate>
		<dc:creator>antiSigma</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[basics]]></category>
		<category><![CDATA[fundamentals]]></category>
		<category><![CDATA[MySql]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[php simple]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/php-mysql/php-tutorials-the-roundup/</guid>
		<description><![CDATA[In this article I will speak about PHP programming language and try  to make it clear for every newbie which wants to start learning php.  But, for beeing able to start learning this computer programming  language, you should start by understand what is this and what is doing.
Well, PHP is a server-side [...]]]></description>
			<content:encoded><![CDATA[<p>In this article I will speak about PHP programming language and try  to make it clear for every newbie which wants to start learning php.  But, for beeing able to start learning this computer programming  language, you should start by understand what is this and what is doing.</p>
<p>Well, PHP is a server-side programming language : server-side? means  that the code is interpreted at level of the PHP engine installed on the  web server. PHP is open-source (free at no cost). Beeing free of charge  makes it very popular and I would say easy to use.</p>
<p>Where can be used php? Everywhere on the web, and I think desktop  application can be coded too with the GTK feature but I dont know much  about it so I will stop here talking about this. On the other side, for  the web application development, you can build dynamic websites,  database driven websites (for example MySQL, PostreSQL, etc.), diverse  web forms like a contact form which will insert the infos into database  system or send details entered in the form to a specified email address,  etc.</p>
<p>How do you start the ball rolling? Well, please start reading  introductory tutorials on php official website, then get a project in  mind and try finding requirements needed for this project. This is the  best way to learn : by practicing, not just reading tons of borring  tutorials.</p>
<p>Once you got a project in mind, you will definitely need a php engine to  be able to execute the code. How do you make this? Simply install a  webserver like apache, add php server to this and mysql database engine.  You&#8217;ll find a lot of documentation to help you doing this or there are a  lot of ready made packs wich includes, php, apache, phpmyadmin, mysql,  etc for example easyphp web server or xampp. They&#8217;re free and easy to  install.</p>
<p>The second thing is to register at specific forums, where you can get  support and help from the php gurus, because you really need fast help  when errors will occure, and by the way, trust me you&#8217;ll encounter a lot  of &#8220;strange&#8221; errors at the begining, which later will become just a  routine.</p>
<p>And lastly, do not forget to get a nice code editor with code colloring,  code auto-completion feature is very important too which will make  developing faster. My tip here is to use Zend IDE (the php company)  which is the best and includes mentioned features. Also, Adobe  Dreamweaver is not bad, you can use that too which is nice for html/css  client side scripting. I assumed that you already know html at least, it  is very recommended to know it to make things clear in programming.</p>
<p>And, for the begining this should be enough for a novice to begin to  learn php programming language at the basic level. Later, with the time  and projects which are mandatory for progress, you&#8217;ll get experience and  will advance maybe to OOP (object oriented programming) which is  another thing important.<br />
Good luck in learning!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/php-tutorials-the-roundup/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Users Online ( Part 1 &amp; Part 2 )</title>
		<link>http://www.webcodez.net/php-mysql/users-online-part-1-part-2/</link>
		<comments>http://www.webcodez.net/php-mysql/users-online-part-1-part-2/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 14:56:24 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[if loop]]></category>
		<category><![CDATA[MySql]]></category>
		<category><![CDATA[net script]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[users online]]></category>
		<category><![CDATA[variables]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=182</guid>
		<description><![CDATA[Part 1
In this tutorial we&#8217;ll be creating a users online system which shows the current users online on a certain page. This can be done either by using files to save the data in or database. We&#8217;ll be using the second method to save the user online data: a database ( -table ). So let&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Part 1</strong></p>
<p>In this tutorial we&#8217;ll be creating a users online system which shows the current users online on a certain page. This can be done either by using files to save the data in or database. We&#8217;ll be using the second method to save the user online data: a database ( -table ). So let&#8217;s start by creating the database and table that will contain the users online data. In this example we call the database &#8216;test&#8217; and the table &#8216;online&#8217; &#8211; this table will require the following fields:</p>
<p>    * timestamp &#8211; the time in seconds &#8211; counted from UNIX timestamp &#8211; when the user viewed the page<br />
    * IP &#8211; the IP of the user that&#8217;s online<br />
    * username &#8211; the username of the user if logged in ( otherwise: guest )<br />
    * location &#8211; the page the user is viewing<br />
    * loc_title &#8211; the name of the page the user is viewing</p>
<p>You can create them manually or use this SQL (import):</p>
<pre name="code" class="php:nogutter">
CREATE TABLE IF NOT EXISTS `online` (
  `timestamp` int(250) NOT NULL,
  `IP` varchar(50) NOT NULL,
  `username` varchar(15) NOT NULL,
  `location` varchar(250) NOT NULL,
  `loc_title` varchar(25) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
</pre>
<p>Now what we basicly need to do, is add a row to this table each time a user views a page and delete rows that are old ( say from 5 minutes ago ). Then we only show the users that got atleast one row remaining in the &#8216;online&#8217; table ( unique IP, so it only counts the same user ( same IP ) once ). Therefor we need to set a few variables:</p>
<pre name="code" class="php:nogutter">
&lt;?php

session_start(); //if needed to use sessions

$time = timestamp(); //current timestmap

$timeout = "3000"; //timeout in seconds, 5 min taken as example

$out = $time-$timeout; //all user logs/views from earlier than  this will be removed

?>
</pre>
<p>We set a variable $time containing the current timestamp in seconds using the function timestamp. Then we set the variable $timeout to an amount of seconds ( 3000 in this example = 5 min. ) and create a variable $out which contains the current timestamp ( $time ) minus the timeout in seconds ( $timeout ). So in this case it contains the timestamp of 5 minutes ago. We&#8217;ll use this to delete all user rows that were created earlier than 5 minutes ago. So we only will keep the users that have still been active in the last 5 minutes. We&#8217;ll use a simple mysql query to do this:</p>
<pre name="code" class="php:nogutter">
"DELETE online WHERE timestamp < '$out' "
</pre>
<p>We use the DELETE query type to delete the rows of the table 'online'. But only the ones ( WHERE ) with a timestamp smaller than the timestamp in $out ( timestamp < $out ). Which is equal to the timestamp 5 minutes ago. We'll need to make a host and database connection first using mysql_connect and mysql_select_db. Then we'll use mysql_query function to execute our query.</p>
<pre name="code" class="php:nogutter">
mysql_connect("localhost", "root"); //host, user(, password)
mysql_select_db("test");

mysql_query("DELETE online WHERE timestamp < '$out' ");
</pre>
<p>Ok so now we know all rows in the table 'online' are from IPs (users) that still have been active in the last 5 minutes ( the timestamp of the rows/userlogs is > timestamp 5 minutes ago ). Now we'll add a row for the user that is currently viewing this page. We'll use a simple INSERT query for this but first we'll need to set the user IP and username. Define it how you want to. We'll take for example that $_SESSION['username'] contains the username of a LOGGED IN user. So we check if it's there, if not: user default 'guest' username.</p>
<pre name="code" class="php:nogutter">
if($_SESSION['username'] AND !empty($_SESSION['username'])) {

     $username = $_SESSION['username']; //username is the username of user logged in

}else{

     $username = "guest"; //not logged in, so guest

}
</pre>
<p>The IP of the user is stored inside the SERVER array - variable 'REMOTE_ADDR':</p>
<pre name="code" class="php:nogutter">

$IP = $_SERVER['REMOTE_ADDR']; //= user IP
</pre>
<p>Now only last are the location url and name. The location we can simply set to $_SERVER['PHP_SELF'], as used in other tutorials as well. This contains a simple path to the current file been viewed. The location name you can set to anything like: "Homepage", depending on what page you insert this code.</p>
<p>So now we've defined all variables needed to add a new user online log:</p>
<pre name="code" class="php:nogutter">

if($_SESSION['username'] AND !empty($_SESSION['username'])) {

     $username = $_SESSION['username']; //username is the username of user logged in

}else{

     $username = "guest"; //not logged in, so guest

}

$IP = $_SERVER['REMOTE_ADDR']; //= user IP

$loc = $_SERVER['PHP_SELF'];

$loc_name = "Homepage";
</pre>
<p>Now we can use a simple INSERT query to make it add the user online log ( row ):</p>
<pre name="code" class="php:nogutter">
"INSERT INTO online(timestamp, IP, username, location, loc_title)VALUES('$time', '$username', '$IP', '$loc', '$loc_name') "
</pre>
<p>We simple insert the data: $timestamp for the field 'timestamp', $IP for 'IP', $username for 'username', $loc for 'location' and $loc_name for the field 'loc_title'. Again use the mysql_query function to execute our query:</p>
<pre name="code" class="php:nogutter">
mysql_query("INSERT INTO online(timestamp, IP, username, location, loc_title)VALUES('$time', '$username', '$IP', '$loc', '$loc_name') ");
</pre>
<p>Ok, so we're now ready to get all users online/active in the last 5 minutes. We'll use a SELECT query to do this. To select all users we'll need to select all IP addresses but only UNIQUE ones once, so instead of using "SELECT field_name" we use "SELECT DISTINCT(field_name)":</p>
<pre name="code" class="php:nogutter">
"SELECT DISTINCT(IP) FROM online"
</pre>
<p>No need to add a WHERE clause part as we are sure all these rows in the table are from users active in the last 5 minutes. W removed old ones and added one for the viewing user. This time we put the query into the mysql_query function but as well in a variable because we'll be using it to count the amount of users online found.</p>
<pre name="code" class="php:nogutter">
$select_users = mysql_query("SELECT DISTINCT(IP) FROM online");
$users_on = mysql_num_rows($select_users);
</pre>
<p>We use the mysql_num_rows function to count the rows found by the $select_users query.</p>
<p>So now we can already show how many users are online, great!<br />
We simply display the number of $users_on.</p>
<p>Let's put it all together!</p>
<pre name="code" class="php:nogutter">
&lt;?php

session_start(); //if needed to use sessions

$time = time(); //current timestmap

$timeout = "3000"; //timeout in seconds, 5 min taken as example

$out = $time-$timeout; //all user logs/views from earlier than  this will be removed

if($_SESSION['username'] AND !empty($_SESSION['username'])) {

     $username = $_SESSION['username']; //username is the username of user logged in

}else{

     $username = "guest"; //not logged in, so guest

}

$IP = $_SERVER['REMOTE_ADDR']; //= user IP

$loc = $_SERVER['PHP_SELF'];

$loc_name = "Homepage";

mysql_connect("localhost", "root"); //host, user(, password)
mysql_select_db("test");

mysql_query("DELETE online WHERE timestamp < '$out' ");

mysql_query("INSERT INTO online(timestamp, IP, username, location, loc_title)VALUES('$time', '$username', '$IP', '$loc', '$loc_name') ");

$select_users = mysql_query("SELECT DISTINCT(IP) FROM online");
$users_on = mysql_num_rows($select_users);

if($users_on == 1) {

   echo "1 user online";

}else{

   echo $users_on." users online";

}

?>
</pre>
<p>Last but not least we use an if-loop to check if there's only 1 user online. Because if so: we need to use the word 'user' instead of 'users'</p>
<p>That's the end of the simple users online tutorial part 1 , in part 2 we'll be creating a list of the users that are online ( names and link location ).</p>
<p><strong>Part 2</strong></p>
<p>In the previous part we've made a system that shows the current amount of online users:</p>
<pre name="code" class="php:nogutter">
&lt;?php

session_start(); //if needed to use sessions

$time = time(); //current timestmap

$timeout = "3000"; //timeout in seconds, 5 min taken as example

$out = $time-$timeout; //all user logs/views from earlier than  this will be removed

if($_SESSION['username'] AND !empty($_SESSION['username'])) {

     $username = $_SESSION['username']; //username is the username of user logged in

}else{

     $username = "guest"; //not logged in, so guest

}

$IP = $_SERVER['REMOTE_ADDR']; //= user IP

$loc = $_SERVER['PHP_SELF'];

$loc_name = "Homepage";

mysql_connect("localhost", "root"); //host, user(, password)
mysql_select_db("test");

mysql_query("DELETE online WHERE timestamp < '$out' ");

mysql_query("INSERT INTO online(timestamp, IP, username, location, loc_title)VALUES('$time', '$username', '$IP', '$loc', '$loc_name') ");

$select_users = mysql_query("SELECT DISTINCT(IP) FROM online");
$users_on = mysql_num_rows($select_users);

if($users_on == 1) {

   echo "1 user online";

}else{

   echo $users_on." users online";

}

?>
</pre>
<p>Now beside showing how many total users are online, we'll also show how many members and how many guests are on. We'll aswel add a list of the members that are online. Let's start with the first thing: showing how many guests and members are online. Therefor we need to change this part of the code:</p>
<pre name="code" class="php:nogutter">
$select_users = mysql_query("SELECT DISTINCT(IP) FROM online");
 $users_on = mysql_num_rows($select_users);

 if($users_on == 1) {

    echo "1 user online";

 }else{

    echo $users_on." users online";

 }
</pre>
<p>Which selects all unique users by IP. We could make it 2 queries, where one selects all guests online ( WHERE username = 'guest' ) and the other one selects all members ( WHERE username != 'guest' ). But this way it could select one user double ( as both queries select unique IPs for THEIR query ). For example when a user just logged in, the old userlog row ( when he was 'guest' ) is selected in the first query and the new one ( where he is logged in ) is selected with the second query. So this way it could double select one user. So therefore we'll still use ONE query which can only select one user once ( because of the DISTINCT (IP) in only one query with same where clause (none) ). We'll need to get the data (username) from the query though and we need to select the username therefore as well:</p>
<pre name="code" class="php:nogutter">
$select_users = mysql_query("SELECT DISTINCT(IP), username FROM online");
$users_on = mysql_fetch_assoc($select_users); //all users
$guests = 0;
$users = 0;

while($user_on = mysql_fetch_assoc($select_users)) {

  if($user_on['username'] == "guest") {
     $guests += 1;
  }else{
     $members += 1;
  }

}
</pre>
<p>Ok let's go through the code. We start with the variables $guest and $members. These will contain the amount of guests and the amount of members logged in. We use the query now to as well select the username of the logged in users. Then for each logged in user found, the username is stored in $user_on['username']. As we used mysql_fetch_assoc to put the found rows of the query into $users_on['field_name']. For each row. Then inside the while loop we made it check if the username is 'guest' of the found row ( user online ) or not. If it's a guest, the variable $guests ( containing the amount of guests online ) will be increased. Otherwise it's a member who's logged in/online, so the variable $members will be increased by one. Now we can show the amount of members and guests online:</p>
<pre name="code" class="php:nogutter">
//show total users on:

if($users_on == 1) {
   echo "1 user online: ";
}else{
   echo $users_on." users online: ";
}

//show guests on:

if($guests == 1) {
   echo "1 guest online, ";
}else{
   echo $guests." guests online, ";
}

//show members on:

if($members == 1) {
    echo "1 member online";
}else{
   echo $members.' members online";
}
</pre>
<p>We done it the same way as before ( when we shown all users online) but now for both the guests and members, and the total users online (which is same as $guests+$members, or just $users_on which we used in the previous script too).</p>
<p>Ok, now we're going to show the USERNAMES of the members online. Therefor we'll need to make another array variable for which we'll add the username into a sub-variable of the array, when a new MEMBER online was found. We need to do this inside the while loop, which handles the data ( IP and username ) of the rows ( users online) found:</p>
<pre name="code" class="php:nogutter">
$usernames = array(); //array will be containing all usernames online found

while($user_on = mysql_fetch_assoc($select_users)) {

  if($user_on['username'] == "guest") {
     $guests += 1;
  }else{
     $members += 1;
  }

}
</pre>
<p>We created an array $usernames beforehand which we'll create a sub-variable for each time a new member online was found ( username will be stored ). This is the case when $username != "guest", which is the 'else' part of the loop. We know the data found is put in $user_on['field_name'], so the username would be set in $user_on['username']. So to add the username to our array we simply do this:</p>
<pre name="code" class="php:nogutter">
$usernames[] = $user_on['username'];
</pre>
<p>$usernames[] means it automaticly adds a new index ( new sub-variable ) to the array $usernames, and $user_on['username'] contains the username of the member found. As mentioned before we need to add this to the else part of the loop:</p>
<pre name="code" class="php:nogutter">
$usernames = array(); //array will be containing all usernames online found

while($user_on = mysql_fetch_assoc($select_users)) {

   if($user_on['username'] == "guest") {
      $guests += 1;
   }else{
      $members += 1;
     $usernames[] = $user_on['username'];
   }

 }
</pre>
<p>Ok, so now we'll have an array $usernames containing all usernames of members online found. The usernames are stored like this:</p>
<blockquote><p>$usernames[0] = "username of member #1 found";<br />
$usernames[1] = "username of member #2 found";<br />
... etc ...</p></blockquote>
<p>This is because we used $usernames[] to automaticly number the sub-variable index ( if the previous one was 0, then the next one will be 1 ).</p>
<p>We'll now use a foreach loop to get all values of the sub-variables ( usernames ) in $usernames:</p>
<pre name="code" class="php:nogutter">
foreach($usernames as $name) {

    echo "

 <b>".$name."</b> 

 ";

}
</pre>
<p>What it simply does is for each sub-variable of the array $usernames, it puts the value into $name and shows it. In other words: it shows all usernames found of members online.</p>
<p>Ok let's put it all together!</p>
<pre name="code" class="php:nogutter">
 &lt;?php

 session_start(); //if needed to use sessions

 $time = time(); //current timestmap

 $timeout = "3000"; //timeout in seconds, 5 min taken as example

 $out = $time-$timeout; //all user logs/views from earlier than  this will be removed

 if($_SESSION['username'] AND !empty($_SESSION['username'])) {

      $username = $_SESSION['username']; //username is the username of user logged in

 }else{

      $username = "guest"; //not logged in, so guest

 }

 $IP = $_SERVER['REMOTE_ADDR']; //= user IP

 $loc = $_SERVER['PHP_SELF'];

 $loc_name = "Homepage";

 mysql_connect("localhost", "root"); //host, user(, password)
 mysql_select_db("test");

 mysql_query("DELETE online WHERE timestamp < '$out' ");

 mysql_query("INSERT INTO online(timestamp, IP, username, location, loc_title)VALUES('$time', '$username', '$IP', '$loc', '$loc_name') ");

$select_users = mysql_query("SELECT DISTINCT(IP), username FROM online");
$users_on = mysql_fetch_assoc($select_users); //all users
$guests = 0;
$users = 0;

while($user_on = mysql_fetch_assoc($select_users)) {

  if($user_on['username'] == "guest") {
       $guests += 1;
    }else{
       $members += 1;
     $usernames[] = $user_on['username'];
    }

}

foreach($usernames as $name) {

    echo "

 <b>".$name."</b> 

 ";

}

?>
</pre>
<p>Cheers,<br />
Admin.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/users-online-part-1-part-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Basic Login System</title>
		<link>http://www.webcodez.net/php-mysql/basic-login-system/</link>
		<comments>http://www.webcodez.net/php-mysql/basic-login-system/#comments</comments>
		<pubDate>Wed, 20 Jan 2010 14:53:57 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[basics]]></category>
		<category><![CDATA[if loop]]></category>
		<category><![CDATA[Login System]]></category>
		<category><![CDATA[MySql]]></category>
		<category><![CDATA[net script]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[php login]]></category>
		<category><![CDATA[php simple]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[variables]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=177</guid>
		<description><![CDATA[In the previous tutorial we&#8217;ve been making a register system. In this tutorial we&#8217;ll be creating a login system for it, where members can login to your website and for example get access to a members area of your website. We&#8217;ll basicly be using SESSION variables in this tutorial to save the login session of [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous tutorial we&#8217;ve been making a register system. In this tutorial we&#8217;ll be creating a login system for it, where members can login to your website and for example get access to a members area of your website. We&#8217;ll basicly be using SESSION variables in this tutorial to save the login session of a member but you could also change all sessions into cookies.</p>
<p>Again we start with a form:</p>
<pre name="code" class="php:nogutter">
<form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">

... form login fields ...
</form>
</pre>
<p>The form method we use is the same as for the register system: POST. We use the same page to handle the login attempt so we make it go to ( action ) $_SERVER['PHP_SELF'] which equals the current page/file. So all user data will be send into $_POST['field_name'] variables to the same page ( itself ).</p>
<p>Now we&#8217;ll add the form fields, which for the login system are just the username and password fields and a submit button.</p>
<pre name="code" class="php:nogutter">
<form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">
<input type='text' name='username'>
<input type='password' name='password'>
<input type='submit' name='submit' value='log me in!'>
</form>
</pre>
<p>So once the user submits the form by clicking the submit button, the $_POST array will be created containing:</p>
<p>$_POST['username'] which equals the username filled in<br />
$_POST['password'] which equals the password filled in<br />
($_POST['submit'] which equals &#8216;log me in!&#8217;)</p>
<p>As we&#8217;re going to make it handle the login in the same page, we&#8217;ll need to make an if loop. This if loop will check if the form has been submitted already ( does $_POST exist? ). If so, it will handle the user filled in data which is stored in this $_POST array as explained above. If not, it will show the form as the user has not submitted it yet.</p>
<pre name="code" class="php:nogutter">
 &lt;?php

 if($_POST) {

 ... handle the login attempt ...

 }else{

 ... show the form ...

 }

 ?>
 </pre>
<p>We can already fill in the form in the else part of the loop ( when $_POST does not exist yet ).</p>
<pre name="code" class="php:nogutter">
&lt;?php

if($_POST) {

... handle the login attempt ...

}else{

?>
<form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">
<input type='text' name='username'>
<input type='password' name='password'>
<input type='submit' name='submit' value='log me in!'></form>

&lt;?php

}

?>
</pre>
<p>We nicely seperate the HTML code from the PHP code by first closing the php tag ( ?> ) and then re-opening it after the HTML code ( &lt;?php ) when the php code goes on. Do this rather than echoing the whole form.</p>
<p>Move on to the part of the if loop that occurs when the user did submit the form. First we need to make it connect to the database. We&#8217;ll take as example the database and table we created in the register system tutorial.</p>
<pre name="code" class="php:nogutter">
mysql_connect('localhost', 'root'); //like: 'host','user','pasword'
mysql_select_db('test'); //'database'
</pre>
<p> Let&#8217;s check whether there the login was valid. To do this we use a mysql_query and a mysql function. We assume there&#8217;s a table called &#8216;accounts&#8217; with the fields id, username, password. It could be called anyhow as long as you&#8217;ve created it correctly in the database as well. Have a look at the query first:</p>
<pre name="code" class="php:nogutter">
"SELECT id FROM accounts WHERE username = '".$_POST['username']."' AND password = '".$_POST['password']."' "
</pre>
<p>What it simply does ( well, tries to do ) is select a row ( to be exact the field &#8216;id&#8217;, doesn&#8217;t really matter what field though ) from the table &#8216;accounts&#8217; that has the same value for the field &#8216;username&#8217; and &#8216;password&#8217; as the user filled in ( $_POST['username'] and $_POST['password'] ). In other words: it tries to select an account with the same username and password the user filled in. We&#8217;ll put it into a variable and make it a query using the mysql_query function. Also we&#8217;ll use mysql_real_escape_string again to secure the user input.</p>
<pre name="code" class="php:nogutter">
$check_account = mysql_query("SELECT id FROM accounts WHERE username = '".mysql_real_escape_string($_POST['username'])."' AND password = '".mysql_real_escape_string($_POST['password'])."' ");
</pre>
<p>Now we aren&#8217;t going to actually retrieve the data the mysql query returned ( we aren&#8217;t even sure if the account actually exists ). We&#8217;ll instead use mysql_num_rows to check if there was any row returned by the query.</p>
<pre name="code" class="php:nogutter">
$check_account = mysql_query("SELECT id FROM accounts WHERE username = '".mysql_real_escape_string($_POST['username'])."' AND password = '".mysql_real_escape_string($_POST['password'])."' ");

$check_account1 = mysql_num_rows($check_account);
 </pre>
<p>$check_account1 now contains a number indicating the amount of rows it found with the query. When it found any rows ( so when $check_account1 contains a number greater than 0 ) the account exists. It found a row that has the same username and password as the user filled in. If not: there wasn&#8217;t any row ( any account in this case ) with the same username and password as the user filled in. So we can just make another if loop which checks if the account exists ( $check_account > 0 ).</p>
<pre name="code" class="php:nogutter">
 $check_account = mysql_query("SELECT id FROM accounts WHERE username = '".mysql_real_escape_string($_POST['username'])."' AND password = '".mysql_real_escape_string($_POST['password'])."' ");

$check_account1 = mysql_num_rows($check_account);

if ( $check_account > 0 ) {

    echo "Logged in!"; //account exists, show logged in message

}else{

   echo "Invalid login."; //account doesn't exist, show error message

}
</pre>
<p>Great, now it checks whether an account with the user filled in data exists. But we also want it to remember the user&#8217;s login, in a session. We&#8217;ll make it create a session called &#8216;logged&#8217; to do that.</p>
<pre name="code" class="php:nogutter">
$_SESSION['logged'] = true;
</pre>
<p>Which contains a boolean value indicating the user is logged in. Though this isn&#8217;t enough, we also need to make a session that contains the username or userid of the user logged in. I prefer using the user&#8217;s ID to determine what account is logged in as each user account has its own unique ID.<br />
To get the user account&#8217;s ID, we&#8217;ll use our previous query which actually selected it. However we first used it only to check if it existed. We&#8217;ll now actually retrieve the data ( user id ) of the query using the mysql_fetch_assoc function. We don&#8217;t need to use a while loop because we know it should be only 1 account that the query selects.</p>
<pre name="code" class="php:nogutter">
 $user = mysql_fetch_assoc($check_account); //get the row data the query returned
  $userid = $user['id']; //get the value of the field 'id' of the row the query returned
$_SESSION['userid'] = $userid; //put it into a session
</pre>
<p>And we created all our sessions required to make a user loggin! Let&#8217;s put it all together now.<br />
<strong><br />
File: login.php</strong></p>
<pre name="code" class="php:nogutter">
 &lt;?php

session_start(); // <-- always on top! needed to use our session

 if($_POST) {

 $check_account = mysql_query("SELECT id FROM accounts WHERE username = '".mysql_real_escape_string($_POST['username'])."' AND password = '".mysql_real_escape_string($_POST['password'])."' ");

 $check_account1 = mysql_num_rows($check_account);

if ( $check_account > 0 ) {

    echo "Logged in!"; //account exists, show logged in message

   $user = mysql_fetch_assoc($check_account); //get the row data the query returned

   $userid = $user['id']; //get the value of the field 'id' of the row the query returned

   $_SESSION['userid'] = $userid; //put it into a session

}else{

   echo "Invalid login."; //account doesn't exist, show error message

}

 }else{

 ?>
<form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">
<input type='text' name='username'>
<input type='password' name='password'>
<input type='submit' name='submit' value='log me in!'></form>

 &lt;?php

 }

 ?>
 </pre>
<p>Holdon, you might have noticed we did not use the session_start function yet, so we wouldn&#8217;t be able to use our sessions! Added it on the top of the page ( always! ).</p>
<p>Now the basic login page is done. We&#8217;ve now come to the part of &#8216;how to use the login?&#8217;. Well, we know that if a user is logged in, a session called &#8216;logged&#8217; is created and set to true ( ALWAYS, for all users that log in ). So we simply check if this session was created and equal to true, to check if a user is logged in:<br />
<strong><br />
file: sample_members_area.php</strong></p>
<pre name="code" class="php:nogutter">
&lt;?php
session_start(); //<--- there it is again

if($_SESSION['logged'] == true) {

    echo "Welcome user!";

}else{

   include("login.php"); //include the login page

}

?>
</pre>
<p>You could also add this to the login page. Also needed is to use the user id to get all info of the user. To do this we can use another mysql SELECT query just like we done to get the user id, but now for the username, password, email or any other field.</p>
<pre name="code" class="php:nogutter">
"SELECT username FROM accounts WHERE id = '".$_SESSION['userid']."' "
</pre>
<p>We now for example select the username of the user account with the id stored in the session &#8216;userid&#8217;, which equals the id of the user logged in.So it selects the username of the logged in user.We can again retrieve the data using mysql_fetch_assoc. Also remember to put the query into the mysql_query function to execute it.</p>
<pre name="code" class="php:nogutter">
$username = mysql_query("SELECT username FROM accounts WHERE id = '".$_SESSION['userid']."' ");

$username = mysql_fetch_assoc($username);

$username = $username['username']; //yeah bit weird names chosen, I know
</pre>
<p>So you could greet the user with:</p>
<pre name="code" class="php:nogutter">
echo "Hi there ".$username."! &lt;br /> Long time no see!";
</pre>
<p>End results:</p>
<p><strong>File: Login.php</strong></p>
<pre name="code" class="php:nogutter">
  &lt;?php

session_start(); // <-- always on top! needed to use our session

if($_SESSION['logged'] == true) { //user already logged in?

   include("Members_area.php"); //include members area

}else{

  if($_POST) {

  $check_account = mysql_query("SELECT id FROM accounts WHERE username = '".mysql_real_escape_string($_POST['username'])."' AND password = '".mysql_real_escape_string($_POST['password'])."' ");

  $check_account1 = mysql_num_rows($check_account);

 if ( $check_account > 0 ) {

     echo "Logged in!"; //account exists, show logged in message

   $user = mysql_fetch_assoc($check_account); //get the row data the query returned

   $userid = $user['id']; //get the value of the field 'id' of the row the query returned

   $_SESSION['userid'] = $userid; //put it into a session

 }else{

    echo "Invalid login."; //account doesn't exist, show error message

 }

  }else{

  ?>
<form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">
<input type='text' name='username'>
<input type='password' name='password'>
<input type='submit' name='submit' value='log me in!'></form>

  &lt;?php

  }

}

  ?>
  </pre>
<p><strong>File: Members_area.php</strong></p>
<pre name="code" class="php:nogutter">
&lt;?php
session_start(); //<--- there it is again

if($_SESSION['logged'] == true) {

    $username = mysql_query("SELECT username FROM accounts WHERE id = '".$_SESSION['userid']."' ");

    $username = mysql_fetch_assoc($username);

    $username = $username['username']; //yeah bit weird names chosen, I know

    echo "Hi there ".$username."! &lt;br /> Long time no see!";

}else{

   include("login.php"); //include the login page

}

?>
</pre>
<p>Cheers,<br />
Admin.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/basic-login-system/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Basic Register System</title>
		<link>http://www.webcodez.net/php-mysql/basic-register-system/</link>
		<comments>http://www.webcodez.net/php-mysql/basic-register-system/#comments</comments>
		<pubDate>Wed, 20 Jan 2010 14:41:48 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[basics]]></category>
		<category><![CDATA[if loop]]></category>
		<category><![CDATA[MySql]]></category>
		<category><![CDATA[net script]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[php register]]></category>
		<category><![CDATA[php simple]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[register system]]></category>
		<category><![CDATA[variables]]></category>
		<category><![CDATA[while loop]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=161</guid>
		<description><![CDATA[In this tutorial we&#8217;ll be creating a register system in which people can create their own account. It&#8217;s a basic register system which uses some mysql functions to insert data into the database (create the account), loops and some PHP functions to handle the POST variables. We&#8217;ll start creating our register page with a form [...]]]></description>
			<content:encoded><![CDATA[<p>In this tutorial we&#8217;ll be creating a register system in which people can create their own account. It&#8217;s a basic register system which uses some mysql functions to insert data into the database (create the account), loops and some PHP functions to handle the POST variables. We&#8217;ll start creating our register page with a form in which the user can fill in the info for his or her account.</p>
<p><strong>File: Register.php</strong></p>
<pre name="code" class="html:nogutter">&lt;form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">

... form felds ...

&lt;/form></pre>
<p>We start by creating the form itself. The attributes we set are method and action. Method is used to define how the data (text filled in the form fields) should be transferred. We use the POST method, which will store all data filled in by the user into $_POST variables. The action is set to the page where it should go to when the form is submitted. We set it to $_SERVER['PHP_SELF'], which is equal to the current file. So after the user completes filling in our form fields and submits the form, it will put all filled in data into $_POST variables and send it to itself (go to the same page).</p>
<p>Let&#8217;s add some form fields to the form, which the user needs to fill in to complete the registration.</p>
<pre name="code" class="html:nogutter">&lt;form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">

<b>*Username:</b>
<input type='text' name='username'> &lt;br />

<b>*Password  :</b>
<input type='password' name='password'> &lt;br />

<b>*Repeat Password: </b>
<input type='password' name='password_rep'> &lt;br />

<b>*Email:</b>
<input type='text' name='email'> &lt;br />
<input type='submit' name='submit' value='create account'>

&lt;/form></pre>
<p>We simply added 4 fields using basic HTML input tags and a submit button to submit the form. These four fields need to be filled in by the user in order to create his/her account. They may not be left empty: the username, password and email. We also created a &#8220;repeat password&#8221; field, which we use to verify the user filled in password. The name we give each input field is important because for each input field, a POST variable will be created once the user submits the form. The POST variable created for a certain field is $_POST['field_name'] and will contain the value the user gave to that field (filled in for that field). In this way all values of the fields will be submitted using POST variables. We will use these variables to check if the user filled in all fields (if they aren&#8217;t empty) and if the form has been submitted at all.</p>
<p>To actually create the account we&#8217;ll be storing the filled in values for the fields, into a database. Let&#8217;s create a database called &#8220;test&#8221; and a table called &#8220;accounts&#8221; which contains 4 fields ( equal to the amount of fields that are filled in for the form plus one ID field which is unique for each member ( password and repeat password should contain one and the same value so are of course just stored in one field: password ) ). If you are not sure how to do this you could also import the SQL code :</p>
<pre name="code" class="php:nogutter">SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
CREATE DATABASE 'test' DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE 'test';
CREATE TABLE IF NOT EXISTS 'accounts' (
  'id' int(250) NOT NULL AUTO_INCREMENT,
  'username' varchar(20) NOT NULL,
  'password' varchar(20) NOT NULL,
  'email' varchar(50) NOT NULL,
  PRIMARY KEY ('id')
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;</pre>
<p>Now we&#8217;ll create a loop to check if the user has already submitted the form. Which is the case when all fields data have been stored into $_POST variables. In other words: if the $_POST variables exist – the form has been submitted. This doesn&#8217;t mean all fields have been filled in though, because the $_POST variables could also be empty, but they are created ( as the user submitted the form).</p>
<pre name="code" class="php:nogutter">&lt;?php

If ( ... the form has been submitted ... ) {

    ... check if all fields have been filled in correctly ...

}else{ //form has not been submitted yet

    ... show the form ...

}

?>
</pre>
<p>This is how our loop looks like. Now we can already fill in our form which we just created and to check if the form has been submitted we just check if $_POST variable exists:</p>
<pre name="code" class="php:nogutter">
&lt;?php
If ( $_POST  ) {

    ... check if all fields have been filled in correctly - create account if valid ...

}else{ //form has not been submitted yet

?>

&lt;form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">

<b>*Username:</b>
<input type='text' name='username'> &lt;br />

<b>*Password  :</b>
<input type='password' name='password'> &lt;br />

<b>*Repeat Password: </b>
<input type='password' name='password_rep'> &lt;br />

<b>*Email:</b>
<input type='text' name='email'> &lt;p>
<input type='submit' name='submit' value='create account'>

&lt;/form>

&lt;?php

}

?></pre>
<p>Only thing last is to check all fields and create the account if valid. As mentioned before, once the form has been submitted, all field values have been stored into $_POST['field_name']. So to check if all fields have been filled in, we just need to check if all $_POST variables aren&#8217;t empty. To do this we are going to use a foreach loop to make it easier. We could also just check all $_POST variables like: $_POST['username'] and $_POST['password'], etc.. But this is an inefficient way to do it, as when you add a new form field, you would need to add it to the loop as well ( check that field too ). Beside that it just can be done much easier and faster than checking all fields manually. The foreach loop will check all fields and values the same way. Let&#8217;s just have alook at the loop code:</p>
<pre name="code" class="php:nogutter">foreach ( $_POST as $key => $value ) {

    if ( empty($value) )

        $errors .= "Field '".$key."' has to be filled in. &lt;br /> ";

    }else{

        ... check if filled in values are valid ...

    }

}</pre>
<p>Ok, let&#8217;s go through this code. What it basicly does is check all sub-variables of the array $_POST ( which are all fields ) and store the name of them in $key and the value of them in $value. As for each field a sub-variable for the array $_POST has been created, it will check each field. $key will contain the name of the field and $value the value ( filled in by the user ). Then we use an if loop to check if the value of the field is empty: we use the function empty to do this. If it&#8217;s empty, we&#8217;ll add text to a variable called $errors. This variable we use to store all errors into if any. This way we can also check if there are any errors at all by checking if the variable $errors contains anything: if not, the user filled in all fields correctly and we can create the account. Otherwise it should show the errors ( echo $errors ).</p>
<p>Now there&#8217;s one more part of the if loop that needs to be done: the part where it checks if the values filled in are actually valid. This part runs when the $value was not empty. We&#8217;ll use a function preg_match for this. What we basicly do is check if it contains the characters that are allowed ( which are basicly: numbers, spaces and alphabetical characters ). The function works like this:</p>
<pre name="code" class="php:nogutter">preg_match("/[...pattern that needs to be matched...]/", $value_to_check)</pre>
<p>In our case the pattern is equal to all numbers, spaces and alphabetical characters as mentioned above. The value to check is the filled in value of the field, which is stored in $value as as well mentioned above. This makes us end up with the following code:</p>
<pre name="code" class="php:nogutter">        If ( !preg_match("/[0-9A-Za-z -_]/", $value) )
            $errors .= "&lt;p> Field '".$key."' has been given an invalid value. &lt;/p>";</pre>
<p>All numbers are 0-9, all capital alphabetical characters are A-Z and all normal alphabetical characters are a-z, and we also allow the &#8211; and _ symbols to be used. Now we check if the value filled in for the current field ( stored in $value ) does NOT match this pattern . Which is the case when it contains any other symbols/characters than the ones given in the pattern. We use the ! symbol for that, which means simply: NOT. In that case we add an error to the $error variable ( the field is not filled in correctly, using inappropriate characters ).</p>
<p>Let&#8217;s put it all together.</p>
<pre name="code" class="php:nogutter">&lt;?php

If ( $_POST  ) {

foreach ( $_POST as $key => $value ) {

        if ( empty($value) )

            $errors .= "&lt;p> Field '".$key."' has to be filled in. &lt;/p>";

        }else{

            If ( !preg_match("/[0-9A-Za-z -_]/", $value) )
                $errors .= "&lt;p> Field '".$key."' has been given an invalid value. &lt;/p>";

        }

}

    ...  check if the passwords ( normal and repeated ) matched ...

    ... check if username/email does not already exist ...

    ...  check if there were any errors with the filled in fields ...

}else{ //form has not been submitted yet

?>

&lt;form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">

<b>*Username:</b>
<input type='text' name='username'> &lt;br />

<b>*Password  :</b>
<input type='password' name='password'> &lt;br />

<b>*Repeat Password: </b>
<input type='password' name='password_rep'> &lt;br />

<b>*Email:</b>
<input type='text' name='email'> &lt;p>
<input type='submit' name='submit' value='create account'>

&lt;/form>

&lt;?php

}

?></pre>
<p>There&#8217;s one field that needs to be checked in a different way: the &#8216;password_rep&#8217; field. Which needs to be equal to the password field. We&#8217;ll use another if loop for that (already put into the code above):</p>
<pre name="code" class="php:nogutter">        If( $_POST['password_rep'] != $_POST['password'])
            $errors .= "&lt;p> Passwords don't match! &lt;/p>";</pre>
<p>A simple condition checks whether they are not equal to eachother (!=). In that case, an error will be added.</p>
<p>Now there&#8217;s a last thing that needs to be checked. We&#8217;re going to check if there isn&#8217;t already an account on the given username or email. We&#8217;ll use a simple mysql SELECT query to do this:</p>
<pre name="code" class="php:nogutter">        $check_account = mysql_query("SELECT id
                                                                    FROM accounts
                                                                    WHERE username = '".$_POST['username']."' OR email = '".$_POST['email']."' ");</pre>
<p>We select the field &#8216;id&#8217; from the table &#8216;accounts&#8217; (we could select any field) from a row where the username or email is equal to what the user filled in as username/email. To make it more secure we can use the mysql_real_escape_string function that escapes all possible harming characters out of the strings.</p>
<pre name="code" class="php:nogutter">        $check_account = mysql_query("SELECT id
                                                                     FROM accounts
                                                                     WHERE username = '".mysql_real_escape_string($_POST['username'])."' OR email = '".mysql_real_escape_string($_POST['email'])."' ");</pre>
<p>Next, instead of retrieving the rows/results ( as we aren&#8217;t sure if there is any row like this already ) we&#8217;ll check if the query selected any rows at all. In other words: we&#8217;ll check if there is already an account with this username or email as this is the only thing we need to check with this query. We&#8217;ll use the function mysql_num_rows to do this.</p>
<pre name="code" class="php:nogutter">        $check_account = mysql_query("SELECT id
                                                                    FROM accounts
                                                                    WHERE username = '".mysql_real_escape_string($_POST['username'])."' OR email = '".mysql_real_escape_string($_POST['email'])."' ");

        $check_account = mysql_num_rows($check_account);</pre>
<p>$check_account now contains a number of the rows that have the same username or email as the user filled in for his account to register. So if $check_account contains a number greater than 0, this means there&#8217;s already 1 or more accounts with this username or email. In that case an error should be added that the username or email already exists for an account.</p>
<pre name="code" class="php:nogutter">        $check_account = mysql_query("SELECT id
                                                                    FROM accounts
                                                                    WHERE username = '".mysql_real_escape_string($_POST['username'])."' OR email = '".mysql_real_escape_string($_POST['email'])."' ");

        $check_account = mysql_num_rows($check_account);

        If($check_account > 0)
            $errors .= "&lt;p> An account with the same username or email already exists. &lt;/p>";</pre>
<p>Now we need to create a code to check if there were any errors: in other words if $errors contains text. We&#8217;ll again use the empty function. If $errors is empty, we can create the account. Otherwise we show the errors.</p>
<p>Now we checked all possible errors for the user filled in data for his/her account to be created. So let&#8217;s put it all together.</p>
<pre name="code" class="php:nogutter">&lt;?php

If ( $_POST  ) {

foreach ( $_POST as $key => $value ) {

        if ( empty($value) )

            $errors .= "&lt;p> Field '".$key."' has to be filled in. &lt;/p>";

        }else{

            If ( !preg_match("/[0-9A-Za-z -_]/", $value) )
                $errors .= "&lt;p> Field '".$key."' has been given an invalid value. &lt;/p>";

        }

}
        If( $_POST['password_rep'] != $_POST['password'])
            $errors .= "&lt;p> Passwords don't match! &lt;/p>";

        $check_account = mysql_query("SELECT id FROM accounts WHERE username = '".mysql_real_escape_string($_POST['username'])."' OR email = '".mysql_real_escape_string($_POST['email'])."' ");

        $check_account = mysql_num_rows($check_account);

        If($check_account > 0)
            $errors .= "&lt;p> An account with the same username or email already exists. &lt;/p>";

    ...  check if there were any errors with the filled in fields ...

}else{ //form has not been submitted yet

?>

&lt;form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">

<b>*Username:</b>
<input type='text' name='username'> &lt;br />

<b>*Password  :</b>
<input type='password' name='password'> &lt;br />

<b>*Repeat Password: </b>
<input type='password' name='password_rep'> &lt;br />

<b>*Email:</b>
<input type='text' name='email'> &lt;p>
<input type='submit' name='submit' value='create account'>

&lt;/form>

&lt;?php

}

?></pre>
<pre name="code" class="php:nogutter">If ( empty($errors) OR !isset($errors) ) {

    ... create account ...

}else{

    ... show errors ...

}</pre>
<p>Showing the errors is not such a big deal, we just echo the variable $errors which contains all errors. Creating the account isn&#8217;t such a big deal either. We&#8217;ll be using a few mysql functions &#038; queries. Which we use to insert rows into the database ( create the account ). First we&#8217;ll need to connect to the host and database. We&#8217;ll use the functions mysql_connect and mysql_select_database.</p>
<pre name="code" class="php:nogutter">mysql_connect("host", "user", "pass");
mysql_select_db("database");</pre>
<p>We&#8217;ll now use a basic mysql_query function to INSERT the values into the database.</p>
<pre name="code" class="php:nogutter">mysql_query( ... query ... );</pre>
<p>In our case the query is to INSERT all values into the table &#8216;accounts&#8217;.</p>
<pre name="code" class="php:nogutter">$query = mysql_query("INSERT INTO accounts(username, password, email)VALUES('".$_POST['username']."', '".$_POST['password']."', '".$_POST['email']."')");</pre>
<p>That&#8217;s how the query looks like. I think it isn&#8217;t that hard so will explain it shortly: we use INSERT INTO to insert data into a table, in our case &#8216;account&#8217;s . Then we need to define which fields we want to insert data into, and put them between brackets after the table: username, password, email in this case. Also we need to give the VALUES for each field, which are stored in $_POST['field_name']. Though, to be sure there won&#8217;t be any SQL injections possible, we will still use the mysql_real_escape_string function to handle all filled in values so that they can&#8217;t harm the database with any bad codes. Even though we already checked the values, you should never just directly insert user filled in data to the database.</p>
<pre name="code" class="php:nogutter">$query = mysql_query("INSERT INTO accounts(username, password, email)VALUES('".mysql_real_escape_string($_POST['username'])."', '".mysql_real_escape_string($_POST['password'])."', '".mysql_real_escape_string($_POST['email'])."')");</pre>
<p>Now we need to check if the query was successfully:</p>
<pre name="code" class="php:nogutter">If($query) {

    echo "Success! Account created!";

}else{

    echo "There was an error creating the account. Please try again or contact the web administrator";

}</pre>
<p>We just use a basic loop to check if the $query variable, which executes the mysql query, was executed successfully.</p>
<p>Now we put it all together!<br />
 <br />
<strong>File: Register.php</strong></p>
<pre name="code" class="php:nogutter">&lt;?php

If ( $_POST  ) {

foreach ( $_POST as $key => $value ) {

        if ( empty($value) )

            $errors .= "&lt;p> Field '".$key."' has to be filled in. &lt;/p>";

        }else{

            If ( !preg_match("/[0-9A-Za-z -_]/", $value) )
                $errors .= "&lt;p> Field '".$key."' has been given an invalid value. &lt;/p>";

        }

    }

        If( $_POST['password_rep'] != $_POST['password'])
            $errors .= "&lt;p> Passwords don't match! &lt;/p>";

        $check_account = mysql_query("SELECT id FROM accounts WHERE username = '".mysql_real_escape_string($_POST['username'])."' OR email = '".mysql_real_escape_string($_POST['email'])."' ");

        $check_account = mysql_num_rows($check_account);

        If($check_account > 0)
            $errors .= "&lt;p> An account with the same username or email already exists. &lt;/p>";

If ( empty($errors) OR !isset($errors) ) {

mysql_connect(host, user, pass);
mysql_select_db(database);

$query = mysql_query("INSERT INTO accounts(username, password, email)VALUES('".mysql_real_escape_string($_POST['username'])."', '".mysql_real_escape_string($_POST['password'])."', '".mysql_real_escape_string($_POST['email'])."')");

If($query) {

    echo "Success! Account created!";

}else{

    echo "There was an error creating the account. Please try again or contact the web administrator";

}

}else{

    echo $errors;

}

}else{ //form has not been submitted yet

?>

&lt;form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">

<b>*Username:</b>
<input type='text' name='username'> &lt;br />

<b>*Password  :</b>
<input type='password' name='password'> &lt;br />

<b>*Repeat Password: </b>
<input type='password' name='password_rep'> &lt;br />

<b>*Email:</b>
<input type='text' name='email'> &lt;p>
<input type='submit' name='submit' value='create account'>

&lt;/form>

&lt;?php

}

?></pre>
<p>And we&#8217;ve got our register system in ONE file!</p>
<p>Note: In queries you might have seen a lot of quotes and double quotes. We use &#8216;&#8221;. and .&#8221;&#8216; to separate an array ( like $_POST[] ) from the rest of the query.</p>
<p>Cheers,<br />
Admin.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/basic-register-system/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MySql Basics &#8211; Retrieve Data</title>
		<link>http://www.webcodez.net/php-mysql/mysql-basics-retrieve-data/</link>
		<comments>http://www.webcodez.net/php-mysql/mysql-basics-retrieve-data/#comments</comments>
		<pubDate>Tue, 19 Jan 2010 11:23:03 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[basics]]></category>
		<category><![CDATA[fundamentals]]></category>
		<category><![CDATA[MySql]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[while loop]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=157</guid>
		<description><![CDATA[To retrieve data from a table of the database, we can use the mysql SELECT query. As discussed in the previous chapter, we use the mysql_query function to interactwith the database ( insert/retrieve data ). Although we&#8217;re now not going to INSERT data into the database but we&#8217;ll be using the SELECT type of query [...]]]></description>
			<content:encoded><![CDATA[<p>To retrieve data from a table of the database, we can use the mysql SELECT query. As discussed in the previous chapter, we use the mysql_query function to interactwith the database ( insert/retrieve data ). Although we&#8217;re now not going to INSERT data into the database but we&#8217;ll be using the SELECT type of query to retrieve data from the database ( from a certain table ). This type of query looks like this (basic structure):</p>
<pre name="code" class="php:nogutter">
mysql_query("SELECT field_name FROM table_name WHERE clause");
</pre>
<p>The 2 main things that need to be set are the field(s) you want to select the values of, and from what table you want to do this. Though if you only set these argruments, then it would retrieve the values of the fields in that table ( the fields you set ) for ALL rows it has. So if you only want to get the field(s)&#8217;s value of a specific row(s), you can be more specific by adding a &#8216;WHERE clause&#8217; part. Fill in any condition for the &#8216;clause&#8217; part. For example:</p>
<p>Example table &#8216;users&#8217;:<br />
[TABLE=2]</p>
<p>Example query:</p>
<pre name="code" class="php:nogutter">
$usernames = mysql_query("SELECT username FROM users WHERE country = 'USA'");
</pre>
<p>Say you&#8217;ve got a table called &#8216;users&#8217; which contains all user accounts of a website. A query smilar to this could be used to retrieve the value of the field &#8216;username&#8217; of all rows ( user accounts in this case ) that have the value ´USA´ for the field ´country´. In other words: in this example it would select all usernames of users who have set their country to &#8216;USA&#8217;.</p>
<p>In this example it would select the first and second row, which have the country set to USA. So it would select the username &#8216;Admin&#8217; and the username &#8216;Test2&#8242;. Which can be stored into an array using the function mysql_fetch_assoc(mysql query here).</p>
<p>However it only puts one row into an array a time. So it only selects 1 row per time, but say we want to show all rows ( usernames of them ) then we will need to use the while loop and the mysql_fetch_assoc function.</p>
<pre name="code" class="php:nogutter">
$usernames = mysql_query("SELECT username FROM users WHERE country = 'USA'");

while($user_row = mysql_fetch_assoc($usernames)) {

    echo "Row (user) match found:".$user_row['username']."

";

}
</pre>
<p>Ok let&#8217;s have a look into this loop. What it basicly does, is execute the mysql query in $usernames and retrieve the data of the row it finds ( in this case the value of the field &#8216;username&#8217; of that certain row it found ). But as it can only select one row a time, it will keep doing it for each row it finds. So when it finds a row that matches the query, it will put the data into the variable $user_row as we called it. Then execute the while loop code ( echo&#8217;s some text with the username found ) and repeats it for each row it find.In this case there were 2 rows that matched the query. So for each of the rows the data will be put in the $user_row variable and the while loop will be executed for each row seperated.</p>
<p>When a row is found then the values of the fields it selected in the query ( username only in this case ) will be stored into $user_row['field_name']. In this case we selected the field &#8216;username&#8217; so the value of it will be stored in the variable $user_row['username']. If you need to select more than one field, for one row each field&#8217;s value will be stored into its own sub-variable too like: $user_row['field_name'].</p>
<p>Then we&#8217;ve come to the output of this code, which is:</p>
<blockquote><p>Row (user) match found: Admin<br />
Row (user) match found: Test2</p></blockquote>
<p>That&#8217;s it, hope you learnt something again</p>
<p>Cheers,<br />
Admin.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/mysql-basics-retrieve-data/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MySql Basics &#8211; Insert Data</title>
		<link>http://www.webcodez.net/php-mysql/mysql-basics-insert-data/</link>
		<comments>http://www.webcodez.net/php-mysql/mysql-basics-insert-data/#comments</comments>
		<pubDate>Tue, 19 Jan 2010 11:20:45 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[basics]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[fundamentals]]></category>
		<category><![CDATA[Insert Data]]></category>
		<category><![CDATA[Insert Query]]></category>
		<category><![CDATA[MySql]]></category>
		<category><![CDATA[Query]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=155</guid>
		<description><![CDATA[To insert data into the database, mysql queries are used. There are multiple types of mysql queries. The one to put data into the database is the INSERT query. This one inserts a new row into the database which requires the fields of a row for that table to be given a value to.
A basic [...]]]></description>
			<content:encoded><![CDATA[<p>To insert data into the database, mysql queries are used. There are multiple types of mysql queries. The one to put data into the database is the INSERT query. This one inserts a new row into the database which requires the fields of a row for that table to be given a value to.</p>
<p>A basic mysql query structure:</p>
<pre name="code" class="php:nogutter">
mysql_query("...query here..");
</pre>
<p>A basic INSERT query:</p>
<pre name="code" class="php:nogutter">
mysql_query("INSERT INTO table_name (field1, field2) VALUES ('value1', 'value2') ");
</pre>
<p>We could again use the or die(mysql_error()) function to make it show the mysql error message when an error occurs.</p>
<p>So in the above example we made it insert a new row for the table &#8216;table_name&#8217;. For that row we gave field1 the value &#8216;value1&#8242; and field2 the value &#8216;value2&#8242;.</p>
<p>Let&#8217;s have a look at an example of a table containing all user accounts (=rows):</p>
<p>Example table &#8216;users&#8217;:</p>
<p>[TABLE=1]</p>
<p>We already got one row in the table of the database, one user account. To add another one to this table we need to set values for the fields (id, )username, password, email. The ID field usually is auto_increment and primairy key, which means it&#8217;s a unique key for each row and automaticly increases for each new row that&#8217;s added and so doesn&#8217;t need to be set by ourselves. The example query would look like this ( for this table called &#8216;users&#8217; ):</p>
<pre name="code" class="php:nogutter">
$new_user = mysql_query("INSERT INTO users (username, password, email) VALUES ('testuser', 'testpassword', 'test.email@hotmail.com') ");
</pre>
<p>You see we here create a new row using the INSERT query, for the table called &#8216;users&#8217;, giving the value &#8216;testuser&#8217; to the field &#8216;username&#8217;, &#8216;testpassword&#8217; to the field &#8216;passsword&#8217; and &#8216;test.email@hotmail.com&#8217; to the field &#8216;email&#8217; for the new row we create ( representing a new user in this case ).</p>
<p>Hope you learnt something, if you have any questions, feel free to ask.</p>
<p>Cheers,<br />
Admin.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/mysql-basics-insert-data/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MySql Basics &#8211; Connect</title>
		<link>http://www.webcodez.net/php-mysql/mysql-basics-connect/</link>
		<comments>http://www.webcodez.net/php-mysql/mysql-basics-connect/#comments</comments>
		<pubDate>Tue, 19 Jan 2010 11:17:17 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[basics]]></category>
		<category><![CDATA[Connect]]></category>
		<category><![CDATA[fundamentals]]></category>
		<category><![CDATA[MySql]]></category>
		<category><![CDATA[mysql_connect]]></category>
		<category><![CDATA[mysql_select_db]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=153</guid>
		<description><![CDATA[MySql can be used to interact with databases: insert and retrieve data. It can come very handy when you need to save a collection of the same &#8216;kind&#8217; ( such as products or forum messages, user accounts, etc. ) and which need to be able to be edited easily. To interact with the database you [...]]]></description>
			<content:encoded><![CDATA[<p>MySql can be used to interact with databases: insert and retrieve data. It can come very handy when you need to save a collection of the same &#8216;kind&#8217; ( such as products or forum messages, user accounts, etc. ) and which need to be able to be edited easily. To interact with the database you first need to connect to the host and then select the database you want to interact with. In MySql you can use the functions mysql_connect and mysql_select_db to do so.</p>
<pre name="code" class="php:nogutter">
mysql_connect("host", "username", "password");
mysql_select_db("database");
</pre>
<p>mysql_connect is used to connect to the host, which requires a username and a password. When the user for the host requires no password, you can leave out the password. The host is usually just &#8220;localhost&#8221;, depending on your host (settings). For the username you can often use &#8220;root&#8221; as default username if there aren&#8217;t any other users made for the host.</p>
<p>mysql_select_db is pretty much straight forward I guess. You make it select the database you&#8217;re going to use. You can also use the or die(&#8220;error message here&#8221;) to make it show an error when it fails to connect. There&#8217;s a standard mysql error message which can be called by using mysql_error() function.So it&#8217;d be:</p>
<pre name="code" class="php:nogutter">
mysql_connect("localhost", "root", "mypassword")or die(mysql_error());
mysql_select_db("mydatabase")or die(mysql_error());
</pre>
<p>So when any error occurs while connecting to the host/database, the mysql error message will appear containing the error occured.</p>
<p>You can also manually check whether the connection was successfully by putitng them into variables and checking the variables:</p>
<pre name="code" class="php:nogutter">
$connect = mysql_connect("localhost", "root", "mypassword");
$db      = mysql_select_db("mydatabase");

if(!$connect) {

     die("Host connection failed");

}

if(!$db) {

    die("Database connection failed");

}

?>
</pre>
<p>Now you&#8217;re ready to use the mysql functions to interact with the database, such as mysql_query, which we&#8217;ll be discussing in the next chapter.</p>
<p>Admin.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/mysql-basics-connect/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
