#!/bin/bash
while read line
do
echo $line
done
Java Read File
Scanner method can be slow for big file:
import java.io.*;
import java.util.*;
private void readFile( String filename ) {
try {
Scanner in = new Scanner( new FileReader( filename ) );
String line = in.nextLine();
System.out.println( line );
} catch ( FileNotFoundException e ) {
}
}
Power of 2
| n | 2^n | approximate | Remarks |
|---|---|---|---|
| 1 | 1 | 1 | 1 byte, 8 bits, 0xFF, java byte |
| 2 | 4 | 4 | 4 bytes, 32 bits, 0xFFFFFFFF, java int, float |
| 3 | 8 | 8 | 8 bytes, 64 bits, java long, double |
| 4 | 16 | ||
| 5 | 32 | ||
| 6 | 64 | ||
| 7 | 128 | ||
| 8 | 256 | ||
| 9 | 512 | ||
| 10 | 1024 | ~1000 | 1KB, 1024 |
| ... | |||
| 16 | 65536 | 65536 | 64KB |
| ... | |||
| 20 | 1,048,536 | ~1,000,000 | 1MB, 1024^2 |
| ... | |||
| 30 | 1,073,741,824 | ~1,000,000,000 | 1GB, 1024^3 |
| ... | |||
| 32 | 4,294,967,296 | ~4,300,000,000 | 4GB |
| ... | |||
| 40 | 1,099,511,627,776 | ~1,000,000,000,000 | 1TB, 1024^4 |
* 1 byte = 8 bits
* 1 kb = kilobit = 1000 bits = kbit
* 1 kB = kilobyte = 1000 bytes
* 1 KB = kibibyte = 1024 bytes = 2^10 bytes = KiB = KBytes
Java Data Type Conversion
int to String:
String s = Integer.toString( 123 );
boolean to String:String s = String.valueOf( true );
String to int:int i = Integer.parseInt( "123" )
Java Random Number
Generate a random number between rndMin and rndMax inclusively:
int n = rndMin + (int)(Math.random() * ((rndMax - rndMin) + 1));
Java Hello World
hello.java: (filename must be hello.java)
> java hello
public class hello {
public static void main( String[] args ) {
System.out.println( "Hello World" );
}
}
> javac hello.java> java hello
HTML Input Style
<style>
input {
border: 1px solid #c0c0c0;
outline: 0;
border-radius: 5px;
height: 25px;
width: 275px;
}
</style>
<input placeholder="Input here" />
HTML Table Style
table.title, table.title th, table.title td {
border-collapse:collapse;
border:1px solid;
}
HTML URL Links Style
div.title a:link, a:visited {
color: #FFFF00;
text-decoration: none;
}
div.title a:hover, a:active {
color: #FFFF00;
text-decoration: underline;
}
How to create a virtual server for Amazon Web Services?
This is a quick start to create a virtual server for Amazon Web Services (AWS). This virtual server will contain Apache web server, PHP and Mysql.
1. Sign Up
You need a credit card to sign up AWS, there is a one year free service for a basic plan. However, if your usage exceeded the plan, you will be charged.
http://aws.amazon.com
2. Login to AWS Management Console
You may need to set up an account before login, but i will skip this part.
https://console.aws.amazon.com
3. Create New Instance
(Reference: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-instance_linux.html)
a. Go to EC2 or this link: https://console.aws.amazon.com/ec2/v2/home
a1. You may change the location of the server at the right-top corning
b. Click "Launch Instance"
c. Select Ubuntu Server 14.04 LTS (HVM), SSD Volume Type
d. Configure Instance Details: Check: "Protect against accidental termination"
("Shutdown Behavior" should be stopped. When you run "shutdown" command within the system, the instance will stop. But it is recommended to stop the instance by EC2 Management Console)
e. Configure Security Group:
e1. Change "Security group name" and "Description" (Suggested: SSH-HTTP-HTTPS)
e2. Set SSH Source to "My IP" (Experimental)
e3. Click "Add Rule" and select HTTP
e4. Click "Add Rule" and select HTTPS (if you need https)
f. Click "Review and Launch"
g. Click "Launch"
h. Select "Create a new key pair" and input "Key pair name" (any name works, i use a name that can identify the instance)
i. Click "Download Key Pair" (this .pem file is the private key that used to connect to the server, make sure you download this file and store in a save place)
j. Click "Launch Instance"
k. Click "View Instances"
l. Wait a few minutes and refresh until the "Status Checks" shows "2/2 checks passed"
m. Now, your server is running!
n. Click "Elastic IPs", click "Allocate New Address", click "Yes, Allocate", an IP address will be created soon.
o. Select the IP address row, click "Associate Address", select your instance, click "Associate". You can use the Elastic IP to refer to your web site. (Important: make sure an Elastic IP is associated with something (an instance), or AWS will charge you)
p. At top-right of the page, select YOUR NAME and then "Billing & Cost Management". Add the billing Alert.
4. Connect to the server
I would like to connect to the server using PuTTY. But you can use any ssh client to connect, even using the AWS build-in(?) java applet. (Reference: Connect to your instance)
(Reference: Connect from Windows Using PuTTY)
a. Download and Install PuTTY
b. Open PuTTYgen
c. Make sure "Type of key to generate" is "SSH-2 RSA"
d. Click "Load" and select the .pem file created at step 3k.
e. Click "Save private key", click "Yes" for the passphrase warning, save as a .ppk file. (It is still the private key, but PuTTY use this .ppk format)
f. Open PuTTY
g. Input "Host Name" ubuntu@public_dns_name (public_dns_name is the Public DNS of the new server, you can also use the Public IP)
h. "Connection type" selects "SSH"
i. Go to "Category" -> "Connection" -> "SSH" -> "Auth", Input "Private key file for authentication" to the .ppk file
j. Click "Open" to connect!
If you are using Linux, do this:
> chmod go-r your.pem
> chmod u-w your.pem
To Login:
> ssh -i your.pem ubuntu@public_dns_name
5. Install Apache and PHP
(Reference: Installing a LAMP Web Server)
> sudo apt-get update
> sudo apt-get upgrade
> sudo apt-get install apache2
> sudo apt-get install mysql-server
(Input mysql root password)
> sudo apt-get install php5 libapache2-mod-php5
This section is just for reference:
> sudo yum update -y
> sudo yum groupinstall -y "Web Server" "MySQL Database" "PHP Support"
> sudo yum install -y php-mysql
> sudo service httpd start
Set Apache web server to start at system boot:
> sudo chkconfig httpd on
The default html files are place at /var/www/html/
Set permission for ec2-user (and all users in www group) to write to the directory:
> sudo groupadd www
> sudo usermod -a -G www ec2-user
> sudo chown -R root:www /var/www
> sudo chmod 2775 /var/www
> find /var/www -type d -exec sudo chmod 2775 {} +
> find /var/www -type f -exec sudo chmod 0664 {} +
ec2-user is not in www group in the current seesion, you need to re-login again now.
Verify ec2-user is in www group:
> groups
Test the web server:
> echo "<?php phpinfo(); ?>" > /var/www/html/phpinfo.php
Open browser: http://public_dns_name/phpinfo.php
Delete the test file after test:
> rm /var/www/html/phpinfo.php
6. Running Mysql
> sudo service mysqld start
> sudo chkconfig mysqld on
> sudo mysql_secure_installation
- Enter the current and new password, "Y" for all the questions
Test mysql server:
> mysql -u root -p
1. Sign Up
You need a credit card to sign up AWS, there is a one year free service for a basic plan. However, if your usage exceeded the plan, you will be charged.
http://aws.amazon.com
2. Login to AWS Management Console
You may need to set up an account before login, but i will skip this part.
https://console.aws.amazon.com
3. Create New Instance
(Reference: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-instance_linux.html)
a. Go to EC2 or this link: https://console.aws.amazon.com/ec2/v2/home
a1. You may change the location of the server at the right-top corning
b. Click "Launch Instance"
c. Select Ubuntu Server 14.04 LTS (HVM), SSD Volume Type
d. Configure Instance Details: Check: "Protect against accidental termination"
("Shutdown Behavior" should be stopped. When you run "shutdown" command within the system, the instance will stop. But it is recommended to stop the instance by EC2 Management Console)
e. Configure Security Group:
e1. Change "Security group name" and "Description" (Suggested: SSH-HTTP-HTTPS)
e2. Set SSH Source to "My IP" (Experimental)
e3. Click "Add Rule" and select HTTP
e4. Click "Add Rule" and select HTTPS (if you need https)
f. Click "Review and Launch"
g. Click "Launch"
h. Select "Create a new key pair" and input "Key pair name" (any name works, i use a name that can identify the instance)
i. Click "Download Key Pair" (this .pem file is the private key that used to connect to the server, make sure you download this file and store in a save place)
j. Click "Launch Instance"
k. Click "View Instances"
l. Wait a few minutes and refresh until the "Status Checks" shows "2/2 checks passed"
m. Now, your server is running!
n. Click "Elastic IPs", click "Allocate New Address", click "Yes, Allocate", an IP address will be created soon.
o. Select the IP address row, click "Associate Address", select your instance, click "Associate". You can use the Elastic IP to refer to your web site. (Important: make sure an Elastic IP is associated with something (an instance), or AWS will charge you)
p. At top-right of the page, select YOUR NAME and then "Billing & Cost Management". Add the billing Alert.
4. Connect to the server
I would like to connect to the server using PuTTY. But you can use any ssh client to connect, even using the AWS build-in(?) java applet. (Reference: Connect to your instance)
(Reference: Connect from Windows Using PuTTY)
a. Download and Install PuTTY
b. Open PuTTYgen
c. Make sure "Type of key to generate" is "SSH-2 RSA"
d. Click "Load" and select the .pem file created at step 3k.
e. Click "Save private key", click "Yes" for the passphrase warning, save as a .ppk file. (It is still the private key, but PuTTY use this .ppk format)
f. Open PuTTY
g. Input "Host Name" ubuntu@public_dns_name (public_dns_name is the Public DNS of the new server, you can also use the Public IP)
h. "Connection type" selects "SSH"
i. Go to "Category" -> "Connection" -> "SSH" -> "Auth", Input "Private key file for authentication" to the .ppk file
j. Click "Open" to connect!
If you are using Linux, do this:
> chmod go-r your.pem
> chmod u-w your.pem
To Login:
> ssh -i your.pem ubuntu@public_dns_name
5. Install Apache and PHP
(Reference: Installing a LAMP Web Server)
> sudo apt-get update
> sudo apt-get upgrade
> sudo apt-get install apache2
> sudo apt-get install mysql-server
(Input mysql root password)
> sudo apt-get install php5 libapache2-mod-php5
This section is just for reference:
> sudo yum groupinstall -y "Web Server" "MySQL Database" "PHP Support"
> sudo yum install -y php-mysql
> sudo service httpd start
Set Apache web server to start at system boot:
> sudo chkconfig httpd on
The default html files are place at /var/www/html/
Set permission for ec2-user (and all users in www group) to write to the directory:
> sudo groupadd www
> sudo usermod -a -G www ec2-user
> sudo chown -R root:www /var/www
> sudo chmod 2775 /var/www
> find /var/www -type d -exec sudo chmod 2775 {} +
> find /var/www -type f -exec sudo chmod 0664 {} +
ec2-user is not in www group in the current seesion, you need to re-login again now.
Verify ec2-user is in www group:
> groups
Test the web server:
> echo "<?php phpinfo(); ?>" > /var/www/html/phpinfo.php
Open browser: http://public_dns_name/phpinfo.php
Delete the test file after test:
> rm /var/www/html/phpinfo.php
6. Running Mysql
> sudo service mysqld start
> sudo chkconfig mysqld on
> sudo mysql_secure_installation
- Enter the current and new password, "Y" for all the questions
Test mysql server:
> mysql -u root -p
HTML5 Hello World
Hello World Template for HTML5:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>HTML 5</title>
<script type="text/javascript">
window.addEventListener( "load", eventWindowLoaded, false );
function eventWindowLoaded() {
var theCanvas = document.getElementById( "canvas1" );
var context = theCanvas.getContext( "2d" );
context.fillText("Hello World!", 100, 50 );
}
</script>
</head>
<body>
<canvas id="canvas1" width="500" height="300">
Your browser does not support HTML5 Canvas.
</canvas>
</body>
</html>
How to programmatically add a button in VB.NET?
Add the button:
Button click event:
Dim btnAdd As New Button
btnAdd.Text = "Text"
AddHandler btnAdd.Click, AddressOf Me.btnAdd_Click
Me.Controls.Add(btnAdd)
Button click event:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim clickButton As Button = CType(sender, System.Windows.Forms.Button)
MsgBox(clickButton.Text)
End Sub
3 ways to apply Stylesheet
1. External Style Sheet:
2. Internal Style Sheet:
3. Inline Styles:
Reference:
http://www.w3schools.com/css/css_howto.asp
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
2. Internal Style Sheet:
<head>
<style>
body {
background-color: black;
}
</style>
</head>
3. Inline Styles:
<p style="color:red;">Red in color</p>
Reference:
http://www.w3schools.com/css/css_howto.asp
jQuery Quick Start
This is an easy way to set up your html page for jQuery.
hello.html:
hello.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
$( document ).ready( function() {
alert( 'hello world' );
});
</script>
</head>
<body>
<p>Hello World</p>
</body>
</html>
PHP Paginating template
This template gets a "page" of records from database, and then shows the links to navigate to other pages.
Install:
paginate.php
Install:
- Install PHP Mysql Library
- Copy paginate.php
- Modify paginate.php to match your database table
paginate.php
<?php
include_once( 'db.php' );
$recordPerPage = 10;
// Get page index
if ( isset( $_GET[ 's' ] ) && is_numeric( $_GET[ 's' ] ) ) {
$start = $_GET[ 's' ];
} else {
$start = 0;
}
// Get total number of pages
if ( isset( $_GET[ 'p' ] ) && is_numeric( $_GET[ 'p' ] ) ) {
$pages = $_GET[ 'p' ];
} else {
$sql = sprintf( "SELECT COUNT(site) as count FROM site;" );
$result = $db->query( $sql );
$row = $result->fetch_assoc();
$recordCount = $row[ 'count' ];
if ( $recordCount > $recordPerPage ) {
$pages = ceil( $recordCount / $recordPerPage );
} else {
$pages = 1;
}
}
$sql = sprintf( "SELECT * FROM site LIMIT %s, %s;", $start, $recordPerPage );
$result = $db->query( $sql );
echo '<table border="1">';
echo '<tr><th>Site</th></tr>';
$bg = '#cccccc';
while ( $row = $result->fetch_assoc() ) {
$bg = ( $bg=='#cccccc' ? '#ffffff' : '#cccccc' );
echo sprintf( '<tr><td bgcolor="%s">%s</td></tr>', $bg, $row[ 'site' ] );
}
echo '</table>';
if ( $pages > 1 ) {
echo '<p>';
$currentPage = ( $start/$recordPerPage ) + 1;
if ( $currentPage != 1 ) {
echo sprintf( '<a href="?s=%s&p=%s">Previous</a> ', ($start - $recordPerPage), $pages );
}
for ( $i=1; $i<=$pages; $i++ ) {
if ( $i != $currentPage ) {
echo sprintf( '<a href="?s=%s&p=%s">%s</a> ', $recordPerPage * ( $i-1 ), $pages, $i );
} else {
echo $i . ' ';
}
}
if ( $currentPage != $pages ) {
echo sprintf( '<a href="?s=%s&p=%s">Next</a>', $start + $recordPerPage, $pages );
}
echo '</p>';
}
Mysql MyISAM vs InnoDB
Advantages of MyISAM:
Advantages of InnoDB:
- Handle SELECT and INSERT very quickly
- Need less disk space
- Support FULLTEXT indexes
Advantages of InnoDB:
- Handle UPDATE quickly
- Can handle transactions (low-level locking)
- Support foreign key constraints
PHP file uploads
Install:
php.ini:
Check the following 3 variables.
upload.php:
- Check php.ini variables
- Copy upload.php
php.ini:
Check the following 3 variables.
;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;
; Whether to allow HTTP file uploads.
; http://php.net/file-uploads
file_uploads = On
; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
; http://php.net/upload-tmp-dir
upload_tmp_dir = "c:/wamp/tmp"
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 2M
upload.php:
<?php
$uploadPath = './';
if ( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ) {
if ( isset( $_FILES[ 'upload' ] ) ) {
$allowed = array( 'image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/x-png' );
if ( in_array( $_FILES[ 'upload' ][ 'type' ], $allowed ) ) {
if ( move_uploaded_file( $_FILES[ 'upload' ][ 'tmp_name' ], $uploadPath . $_FILES[ 'upload' ][ 'name' ] ) ) {
echo '<p>File uploaded.</p>';
}
} else {
echo '<p>Please upload a jpeg or png image.</p>';
}
}
if ( $_FILES[ 'upload' ][ 'error' ] > 0 ) {
echo '<p>The file could not be uploaded because:<br />';
switch ( $_FILES[ 'upload' ][ 'error' ] ) {
case 1:
echo 'The file exceeds the upload_max_filesize setting in php.ini.';
break;
case 2:
echo 'The file exceeds the MAX_FILE_SIZE setting in the HTML form.';
break;
case 3:
echo 'The file was only partially uploaded.';
break;
case 4:
echo 'No file was uploaded.';
break;
case 6:
echo 'No temporary folder was available.';
break;
case 7:
echo 'Unable to write to the disk.';
break;
case 8:
echo 'File upload stopped.';
break;
default:
echo 'A system error occurred.';
break;
}
echo '</p>';
if ( file_exists( $_FILES[ 'upload' ][ 'tmp_name' ] ) && is_file( $_FILES[ 'upload' ][ 'tmp_name' ] ) ) {
unlink( $_FILES[ 'upload' ][ 'tmp_name' ] );
}
}
}
?>
<form enctype="multipart/form-data" action="" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="524288" />
<fieldset>
<legend>Select a JPEG or PNG image of 512KB or smaller to be uploaded:</legend>
<p>File: <input type="file" name="upload" /></p>
</fieldset>
<input type="submit" name="submit" value="Upload" />
</form>
PHP echo vs print
Advantages of echo:
Advantages of print:
Reference:
http://stackoverflow.com/questions/234241/how-are-echo-and-print-different-in-php
- Faster
- Can take multiple parameters (separated by comma)
Advantages of print:
- Can use as a function (have a return value)
- Can take multiple parameters
Reference:
http://stackoverflow.com/questions/234241/how-are-echo-and-print-different-in-php
PHP Sessions vs Cookies
Advantages of Sessions:
Advantages of Cookies:
In general, if the data is small, or need to store for a long duration, use cookies. Otherwise, use sessions.
- More secure (data is saved on the server)
- Can store more data
Advantages of Cookies:
- Easier to program
- Lower server workload
- Last longer
In general, if the data is small, or need to store for a long duration, use cookies. Otherwise, use sessions.
PHP Standard Library
Only one function now, hoping to add more later.
Functions:
stdlib.lib.php:
Functions:
- Get http parameters
stdlib.lib.php:
<?php
function http_request( $name ) {
if ( isset( $_REQUEST[ $name ] ) ) {
return mysql_real_escape_string( $_REQUEST[ $name ] );
}
return '';
}
?>
PHP authentication template
This is a basic PHP authentication template included:
Install:
login.lib.php:
2 functions, one for redirect page, one for checking username and password.
login.php:
Perform the login action using session.
loginPage.php:
LogoutPage.php:
index.php:
Sample of normal pages, use session variable to check if it is login or not.
loginCheck.php:
Include this file to all protected pages.
mustLoginPage.php:
Sample of protected page:
- Login page
- Logout page
- Normal page (check if user login or not)
- Protected page (must be login to view)
Install:
- Install PHP Standard Library
- Install PHP Mysql Library
- Copy all the following files.
login.lib.php:
2 functions, one for redirect page, one for checking username and password.
<?php
// Call before write anything on the html page
function redirectPage( $page = 'index.php' ) {
$url = 'http://' . $_SERVER[ 'HTTP_HOST' ] . dirname( $_SERVER[ 'PHP_SELF' ] );
$url = rtrim( $url, '/\\' ) . '/' . $page;
header( "Location: $url" );
exit();
}
function checkLogin( $dbc, $username, $password ) {
$errors = array();
if ( empty( $username ) ) {
$errors[] = 'Please input the username.';
} else {
$u = trim( $username );
}
if ( empty( $password ) ) {
$errors[] = 'Please input the password.';
} else {
$p = $password;
}
if ( empty( $errors ) ) {
include_once( 'db.php' );
$sql = "SELECT * FROM user WHERE username='$username' AND password='$password';";
$result = $dbc->query( $sql );
if ( $result->num_rows == 1 ) {
$row = $result->fetch_assoc();
return array( true, $row );
} else {
$errors[] = 'Username and password do not match.';
}
}
return array( false, $errors );
}
login.php:
Perform the login action using session.
<?php
include_once( 'stdlib.lib.php' );
include_once( 'db.php' );
include_once( 'login.lib.php' );
$username = http_request( 'username' );
$password = http_request( 'password' );
list( $isLoginOk, $data ) = checkLogin( $db, $username, $password );
if ( $isLoginOk ) {
// set session
session_start();
$_SESSION[ 'userid' ] = $data[ 'id' ];
redirectPage();
} else {
$errors = $data;
}
include( 'loginPage.php' );
loginPage.php:
<?php
if ( isset( $errors ) && !empty( $errors ) ) {
echo '<h1>Error!</h1>';
echo '<p>The following error(s) occurred:<br />';
foreach ( $errors as $msg ) {
echo " - $msg<br />";
}
echo '</p><p>Please try again.</p>';
}
?>
<h1>Login</h1>
<form action="login.php" method="post">
<p>Username: <input type="text" name="username" size="20" /></p>
<p>Password: <input type="password" name="password" size="20" /></p>
<p><input type="submit" name="submit" value="Login" /></p>
</form>
LogoutPage.php:
<?php
session_start();
if ( !isset( $_SESSION[ 'userid' ] ) ) {
echo '<p>You are already logged out!</p>';
} else {
$_SESSION = array();
session_destroy();
echo '<p>You are now logged out!</p>';
}
?>
<a href="index.php">Home</a>
index.php:
Sample of normal pages, use session variable to check if it is login or not.
<?php
session_start();
if ( isset( $_SESSION[ 'userid' ] ) ) {
echo "<p>You are logged in! (userid = {$_SESSION[ 'userid' ]})</p>";
echo '<a href="logoutPage.php">Logout</a>';
} else {
echo '<p>You are not logged in.</p>';
echo '<a href="loginPage.php">Login</a>';
}
?>
<p><a href="mustLoginPage.php">You have to log in to go to this page.</a></p>
loginCheck.php:
Include this file to all protected pages.
<?php
session_start();
if ( !isset( $_SESSION[ 'userid' ] ) ) {
include_once( 'login.lib.php' );
redirectPage( 'loginPage.php' );
}
?>
mustLoginPage.php:
Sample of protected page:
<?php
include_once( 'loginCheck.php' );
?>
<h1>Logged in</h1>
<p>You are now logged in! (userid = <?=$_SESSION[ 'userid' ]?>)</p>
<p><a href="index.php">Home</a></p>
<p><a href="logoutPage.php">Logout</a></p>
PHP Mysql Library
A simple mysql library, each time I need the mysql from php, I just include it and everything ready to go.
Each time you include this library, it will connect to the mysql database. You can use $db as the link identifier. I sometimes add all the project related database functions under db.php, it makes the code easier to maintenance.
Usage:
Install:
db.php:
config.ini.php:
Each time you include this library, it will connect to the mysql database. You can use $db as the link identifier. I sometimes add all the project related database functions under db.php, it makes the code easier to maintenance.
Usage:
include_once( 'db.php' );
Include the file and use $db as the link identifier.Install:
- Copy db.php and config.ini.php.
- Set the connection parameters in config.ini.php
db.php:
<?php
// Can use $db for mysqli function after included this file
include_once( 'config.ini.php' );
$db = @mysqli_connect( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME )
or die( 'Could not connect to database: ' . mysqli_connect_error() );
mysqli_set_charset( $db, 'utf8' );
/*
* Database functions used in this specified project
*/
function foo() {
global $db;
$sql = sprintf( "SELECT * FROM user WHERE id='%s';", 1 );
$result = $db->query( $sql );
if ( $result->num_rows == 1 ) {
$row = $result->fetch_assoc();
// do something for exactly one record found.
}
while ( $row = $result->fetch_assoc() ) {
// do something for each record.
}
}
?>
config.ini.php:
<?php
define( 'DB_HOST', 'localhost' );
define( 'DB_USER', 'root' );
define( 'DB_PASSWORD', '' );
define( 'DB_NAME', 'test' );
?>
Subscribe to:
Comments (Atom)