Wednesday, November 24, 2010

Simple Chat script in PHP, MySQL and Ajax

In this tutorial I will show you how to create a simple but very effective Chat script, and I said effective because unlike the most of the chat scripts this one deletes automatically the old messages from the database. Here is a live demo:

------------------------------
hi
venkat

hi
raja
------------------------------

The chat is refreshed automatically each 30 seconds.

Let`s start: First we need to create a MySQL table with 4 fields:

time - the time when the message was posted (UNIX)
name - the name of the author of the message
ip - the ip of the author of the message
message - the message text


To create the table (I will call it chat) I`we used the following file:
create-table.php


//Connect to MySQL
mysql_connect('host', 'database', 'password')
or die (mysql_error());
//Select database
mysql_select_db('database')
or die (mysql_error());
//Create the table
mysql_query("create table chat(
time int(11) NOT NULL,
name varchar(30) NOT NULL,
ip varchar(15) NOT NULL,
message varchar(255) NOT NULL,
PRIMARY KEY (time)
)") or die (mysql_error());
echo "Complete.";
?>



For the rest of the Chat script we will need 3 more files:
chat.php
send.php
show-messages.php

Let`s start with the chat.php what will contain the forms and all the Ajax scripts what will trigger the other 2 files:
chat.php








//This div will contain the messages

//This div will contain an eventual error message

//This div contains the forms and the send button

Name:















//This div will contain the messages

//This div will contain an eventual error message

//This div contains the forms and the send button

Name:









send.php



//Connect to MySQL
mysql_connect('host', 'database', 'password') or die (1);
//Select database
mysql_select_db('database') or die (2);
//Check if message is empty and send the error code
if(strlen($message) <>
echo 3;
}
//Check if message is too long
else if(strlen($message) > 255){
echo 4;
}
//Check if name is empty
else if(strlen($name) <>
echo 5;
}
//Check if name is too long
else if(strlen($name) > 29){
echo 6;
}
//Check if the name is used by somebody else
else if(mysql_num_rows(mysql_query("select * from chat where name = '" . $name . "' and ip != '" . @$REMOTE_ADDR . "'")) != 0){
echo 7;
}
//If everything is fine
else{
//This array contains the characters what will be removed from the message and name, because else somebody could send redirection script or links
$search = array("<",">",">","<");
//Insert a new row in the chat table
mysql_query("insert into chat values ('" . time() . "', '" . str_replace($search,"",$name) . "', '" . @$REMOTE_ADDR . "', '" . str_replace($search,"",$message) . "')") or die(8);
}
?>

show-messages.php


//Connect to MySQL
mysql_connect('host','database','password');
//Select database
mysql_select_db('database') or die(2);
//Get the first 10 messages ordered by time
$result = mysql_query("select * from chat order by time desc limit 0,10");
$messages = array();
//Loop and get in an array all the rows until there are not more to get
while($row = mysql_fetch_array($result)){
//Put the messages in divs and then in an array
$messages[] = "
" . $row[name] . " - " . date('g:i A M, d Y',$row[time]) . "
" . $row[message] . "
";

//The last posts date
$old = $row[time];
}
//Display the messages in an ascending order, so the newest message will be at the bottom
for($i=9;$i>=0;$i--){
echo $messages[$i];
}
//This is the more important line, this deletes each message older then the 10th message ordered by time is deleted, so the table will never have to store more than 10 messages.
mysql_query("delete from chat where time < " . $old);
?>


And this is it. A very effect chat system what uses only 10 rows of a MySQL table. This chat system can be easily upgraded with admin options or IP bans, smileys and other stuff like this. If you have any question related to this chat system just ASK!

Monday, November 22, 2010

Count number of rows with php mysql

This is a small script which will help you find the number of rows from a mysql database for your query.



//code for connect.php

$host = "localhost"; // replace this with your host, default is localhost

$user = "username"; // replace with the mysql username

$pass = "password"; // replace with the mysql password

$db_name = "mydb";


mysql_connect($host,$user,$pass) or die("
Cannot connect to host.....".mysql_error());

mysql_select_db($db_name) or die("
Cannot connect to Database.....".mysql_error());

?>


// Connect to the database

include "connect.php";

// Query the database and get the count

$result = mysql_query("SELECT * FROM tablename");

$num_rows = mysql_num_rows($result);

// Display the results

echo $num_rows;

Thursday, November 11, 2010

What is PHP?


What is PHP?

  • PHP stands for PHP: Hypertext Preprocessor
  • PHP is a server-side scripting language, like ASP
  • PHP scripts are executed on the server
  • PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
  • PHP is an open source software
  • PHP is free to download and use

What is a PHP File?

  • PHP files can contain text, HTML tags and scripts
  • PHP files are returned to the browser as plain HTML
  • PHP files have a file extension of ".php", ".php3", or ".phtml"

What is MySQL?

  • MySQL is a database server
  • MySQL is ideal for both small and large applications
  • MySQL supports standard SQL
  • MySQL compiles on a number of platforms
  • MySQL is free to download and use

PHP + MySQL

  • PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform)

Why PHP?

  • PHP runs on different platforms (Windows, Linux, Unix, etc.)
  • PHP is compatible with almost all servers used today (Apache, IIS, etc.)
  • PHP is FREE to download from the official PHP resource: www.php.net
  • PHP is easy to learn and runs efficiently on the server side

Where to Start?

To get access to a web server with PHP support, you can:

  • Install Apache (or IIS) on your own server, install PHP, and MySQL
  • Or find a web hosting plan with PHP and MySQL support


PHP is a server-side scripting language for creating dynamic Web pages. You create pages with PHP and HTML. When a visitor opens the page, the server processes the PHP commands and then sends the results to the visitor's browser, just as with ASP or ColdFusion. Unlike ASP or ColdFusion, however, PHP is Open Source and cross-platform. PHP runs on Windows NT and many Unix versions, and it can be built as an Apache module and as a binary that can run as a CGI. When built as an Apache module, PHP is especially lightweight and speedy. Without any process creation overhead, it can return results quickly, but it doesn't require the tuning of mod_perl to keep your server's memory image small.

In addition to manipulating the content of your pages, PHP can also send HTTP headers. You can set cookies, manage authentication, and redirect users. It offers excellent connectivity to many databases (and ODBC), and integration with various external libraries that let you do everything from generating PDF documents to parsing XML.

PHP goes right into your Web pages, so there's no need for a special development environment or IDE. You start a block of PHP code with and end it with ?>. (You can also configure PHP to use ASP-style <% %> tags or even .) The PHP engine processes everything between those tags.

PHP's language syntax is similar to C's and Perl's. You don't have to declare variables before you use them, and it's easy to create arrays and hashes (associative arrays). PHP even has some rudimentary object-oriented features, providing a helpful way to organize and encapsulate your code.

Although PHP runs fastest embedded in Apache, there are instructions on the PHP Web site for seamless setup with Microsoft IIS and Netscape Enterprise Server. If you don't already have a copy of PHP, you can download it at the official Web site. You'll also find a manual that documents all of PHP's functions and features