Category Archives: programming

Way to insert CSS

1. Attached style sheet

1
2
3
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>

2. Internal

1
2
3
4
5
<head>
<style>
body {color:red;font:arial}
</style>
</head>

3. Inline

1
<p style="color:red;font:arial">Content</p>

PHP Data Object (PDO)

An object in PHP to manage data

PDO

  • exec
  • prepare
  • query
  • lastInsertId

PDOStatement

  • execute
  • fetch
  • fetchAll
  • fetchColumn
  • fetchObject
  • rowCount

PDOException

  • getMessage (return string)

Some sample code:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); //establish connection
$dbh = null; //close connection
 
//insert by prepare statement
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
 
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
 
//get result
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE ?");
 
if ($stmt->execute(array("%$_GET[name]%"))) {
  while ($row = $stmt->fetch()) {
    print_r($row);
  }
}

Learn CodeIgniter

What you should do and learn

  • Download latest version of codeigniter
  • Set config/autoload.php to automatically load important and common helpers/library etc
    • helper – form, url
    • library – database
  • Good to start following tutorial under “General Topics” and “Tutorial”
  • Create a new controller (can copy from sample controller named welcome). Edit the class name, change the view to call. Class name should start with capital letter.
  • Create a new view and call from the controller
  • Change the config/routes.php to set as default controller
  • Learn how to pass data from controller to view
  • This is the way to load view, controller, helper etc
    • $this->load->view(‘aname’);
    • $this->load->helper(‘aname’);
    • $this->load->model(‘aname’);
  • Create a form in the view
    • use form_open(‘controller/function_name’) and form_close() function
  • Try pass a value via the form
    • to get data in controller use $arecord = $this->input->post(‘fieldname’);

DB Activities

  • set up DB config in config/database.php
  • set config/autoload.php to auto load database library
  • learn to use standard query and active record to insert/retrieve data from database
    • standard query – $query = $this->db->query(‘SELECT * FROM my_table’);
    • active record
      • $this->db->select(‘field1, field2’);
      • $query = $this->db->get(‘my_table’);  //use this to get all records and fields in a table.
  • retrieve the data result
  • controller to get result from model,
    • $this->load->model(‘model_name’,’avar’); //avar is variable to the model
    • function (in controller) to get the result by calling the function in model – $result = $this->avar->function_name();
    • function in model must do the query and return the result (to be retrieved by other functions from controller)
  • controller to pass the result to view as usual $this->load->view(‘view_name’, $data);
  • to loop the result set in view using foreach ($result as $list): echo $list[‘field_name’]
  • more with active record – complete CRUD and more
  • //save data to db (must load db class)
  • $data = array(
    ‘title’ => ‘My title’ ,
    ‘name’ => ‘My Name’ ,
    ‘date’ => ‘My date’
    );
    $this->db->insert(‘mytable’, $data);

Codeigniter user guide

PHP script to check no record found

If no record found for a particular condition, you can display message to the users. The code as below

1
2
3
4
5
6
7
8
$sql="SELECT * FROM user WHERE email = '$email'";  
$result=mysql_query($sql);
$num=mysql_numrows($result);
 
if ($num > 0)
  echo "found something";
else
  echo "no record found";

PHP automatic run without cron job

If you don’t have a cron in your serveer, you can use this script to run a daily cron job.

Prepare a writeable file with a date inside and name it as ‘crondate.php’. The file should contain only date in one line.

2012-09-22

Run this function in a file on your website. It will check whether today’s date and date in file are different.
If yes, then it will call any function you want to run daily

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function cron_daily_check() {
	//read file to get last date
	$filename = 'crondate.php';
	$handle = fopen($filename, 'r');
	$filedate = fgets($handle);
 
	//if date different, run a function and update file date
	if (date('Y-m-d') != $filedate) {	 
		/***** call any function or script to execute here ****/
 
		//write new date
		$fh = fopen($filename, 'w') or die("Failed to open file.");
		$stringData = date('Y-m-d');
		fwrite($fh, $stringData);
		fclose($fh);
	}		
}

Should we store datetime or unix timestamp in MySQL?

Timestamps in MySQL generally used to track changes to records, and are updated every time the record is changed. If you want to store a specific value you should use a datetime field.

If you meant that you want to decide between using a UNIX timestamp or a native MySQL datetime field, go with the native format. You can do calculations within MySQL that way ("SELECT DATE_ADD(my_datetime, INTERVAL 1 DAY)") and it is simple to change the format of the value to a UNIX timestamp ("SELECT UNIX_TIMESTAMP(my_datetime)") when you query the record if you want to operate on it with PHP.

Timestamp (both PHP ones and MySQL’s ones) are stored using 32 bits (i.e. 4 bytes) integers ; which means they are limited to a date range that goes from 1970 to 2038.

DATETIME don’t have that limitation — but are stored using more bytes (8 bytes, if I’m not mistaken)

After, between storing timestamps as seen by PHP, or timestamps as seen by MySQL :

using PHP timestamps means manipulations are easier from PHP — see Date/Time Functions

using MySQL’s timestamps means manipulations are easier from MySQL — see 11.6. Date and Time Functions

And, for more informations between MySQL’s TIMESTAMP and DATETIME datatypes, see 10.3.1. The DATETIME, DATE, and TIMESTAMP Types

source:

http://stackoverflow.com/questions/2533767/mysql-whats-the-best-to-use-unix-timestamp-or-datetime

http://stackoverflow.com/questions/409286/datetime-vs-timestamp

iPhone CSS

This CSS to be used to display website nicely on iPhone. Not tested on Android and other smart phones.

Add this code on top of what ever css style you have.

1
2
3
4
5
<!-- Start iPhone -->
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
<link rel="apple-touch-icon" href="/images/money.png" />
<link media="only screen and (max-device-width: 480px)" href="/iphone.css" type= "text/css" rel="stylesheet" />
<!-- End iPhone -->

In iphone.css file, just write the css code. For example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
body,td,input,textarea,select,label { font-size: 6em;}
mainlink {font-size:3em; }
body {
background-color: #fff;
}
 
.header, .footer {
width: 100%;
}
 
.sidebar {
display: none;
}
 
.mainlink {	color:#FFFFFF; font-size:150%; }
 
.mainlink A:link {text-decoration: none; color:#FFFFFF; }
 
.mainlink A:visited {text-decoration: none; color:#FFFFFF; }
 
.mainlink A:active {text-decoration: none; color:#FFFFFF; }
 
.mainlink A:hover {text-decoration: underline; color:#FFFF66; }

Database config for localhost and server

To easily toggle database config for localhost and server, you can simply check whether you are accessing the local or server.

1
2
3
4
5
6
7
8
9
10
11
12
13
if (preg_match("/localhost/i", $_SERVER['SERVER_NAME'])) {
define ('DBHOST','localhost');
define ('DBNAME','localdbname'); 
define ('DBUSER','localuser');
define ('DBPASS','localpass');
define ('DEV',TRUE);
} else {
define ('DBHOST','localhost');
define ('DBNAME','serverdbname'); 
define ('DBUSER','serveruser');
define ('DBPASS','serverpass');
define ('DEV',FALSE);
}