varemenos
3/29/2012 - 3:51 PM

PHP - Database connection and query

PHP - Database connection and query

<?php
	// db info
	$db_host = 'localhost'; // local only connection
	$db_port = 3306; // default mysql port
	$db_database = 'db_user'; // database username

	// initiate dns string
	$dns = "mysql:host=$db_host;port=$db_port;dbname=$db_database";

	// create database object or close connection
	try{
		$db = new PDO(
			// Database Information
			$dns,
			// Database User Information
			'db_name',
			// Database User Password
			'db_pass',
			// set collation to utf8
			// without this, PHP cant display greek characters properly
			array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
		);
	}catch(PDOException $e){
		print '<h4>' . $e->getMessage() . '</h4>';
	}

	// once you have your database object, unset database connection info
	unset(
		$db_host,
		$db_port,
		$db_database,
		$dns
	);

	// prepare query
	$statement = $db->prepare("SELECT * FROM table WHERE id= ?");
	// execute query
	$statement->execute(array($id));

	// 1 result per time
	while($result = $statement->fetchObject()){
	}

	// or

	// all results at once
	$results = $statement->fetchAll();
?>