Showing posts with label Tutorials. Show all posts
Showing posts with label Tutorials. Show all posts

Sunday, September 30, 2007

Connecting to MySQL database

This tutorial will show you how to connect to mysql database. It's easy to write a script to connect to world's most popular opensource database.

Define your database information:

* host="localhost" you don't have to change it. When it's on your computer or server it still be localhost

Username = mysqluser
Password = 123456
Database = test

$host="localhost";
$username="phpeasystep";
$password="1234";
$db_name="test";

mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select db");

or

mysql_connect("localhost", "phpeaststep", "1234")or die("cannot connect to server");
mysql_select_db("test")or die("cannot select db");

Creating file config.php
$host="localhost";
$username="phpeasystep";
$password="1234";
$db_name="test";


mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select db");
save this file as "config.php"
when you want to use this code include it to your main php file

example


include("config.php");

$tbl_name="member";
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);

?>

PHP Counter script tutorial

Create your own counter script. Using a basic knowledge of php + mysql script and keeps your visitors number to database for analysis.

Step1. Create table "counter" in database "test".
CREATE TABLE `counter` (
`counter` int(9) NOT NULL default '0'
) TYPE=MyISAM;

Step2. Create file counter.php.
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect to server "); mysql_select_db("$db_name")or die("cannot select DB")
$sql="SELECT * FROM $tbl_name";$result=mysql_query($sql);
$rows=mysql_fetch_array($result);$counter=$rows['counter'];


// if have no counter value set counter = 1
if(empty($counter)){$counter=1;$sql1="INSERT INTO $tbl_name(counter) VALUES('$counter')";$result1=mysql_query($sql1);}
echo "You 're visitors No. ";

echo $counter;
// count more value
$addcounter=$counter+1;$sql2="update $tbl_name set counter='$addcounter'";$result2=mysql_query($sql2);
mysql_close();

?>