<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" ><channel><title>ZenTut</title> <atom:link href="http://www.zentut.com/feed/" rel="self" type="application/rss+xml" /><link>http://www.zentut.com</link> <description>Programming Made Easy</description> <lastBuildDate>Fri, 10 May 2013 16:14:25 +0000</lastBuildDate> <language>en-US</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.5.1</generator> <item><title>PDO Inserting Data into Tables</title><link>http://www.zentut.com/php-pdo/pdo-inserting-data-into-tables/</link> <comments>http://www.zentut.com/php-pdo/pdo-inserting-data-into-tables/#comments</comments> <pubDate>Mon, 06 May 2013 04:24:55 +0000</pubDate> <dc:creator>Zentut Founder</dc:creator> <guid isPermaLink="false">http://www.zentut.com/?page_id=4875</guid> <description><![CDATA[<p>Summary: in this tutorial, we will show you how to insert data into database table using PDO API. The following are steps of how to insert data into a table using PDO: Create a connection to the database by create a new PDO object. Use a SQL INSERT statement to insert the data into the [...]</p><p>The post <a href="http://www.zentut.com/php-pdo/pdo-inserting-data-into-tables/">PDO Inserting Data into Tables</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></description> <content:encoded><![CDATA[<p><strong>Summary</strong>: in this tutorial, we will show you how to insert data into database table using PDO API.</p><p>The following are steps of how to insert data into a table using PDO:</p><ul><li><a title="Check it out how to connect to MySQL" href="http://www.zentut.com/php-pdo/pdo-connecting-to-mysql/">Create a connection to the database</a> by create a new <code>PDO </code>object.</li><li>Use a <a title="SQL INSERT statement" href="http://www.zentut.com/sql-tutorial/sql-insert/">SQL INSERT statement</a> to insert the data into the table.</li><li>Call the <code>exec()</code> method of the <code>PDO </code>object to execute the <code>INSERT </code>statement. The <code>exec()</code> method returns the number of rows that were affected on success or return <code>false</code> on failure.</li></ul><h2>PDO Inserting data into a table example</h2><p>We will insert a new department into the <code>departments </code>table of the <code>empdb </code>sample database.</p><p>First, we create a form for creating a new department. The form consists of one text field that accepts department name and a submit button.</p><p><img class="alignnone size-full wp-image-4876" alt="insert department form" src="http://www.zentut.com/wp-content/uploads/2013/05/insert-department-form.gif" width="422" height="104" /></p><p>Second, when we enter a department name and click the <code>Create Department</code> button, the we need to:</p><ul><li><span style="line-height: 13px;">Validate the input by using the <code>filter_var()</code> function. Check it out the <a title="PHP Form" href="http://www.zentut.com/php-tutorial/php-html-form/">PHP HTML form tutorial</a> to learn how to use the <code>filter_var()</code> function to validate form&#8217;s data.</span></li><li>Check the input department name to see if it already exists by <a title="PHP PDO querying data" href="http://www.zentut.com/php-pdo/pdo-querying-data/">querying data</a> from the <code>departments</code> table. If the department already exists, we display an error message. Otherwise we insert the new department and display a success message.</li></ul><p>To insert a new department into the <code>departments </code>table, we construct an <code>INSERT </code>statement and call the <code>exec()</code> method of the <code>PDO</code> object.</p><h3>PDO Inserting data into table script</h3><p>We put the following code at the beginning of the script file:</p><pre class="brush: php; gutter: true; first-line: 1">&lt;?php

$msg = '';
$result = false;

if(isset($_POST['submit'])){

	require_once 'dbconfig.php';

	$dsn = "mysql:host=$host;dbname=$db";
	try {
		// create database connection
		$dbh = new PDO($dsn, $username, $password);

		// create new department
		$result = create_dept();

		// display the insert form again
		display_form();

	} catch (PDOException $e) {
		echo $e-&gt;getMessage();
	}
}
else{
	// display insert form
	display_form();
}</pre><p>If the form is not submitted, we display it. If it is submitted, we perform the logic as described above. The following are the functions for the each step:</p><p>Validate department function:</p><pre class="brush: php; gutter: true; first-line: 1">/**
 * validate department
 * @return department name on success or false on failure
 */
function validate_dept(){
	global $msg;

	$dept_name = $_POST['department'];

	if($dept_name != ''){
		$dept_name = filter_var($dept_name,FILTER_SANITIZE_STRING);
		return $dept_name;
	}else{
		$msg =  'Please enter the department name';
		return false;
	}
}</pre><p>Check department exists function:</p><pre class="brush: php; gutter: true; first-line: 1">/**
 * Check if a department exists
 * @param string $dept_name department name
 * @return NULL|boolean return true if department exists, false
 *         if it does not exist, and NULL on failure
 */
function dept_exist($dept_name){
	global $msg, $dbh;

	$sql_select = "SELECT department_no
		       FROM departments
		       WHERE name = " . $dbh-&gt;quote($dept_name) . "
		       LIMIT 1";

	$stmt = $dbh-&gt;query($sql_select);

	if($stmt === false){
		$msg = 'Error querying departments table';
		return NULL;
	}

	$r = $stmt-&gt;fetch(PDO::FETCH_ASSOC);

	if($r !== false){
		$msg = "Department with name $dept_name already exists.";
		return true;
	}else
		return false;

}</pre><p>Insert a new department function:</p><pre class="brush: php; gutter: true; first-line: 1">/**
 * insert a new department table
 * @param string $dept_name department name
 * @return boolean return true on success or false on failure
 */
function insert_dept($dept_name){
	global $dbh, $msg;
	// construct SQL insert statement
	$sql_insert = "INSERT INTO departments(name)
				   VALUES(" . $dbh-&gt;quote($dept_name) .")";

	if($dbh-&gt;exec($sql_insert) === false){
		$msg = 'Error inserting the department.';
		return false;
	}else{
		$msg = "The new department $dept_name is created";
		return true;
	}
}</pre><p>Create new department function that includes the logic of validating, checking for existence and inserting :</p><pre class="brush: php; gutter: true; first-line: 1">/**
 * insert new department
 * @param string $msg message 
 * @return boolean return true on success, false on failure
 */
function create_dept(){
	// validate department
	$dept_name = validate_dept();

	if($dept_name){
		// check if the department exists
		if(!dept_exist($dept_name)){
			// insert the department
			return insert_dept($dept_name);
		}		
	}
	return false;
}</pre><p>Display error or success message function:</p><pre class="brush: php; gutter: true; first-line: 1">/**
 * display message based on message type
 * @param string $msg message to display
 * @param boolean $type true: success message, 
 * 			false: failed message
  */
function display_msg($msg,$type){
	 $type === true ? $cssClass = "alert-success" :
	 		  $cssClass = "alert-error";
	 if($msg != ''){
	 	?&gt;
	 		&lt;div class="alert &lt;?php echo $cssClass; ?&gt;"&gt;
				&lt;?php echo $msg; ?&gt;
			&lt;/div&gt;
	 	&lt;?php 
	 }
}</pre><p>Display form function:</p><pre class="brush: html; gutter: true; first-line: 1">/**
 * display the create new department form
 */
function display_form(){
	global $msg, $result;
	?&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Create Department&lt;/title&gt;
&lt;link href="css/bootstrap.min.css" rel="stylesheet"&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;div class="container" style="margin-top:20px;"&gt;
	&lt;form action = "&lt;?php $_SERVER['PHP_SELF']?&gt;" 
			 method = "POST"
			 class = "form-horizontal"&gt;
		&lt;?php display_msg($msg,$result); ?&gt;

		&lt;div class="control-group"&gt;
			&lt;label for="department" class="control-label"&gt;Department:&lt;/label&gt;
			&lt;div class="controls"&gt;
				&lt;input type="text" 
				       name="department" 
				       id="department"
				       class="input-xlarge"
				       placeholder="Enter department name" /&gt;
			&lt;/div&gt;
		&lt;/div&gt;
		&lt;div class="control-group"&gt;
			&lt;div class="controls"&gt;
				&lt;input name="submit" 
				       type="submit" 
				       value="Create Department"
				       class="btn btn-primary" /&gt;
			&lt;/div&gt;
		&lt;/div&gt;		

	&lt;/form&gt;
	&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
	&lt;?php
}</pre><p>Testing the form:</p><div id="attachment_4880" class="wp-caption alignnone" style="width: 444px"><a href="http://www.zentut.com/wp-content/uploads/2013/05/PHP-PDO-insert-sales-department.gif" rel="lightbox[4875]" title="PHP PDO Insert Sales Department"><img class="size-full wp-image-4880" title="PHP PDO Insert Sales Department" alt="PHP PDO Insert Sales Department" src="http://www.zentut.com/wp-content/uploads/2013/05/PHP-PDO-insert-sales-department.gif" width="434" height="107" /></a><p class="wp-caption-text">Insert Sales Department</p></div><div id="attachment_4879" class="wp-caption alignnone" style="width: 519px"><a href="http://www.zentut.com/wp-content/uploads/2013/05/PHP-PDO-insert-sales-department-error.gif" rel="lightbox[4875]" title="PHP PDO insert sales department error"><img class="size-full wp-image-4879" title="PHP PDO insert sales department error" alt="Failed to insert Sales department because it already exists" src="http://www.zentut.com/wp-content/uploads/2013/05/PHP-PDO-insert-sales-department-error.gif" width="509" height="161" /></a><p class="wp-caption-text">Failed to insert Sales department because it already exists</p></div><div id="attachment_4878" class="wp-caption alignnone" style="width: 548px"><a href="http://www.zentut.com/wp-content/uploads/2013/05/PHP-PDO-insert-Legal-department.gif" rel="lightbox[4875]" title="PHP PDO insert Legal department"><img class="size-full wp-image-4878" title="PHP PDO insert Legal department" alt="PHP PDO insert Legal department" src="http://www.zentut.com/wp-content/uploads/2013/05/PHP-PDO-insert-Legal-department.gif" width="538" height="169" /></a><p class="wp-caption-text">Insert Legal Department</p></div><div id="attachment_4877" class="wp-caption alignnone" style="width: 509px"><a href="http://www.zentut.com/wp-content/uploads/2013/05/PHP-PDO-insert-Lega-department-success.gif" rel="lightbox[4875]" title="PHP PDO insert Lega department success"><img class="size-full wp-image-4877" title="PHP PDO insert Lega department success" alt="PHP PDO insert Lega department success" src="http://www.zentut.com/wp-content/uploads/2013/05/PHP-PDO-insert-Lega-department-success.gif" width="499" height="166" /></a><p class="wp-caption-text">Legal department created successfully</p></div><p>In this tutorial, we have shown you step by step how to insert data into a database table using PHP PDO.</p><p>The post <a href="http://www.zentut.com/php-pdo/pdo-inserting-data-into-tables/">PDO Inserting Data into Tables</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></content:encoded> <wfw:commentRss>http://www.zentut.com/php-pdo/pdo-inserting-data-into-tables/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>PL/SQL GOTO</title><link>http://www.zentut.com/plsql-tutorial/plsql-goto/</link> <comments>http://www.zentut.com/plsql-tutorial/plsql-goto/#comments</comments> <pubDate>Fri, 03 May 2013 07:06:37 +0000</pubDate> <dc:creator>Zentut Founder</dc:creator> <guid isPermaLink="false">http://www.zentut.com/?page_id=4830</guid> <description><![CDATA[<p>Summary: in this tutorial, you will learn how to use PL/SQL GOTO statement to jump unconditionally to another executable statement in a same PL/SQL block. Introduction to PL/SQL GOTO statement PL/SQL GOTO statement allows you to jump to a specific executable statement in the same execution section of a PL/SQL block. The syntax of the [...]</p><p>The post <a href="http://www.zentut.com/plsql-tutorial/plsql-goto/">PL/SQL GOTO</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></description> <content:encoded><![CDATA[<p><strong>Summary</strong>: in this tutorial, you will learn how to use <strong>PL/SQL GOTO</strong> statement to jump unconditionally to another executable statement in a same PL/SQL block.</p><h2><a href="http://www.zentut.com/wp-content/uploads/2013/05/plsql-goto.png" rel="lightbox[4830]" title="PL/SQL GOTO"><img class="alignright" title="PL/SQL GOTO" alt="PL/SQL GOTO" src="http://www.zentut.com/wp-content/uploads/2013/05/plsql-goto.png" width="256" height="109" /></a>Introduction to PL/SQL GOTO statement</h2><p>PL/SQL <code>GOTO </code>statement allows you to jump to a specific executable statement in the same execution section of a <a title="PL/SQL Block" href="http://www.zentut.com/plsql-tutorial/plsql-block-structure/">PL/SQL block</a>.</p><p>The syntax of the PL/SQL <code>GOTO </code>statement is as follows:</p><pre class="brush: sql; gutter: true; first-line: 1">GOTO label_name</pre><p>Where <code>label_name </code>is a label that defines the target statement. In program, you define a label as follows:</p><pre class="brush: sql; gutter: true; first-line: 1">&lt;&lt;label_name&gt;&gt;</pre><p>The label name is enclosed in double angle brackets ( <code>&lt;&lt;&gt;&gt;</code>).</p><h2>PL/SQL GOTO restrictions</h2><p>There are some restrictions of using the PL/SQL GOTO statement that you should be aware of before using it.</p><p>First, the PL/SQL <code>GOTO</code> statement cannot jump to an <code>IF</code> statement, <code>CASE</code> statement, <code>LOOP</code> statement, or child-block.</p><p>The only way to branch into an <a title="PL/SQL IF statement" href="http://www.zentut.com/plsql-tutorial/plsql-if-statement/">IF statement</a> is through its condition check. This is also applied for the <a title="PL/SQL CASE statement" href="http://www.zentut.com/plsql-tutorial/plsql-case-statement/">CASE statement</a>. In the following example, the <code>GOTO </code>statement tries to jump to inside an <code>IF </code>statement, which is not allowed. As a result, PL/SQL issues an error message.</p><pre class="brush: sql; gutter: true; first-line: 1">BEGIN 
    GOTO goto_inside_if;
    IF v_status = 'COMPLETED'.
      &lt;&lt;goto_inside_if&gt;&gt;
      ...
    ENDIF.
END;</pre><p>The <code>GOTO </code>statement cannot branch to middle of a <a title="PL/SQL FOR loop" href="http://www.zentut.com/plsql-tutorial/plsql-for-loop/">loop</a>:</p><pre class="brush: sql; gutter: true; first-line: 1">BEGIN
  GOTO goto_inside_loop;
  FOR n_day IN 1 .. 7
  LOOP
     &lt;&lt;goto_inside_loop&gt;&gt;
     ...
  END LOOP; 
END;</pre><p>The only way to enter the child-block is through its <code>BEGIN </code>statement. The following example does not comply with this rule, hence causes an error.</p><pre class="brush: sql; gutter: true; first-line: 1">BEGIN
  GOTO inside_child_block;
  ...
  BEGIN
    ...
    &lt;&lt;inside_child_block&gt;&gt;
    ...
  END;
END;</pre><p>Second, you cannot use a <code>GOTO</code> statement to branch from an exception handling section back into the current block. The following example does not comply with this rule, hence it causes an error.</p><pre class="brush: sql; gutter: true; first-line: 1">BEGIN
  --...
  &lt;&lt;back_to_exec&gt;&gt;
  --...
  EXCEPTION.
    --...
    WHEN SOMETHING_WRONG_HAPPENED.
        GOTO back_to_exec;
    --...
END;</pre><p>Third, you cannot use a <code>GOTO</code> statement to jump out of a subprogram. To end a subprogram, you jump to the end of subprogram using the <code>GOTO</code> statement or use a <code>RETURN </code>statement instead.</p><p>Fourth, you cannot use a <code>GOTO</code> statement to branch from one <code>IF</code> clause to another, or from one <code>WHEN</code> clause of a <code>CASE</code> statement to another.</p><p>Fifth, there must be at least one executable statement appears after the target label. If you just want to branch to a target label without doing anything, you use a NULL statement.</p><h2>PL/SQL GOTO examples</h2><p>The following example demonstrates how to use PL/SQL <code>GOTO </code>statement:</p><pre class="brush: sql; gutter: true; first-line: 1">SET SERVEROUTPUT ON SIZE 1000000;
BEGIN 
  GOTO label_1;
  DBMS_OUTPUT.PUT_LINE('Right after the GOTO statement');
  &lt;&lt;label_1&gt;&gt;
  DBMS_OUTPUT.PUT_LINE('It is here!');
END;
/</pre><p>The output of the script is:</p><pre class="brush: text; gutter: false; first-line: 1">It is here!</pre><p>When PL/SQL reaches the <code>GOTO </code>statement, it skips everything and immediately jumps to the target label i.e. <code>label_1 </code>and it displays the message <code>It is here</code></p><p>The PL/SQL <code>GOTO </code>statement has a bad reputation because it makes the code hard to understand and difficult to debug. In general, the PL/SQL <code>GOTO </code>statement should be avoided and replaced by other statements such as <code>IF</code> or <code>CASE </code>statement.</p><p>However, there are some cases that using the <code>GOTO </code>statement can make the program more efficient. See the following example:</p><pre class="brush: sql; gutter: true; first-line: 1">BEGIN
   IF ... THEN
         FOR rec_emp IN cur_emp LOOP
            -- By pass all using GOTO
            GOTO &lt;&lt;exit_now&gt;&gt;
         END LOOP;
         -- a lot of code here
   END IF;
   -- target label
   &lt;&lt;exit_now&gt;&gt; 
   NULL;
END;</pre><p>In the above example, instead of going through a lot of code after the first <a title="PL/SQL FOR loop" href="http://www.zentut.com/plsql-tutorial/plsql-for-loop/">FOR </a>loop statement, we used the <code>GOTO </code>statement to jump to the end of the block that make the code very efficient.</p><p>In this tutorial, you have learned how to use the PL/SQL <code>GOTO </code>statement to branch unconditionally to a target label in the same block.</p><p>&nbsp;</p><p>The post <a href="http://www.zentut.com/plsql-tutorial/plsql-goto/">PL/SQL GOTO</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></content:encoded> <wfw:commentRss>http://www.zentut.com/plsql-tutorial/plsql-goto/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>What is PL/SQL</title><link>http://www.zentut.com/plsql-tutorial/what-is-plsql/</link> <comments>http://www.zentut.com/plsql-tutorial/what-is-plsql/#comments</comments> <pubDate>Thu, 02 May 2013 07:38:29 +0000</pubDate> <dc:creator>Zentut Founder</dc:creator> <guid isPermaLink="false">http://www.zentut.com/?page_id=4766</guid> <description><![CDATA[<p>Summary: in this tutorial, we introduce you to PL/SQL language. We will discuss about PL/SQL history, the language elements and the advantages that PL/SQL brings to the Oracle development. PL/SQL is a Procedural Language (PL) that extends the Structured Query Language (SQL). If you have been programming Pascal or Ada, you will find much familiar [...]</p><p>The post <a href="http://www.zentut.com/plsql-tutorial/what-is-plsql/">What is PL/SQL</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></description> <content:encoded><![CDATA[<p><strong>Summary</strong>: in this tutorial, we introduce you to PL/SQL language. We will discuss about PL/SQL history, the language elements and the advantages that PL/SQL brings to the Oracle development.</p><p>PL/SQL is a Procedural Language (PL) that extends the <a title="Check it out the SQL tutorial if you haven't heard about SQL yet" href="http://www.zentut.com/sql-tutorial/">Structured Query Language</a> (SQL). If you have been programming Pascal or Ada, you will find much familiar syntax in PL/SQL.</p><p>It is difficult to write applications using SQL only because each SQL statement runs independently and has little or no effect on each other. To overcome this limitation, you often have to use other programming languages such as <a title="C Tutorial" href="http://www.zentut.com/c-tutorial/">C</a>/C++, <a title="Perl Tutorial" href="http://www.zentut.com/perl-tutorial/">Perl</a>, <a title="More on PHP" href="http://www.zentut.com/php-tutorial/">PHP</a>, Java, etc., by using standard database interfaces. Oracle supports this approach when you want to develop applications that interact with Oracle databases.</p><p>In addition, Oracle also encourages you to use PL/SQL to work with Oracle databases because PL/SQL brings many advantages.</p><h2>PL/SQL history</h2><p>Oracle introduced PL/SQL (version 1.0) in its Oracle Database product version 6.0 as the scripting language in SQL*Plus and programming language in SQL*Forms 3.</p><p>Since version 7, Oracle did a major upgrade for PL/SQL (version 2.0) that provides more features such as <a title="PL/SQL procedure" href="http://www.zentut.com/plsql-tutorial/plsql-procedure/">procedures</a>, <a title="PL/SQL Function" href="http://www.zentut.com/plsql-tutorial/plsql-function/">functions</a>, <a title="PL/SQL Package" href="http://www.zentut.com/plsql-tutorial/plsql-package/">packages</a>, <a title="PL/SQL Record" href="http://www.zentut.com/plsql-tutorial/plsql-record/">records</a>, collections, and some package extensions.</p><p>Since then many features have been added to PL/SQL such as XML support, preprocessor, file I/O, object-orientation, new statements such as <code>CONTINUE</code>, <code>GOTO</code>, etc. to make it one of the most highly structure programming languages .</p><h2>PL/SQL Advantages</h2><h3>PL/SQL is a highly structured language</h3><p>PL/SQL provides a very expressive syntax that makes it easy for anyone who wants to learn PL/SQL. If you are programming in other languages, you can get familiar with PL/SQL very quickly and understand the intent of the code without difficulty.</p><p>PL/SQL language features include the following elements:</p><ul><li><a title="PL/SQL Variables" href="http://www.zentut.com/plsql-tutorial/plsql-variables/">Variables</a></li><li><a title="Block structure" href="http://www.zentut.com/plsql-tutorial/plsql-block-structure/">Block structure</a>, <a title="PL/SQL Nested Block" href="http://www.zentut.com/plsql-tutorial/plsql-nested-block/">nested block structure</a></li><li>Conditional and sequential statements: <code>IF</code>, <code>CASE</code>, <code>GOTO</code>, <code>CONTINUE </code>and <code>NULL</code></li><li>Loop statements: <code>WHILE </code>loop, <code>FOR </code>loop</li><li>Exception and error handling</li><li>Data types: string, numbers, date &amp; timestamp, boolean and LOB</li><li>Record</li><li>Collection</li><li>Cursor</li><li>Procedures, functions, packages</li><li>Object-orientation features</li><li>Dynamic SQL and dynamic PL/SQL</li></ul><h3>PL/SQL is a portable and standard language for Oracle development</h3><p>Once you develop a PL/SQL program in an Oracle Database, you can move it to the other Oracle Databases without changes, with the assumption that the versions of Oracle database are compatible.</p><h3>PL/SQL is an embedded language</h3><p>PL/SQL programs such as functions and procedures are stored in Oracle database in compiled form. This allows applications or users to share the same functionality stored in Oracle database.</p><p>PL/SQL also allows you to define triggers that can be invoked automatically to response to particular events in associated tables.</p><h3>PL/SQL is a high-performance language inside Oracle Databases</h3><p>Oracle adds many enhancements to the PL/SQL to make it more efficient to interact with Oracle databases.</p><p>The post <a href="http://www.zentut.com/plsql-tutorial/what-is-plsql/">What is PL/SQL</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></content:encoded> <wfw:commentRss>http://www.zentut.com/plsql-tutorial/what-is-plsql/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>PL/SQL Setting Up a Development Environment</title><link>http://www.zentut.com/plsql-tutorial/plsql-setting-up-a-development-environment/</link> <comments>http://www.zentut.com/plsql-tutorial/plsql-setting-up-a-development-environment/#comments</comments> <pubDate>Thu, 02 May 2013 04:56:18 +0000</pubDate> <dc:creator>Zentut Founder</dc:creator> <guid isPermaLink="false">http://www.zentut.com/?page_id=4740</guid> <description><![CDATA[<p>Summary: in this tutorial, we will show you step by step how to download and install Oracle Database for learning and practicing PL/SQL programming in your system. Download and install Oracle Database First, you need go to the Oracle office website and download the Oracle Database. We are going to download Oracle Database 11g Release 2 on Microsoft [...]</p><p>The post <a href="http://www.zentut.com/plsql-tutorial/plsql-setting-up-a-development-environment/">PL/SQL Setting Up a Development Environment</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></description> <content:encoded><![CDATA[<p><strong>Summary</strong>: in this tutorial, we will show you step by step how to download and install Oracle Database for learning and practicing PL/SQL programming in your system.</p><h2>Download and install Oracle Database</h2><p>First, you need go to the <a title="Oracle Official Website" href="http://www.oracle.com/" target="_blank">Oracle office website</a> and <a title="Download Oracle Database" href="http://www.oracle.com/technetwork/database/enterprise-edition/downloads/index.html" target="_blank">download the Oracle Database</a>. We are going to download Oracle Database 11g Release 2 on Microsoft Windows (x64).</p><p>Second, unzip the downloaded files into a folder e.g., C:\setup\Oracle as follows:</p><p><img class="alignnone size-full wp-image-4741" title="Oracle Installation folder" alt="Oracle Installation folder" src="http://www.zentut.com/wp-content/uploads/2013/05/Oracle-Installation-folder.png" width="213" height="132" /></p><p>Third, double click the setup.exe file to start installing Oracle database. You need to follows the steps as described in the following section:</p><h2>Step 1.</h2><p>In this step, you can provide your email to get the updated information on security issues from Oracle.</p><p><img class="alignnone  wp-image-4742" title="install oracle step 1" alt="install oracle step 1" src="http://www.zentut.com/wp-content/uploads/2013/05/install-oracle-step-1.png" width="560" height="420" /></p><h2>Step 2.</h2><p>There are three options in this step as shown in the screenshot. Choose the first one to create and configure database and click <em>Next</em> button.</p><p><img class="alignnone  wp-image-4743" title="install oracle step 2" alt="install oracle step 2" src="http://www.zentut.com/wp-content/uploads/2013/05/install-oracle-step-2.png" width="560" height="420" /></p><h2>Step 3.</h2><p>If you are installing Oracle database in your laptop or desktop, choose the first option, otherwise choose the second one and click the <em>Next</em> button.</p><p><img class="alignnone  wp-image-4744" title="install oracle step 3" alt="install oracle step 3" src="http://www.zentut.com/wp-content/uploads/2013/05/install-oracle-step-3.png" width="560" height="420" /></p><h2>Step 4.</h2><p>This step allows you to enter full database installation folders. You can change the Oracle base folder e.g., c:\app\zentut, other folders be changed accordingly. After that click <em>Next</em> button to go to the next step.</p><p><a href="http://www.zentut.com/wp-content/uploads/2013/05/install-oracle-step-41.png" rel="lightbox[4740]" title="install oracle step 4"><img class="alignnone  wp-image-4761" title="install oracle step 4" alt="install oracle step 4" src="http://www.zentut.com/wp-content/uploads/2013/05/install-oracle-step-41.png" width="560" height="420" /></a></p><h2>Step 5.</h2><p>In this step, Oracle will perform prerequisite checks before installing Oracle database component.</p><p><img title="install oracle step 5" alt="install oracle step 5" src="http://www.zentut.com/wp-content/uploads/2013/05/install-oracle-step-5.png" width="560" height="420" /></p><h2>Step 6.</h2><p>This steps shows you summary information of the previous steps. Click the finish button to start installing Oracle database.</p><p><img class="alignnone  wp-image-4762" title="install oracle step 6" alt="install oracle step 6" src="http://www.zentut.com/wp-content/uploads/2013/05/install-oracle-step-6.png" width="560" height="420" /></p><h2>Step 7.</h2><p>This step copies the files to the corresponding folder and install the Oracle components and services. It takes few minutes to finish so please be patient.</p><p><img class="alignnone  wp-image-4751" title="install oracle step 7" alt="install oracle step 7" src="http://www.zentut.com/wp-content/uploads/2013/05/install-oracle-step-7.png" width="560" height="420" /></p><p>After complete, the installer displays a database Configuration Assistant dialog, click on the Password Management&#8230; button to setup the passwords for different users.</p><p>We need to unlock the SYS, SYSTEM and HR users and set the their corresponding passwords.<br /> <img class="alignnone size-full wp-image-4763" title="install oracle step 7 - DB config assistant" alt="install oracle step 7 - DB config assistant" src="http://www.zentut.com/wp-content/uploads/2013/05/install-oracle-step-7-DB-config-assistant.png" width="557" height="552" /></p><p><img class="alignnone  wp-image-4749" title="install oracle step 7 - DB config assistant - SYS users" alt="install oracle step 7 - DB config assistant - SYS users" src="http://www.zentut.com/wp-content/uploads/2013/05/install-oracle-step-7-DB-config-assistant-SYS-users.png" width="540" height="360" /></p><p><img class="alignnone  wp-image-4748" title="install oracle step 7 - DB config assistant - HR user" alt="install oracle step 7 - DB config assistant - HR user" src="http://www.zentut.com/wp-content/uploads/2013/05/install-oracle-step-7-DB-config-assistant-HR-user.png" width="540" height="360" /></p><h2>Step 8.</h2><p>Once the installation process is done, you can click the button to close the installer.</p><p><img class="alignnone  wp-image-4752" title="install oracle step 8" alt="install oracle step 8" src="http://www.zentut.com/wp-content/uploads/2013/05/install-oracle-step-8.png" width="560" height="420" /></p><h2>Verify the installation</h2><p>If everything is fine, you will see the Oracle folder as follows:<br /> <img class="alignnone size-full wp-image-4759" title="Oracle Folder" alt="Oracle Folder" src="http://www.zentut.com/wp-content/uploads/2013/05/Oracle-Folder1.png" width="247" height="215" /></p><p>First, launch the <strong>SQL Plus</strong> that is a command line interface tool which you can use to interact with Oracle databases.</p><p>Second, enter user name and password that you have set in the installation process. we enter HR user and its corresponding password.</p><p><a href="http://www.zentut.com/wp-content/uploads/2013/05/SQL-plus.png" rel="lightbox[4740]" title="SQL plus"><img class="alignnone  wp-image-4754" title="SQL plus" alt="SQL plus" src="http://www.zentut.com/wp-content/uploads/2013/05/SQL-plus.png" width="542" height="274" /></a></p><p>Third, enter the following statement:</p><pre class="brush: sql; gutter: true; first-line: 1">SELECT * FROM dual;</pre><p>If you see the output as shown in the following screenshot, it means you have installed Oracle database successfully and start learning PL/SQL programming.</p><p><a href="http://www.zentut.com/wp-content/uploads/2013/05/install-oracle-select-dual-table.png" rel="lightbox[4740]" title="Select from dual table"><img class="alignnone  wp-image-4760" title="Select from dual table" alt="Select from dual table" src="http://www.zentut.com/wp-content/uploads/2013/05/install-oracle-select-dual-table.png" width="542" height="274" /></a></p><p>In this tutorial, we have shown you step by step how to install Oracle database and verify the installation using SQL Plus. We hope that you got everything right at the first time. If this is not the case, please review each step one more time and make the appropriate correction if necessary.</p><p>The post <a href="http://www.zentut.com/plsql-tutorial/plsql-setting-up-a-development-environment/">PL/SQL Setting Up a Development Environment</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></content:encoded> <wfw:commentRss>http://www.zentut.com/plsql-tutorial/plsql-setting-up-a-development-environment/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>PDO Querying Data</title><link>http://www.zentut.com/php-pdo/pdo-querying-data/</link> <comments>http://www.zentut.com/php-pdo/pdo-querying-data/#comments</comments> <pubDate>Fri, 26 Apr 2013 09:18:24 +0000</pubDate> <dc:creator>Zentut Founder</dc:creator> <guid isPermaLink="false">http://www.zentut.com/?page_id=4703</guid> <description><![CDATA[<p>Summary: in this tutorial, you will learn how to query data from tables using PDOStatement object with different fetch modes. In order to query data from database table, you have to perform the following steps: Create a connection to the database by initiating an instance of the PDO class. Pass a SQL statement to the [...]</p><p>The post <a href="http://www.zentut.com/php-pdo/pdo-querying-data/">PDO Querying Data</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></description> <content:encoded><![CDATA[<p><strong>Summary</strong>: in this tutorial, you will learn how to query data from tables using <code>PDOStatement </code>object with different fetch modes.</p><p>In order to query data from database table, you have to perform the following steps:</p><ol><li><span style="line-height: 13px;">Create a <a title="Connect to a MySQL database" href="http://www.zentut.com/php-pdo/pdo-connecting-to-mysql/">connection to the database</a> by initiating an instance of the <code>PDO </code>class.</span></li><li>Pass a SQL statement to the <code>query()</code> method of the <code>PDO </code>object. This <code>query()</code> method returns a <code>PDOStatement </code>object that allows you to traverse the returned result set. If an error occurred during executing the SQL statement, the <code>query()</code> method return <code>false</code>.</li></ol><p>For example, if you want to query all data from the <code>departments </code>table in the <code>employees </code>database ( <code>empdb</code>), you can use the following script:</p><pre class="brush: php; gutter: true; first-line: 1">&lt;?php
require_once 'dbconfig.php';

// MySQL DSN
$dsn = "mysql:host=$host;dbname=$db"; 
// get all departments
$sql_get_depts = "SELECT * FROM departments";

try{
	$dbh = new PDO($dsn, $username, $password);
	$stmt = $dbh-&gt;query($sql_get_depts);

	if($stmt === false){
		die("Error executing the query: $sql_get_depts");
	}

}catch (PDOException $e){
	echo $e-&gt;getMessage();
}
?&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Departments&lt;/title&gt;
&lt;link href="css/bootstrap.min.css" rel="stylesheet"&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;h1&gt;Departments&lt;/h1&gt;
	&lt;table class="table table-striped table-bordered" style="width:300px;"&gt;
		&lt;thead&gt;
			&lt;tr&gt;
				&lt;th&gt;No.&lt;/th&gt;
				&lt;th&gt;Name&lt;/th&gt;
			&lt;/tr&gt;
		&lt;/thead&gt;
		&lt;tbody&gt;
			&lt;?php while($row = $stmt-&gt;fetch(PDO::FETCH_ASSOC)) : ?&gt;
			&lt;tr&gt;
				&lt;td&gt;&lt;?php echo htmlspecialchars($row['department_no']); ?&gt;&lt;/td&gt;
				&lt;td&gt;&lt;?php echo htmlspecialchars($row['name']); ?&gt;&lt;/td&gt;
			&lt;/tr&gt;
			&lt;?php endwhile; ?&gt;
		&lt;/tbody&gt;
	&lt;/table&gt;
&lt;/body&gt;
&lt;/html&gt;</pre><p>How it works.</p><ul><li><span style="line-height: 13px;">First, we included the <code>dbconfig.php</code> file, which is a database configuration file that contains database parameters including host, database name, username and password. These parameters are used to create a connection to the employees database.</span></li><li>Second, we created a connection to the employees database by initiating an instance of the <code>PDO </code>class.</li><li>Third, we called the <code>query()</code> method of the PDO object and passed the <a title="SQL SELECT statement" href="http://www.zentut.com/sql-tutorial/sql-select/">SELECT statement </a>that gets all data from the <code>departments </code>table.</li><li>Fourth, in the body of the HTML document, we called the <code>fetch()</code> method of the <code>PDOStatement </code>object with the <code>FETCH_ASSOC</code> fetch mode and displayed the column&#8217;s value of each record.</li></ul><p>The following is the output of the script:</p><p><a href="http://www.zentut.com/wp-content/uploads/2013/04/PDO-query-departments-data.png" rel="lightbox[4703]" title="PDO query departments data"><img class="alignnone size-full wp-image-4704" title="PDO query departments data" alt="PDO query departments data" src="http://www.zentut.com/wp-content/uploads/2013/04/PDO-query-departments-data.png" width="354" height="481" /></a></p><p>When we use <code>PDO::FETCH_ASSOC</code> fetch mode, the <code>PDOStatement</code> returns an array indexed by column name.</p><p>PDO provides several fetch modes. We will discuss the most commonly used ones in this section.</p><p>If you don&#8217;t pass a fetch mode to the <code>fetch()</code> method, it will use a default fetch mode which is <code>PDO::FETCH_BOTH</code> that instructs the <code>fetch()</code> method to returns an array indexed by both column name and integer index. For example, if you use <code>PDO::FETCH_BOTH</code> fetch mode, you can access the <code>department </code>column by using not only:</p><pre class="brush: php; gutter: true; first-line: 1">$row['department_no']</pre><p>but also</p><pre class="brush: php; gutter: true; first-line: 1">$row[0]</pre><p>The <code>PDO::FETCH_NUM</code> allows the <code>fetch()</code> method to return an array indexed by integer index. Therefore the <code>FETCH_BOTH </code>mode is the combination of <code>FETCH_ASSOC </code>and <code>FETCH_NUM </code>modes.</p><p>You can set fetch mode before calling the <code>fetch()</code> method by calling the <code>setFetchMode()</code> method of the <code>PDOStatement </code>object.</p><p>See the following example:</p><pre class="brush: php; gutter: true; first-line: 1">$stmt-&gt;setFetchMode(PDO::FETCH_BOTH);
while($r = $stmt-&gt;fetch()){
   //..
}</pre><p>The <code>PDO::FETCH_COLUMN</code> instructs PDO to return a specified column of every row. In this case, the <code>fetch()</code> method return a scalar value:</p><pre class="brush: php; gutter: true; first-line: 1">// only get the department name column
$stmt-&gt;setFetchMode(PDO::FETCH_COLUMN,1);
// $r is a string 
while($r = $stmt-&gt;fetch()){
	echo $r . '&lt;br/&gt;';
}</pre><p>The PDO statement allows you to query multiple times however before querying a new result set you have to call the <code>closeCursor()</code> method. The following example shows the department with number 1 and employees who belong to department 1.</p><pre class="brush: php; gutter: true; first-line: 1">&lt;?php
require_once 'dbconfig.php';

// MySQL DSN
$dsn = "mysql:host=$host;dbname=$db";

// get department no 1
$sql_get_depts = "SELECT * FROM departments
				  WHERE department_no = 1";

try{
	$dbh = new PDO($dsn, $username, $password);
	$stmt = $dbh-&gt;query($sql_get_depts);

	if($stmt === false){
		die("Error executing the query: $sql_get_depts");
	}

}catch (PDOException $e){
	echo $e-&gt;getMessage();
}
?&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Departments&lt;/title&gt;
&lt;link href="css/bootstrap.min.css" rel="stylesheet"&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;h1&gt;Departments&lt;/h1&gt;
	&lt;table class="table table-striped table-bordered" style="width:300px;"&gt;
		&lt;thead&gt;
			&lt;tr&gt;
				&lt;th&gt;No.&lt;/th&gt;
				&lt;th&gt;Name&lt;/th&gt;
			&lt;/tr&gt;
		&lt;/thead&gt;
		&lt;tbody&gt;
			&lt;?php while($row = $stmt-&gt;fetch(PDO::FETCH_ASSOC)) : ?&gt;
			&lt;tr&gt;
				&lt;td&gt;&lt;?php echo htmlspecialchars($row['department_no']); ?&gt;&lt;/td&gt;
				&lt;td&gt;&lt;?php echo htmlspecialchars($row['name']); ?&gt;&lt;/td&gt;
			&lt;/tr&gt;
			&lt;?php endwhile; ?&gt;
		&lt;/tbody&gt;
	&lt;/table&gt;

	&lt;?php
		$stmt-&gt;closeCursor();
		// get employees of department no 1
		$sql_get_emps_by_dept = "SELECT * FROM employees
					 WHERE department_no = 1
 					 ORDER BY last_name";
		$stmt = $dbh-&gt;query($sql_get_emps_by_dept);

		if($stmt === false){
			die("Error executing the query: $sql_get_emps_by_dept");
		}
	?&gt;
	&lt;h2&gt;Employees&lt;/h2&gt;
	&lt;table class="table table-striped table-bordered" style="width:600px;"&gt;
		&lt;thead&gt;
			&lt;tr&gt;
				&lt;th&gt;No.&lt;/th&gt;
				&lt;th&gt;First Name&lt;/th&gt;
				&lt;th&gt;Last Name&lt;/th&gt;
				&lt;th&gt;Gender&lt;/th&gt;
				&lt;th&gt;Birth Date&lt;/th&gt;
				&lt;th&gt;Hire Date&lt;/th&gt;
			&lt;/tr&gt;
		&lt;/thead&gt;
		&lt;tbody&gt;
			&lt;?php while($row = $stmt-&gt;fetch(PDO::FETCH_ASSOC)) : ?&gt;
			&lt;tr&gt;
				&lt;td&gt;&lt;?php echo htmlspecialchars($row['employee_no']); ?&gt;&lt;/td&gt;
				&lt;td&gt;&lt;?php echo htmlspecialchars($row['last_name']); ?&gt;&lt;/td&gt;
				&lt;td&gt;&lt;?php echo htmlspecialchars($row['first_name']); ?&gt;&lt;/td&gt;
				&lt;td&gt;&lt;?php echo htmlspecialchars($row['gender']); ?&gt;&lt;/td&gt;
				&lt;td&gt;&lt;?php echo htmlspecialchars($row['birth_date']); ?&gt;&lt;/td&gt;
				&lt;td&gt;&lt;?php echo htmlspecialchars($row['hire_date']); ?&gt;&lt;/td&gt;
			&lt;/tr&gt;
			&lt;?php endwhile;	?&gt;
		&lt;/tbody&gt;
	&lt;/table&gt;
&lt;/body&gt;
&lt;/html&gt;</pre><p>The following is the output of the script:</p><p><a href="http://www.zentut.com/wp-content/uploads/2013/04/PDO-query-department-and-employees.png" rel="lightbox[4703]" title="PDO query department and employees"><img class="alignnone  wp-image-4705" title="PDO query department and employees" alt="PDO query department and employees" src="http://www.zentut.com/wp-content/uploads/2013/04/PDO-query-department-and-employees.png" width="551" height="520" /></a></p><p>In this tutorial, we have shown you how to query data from the database tables using the <code>PDOStatement</code> object with different fetch modes.</p><p>The post <a href="http://www.zentut.com/php-pdo/pdo-querying-data/">PDO Querying Data</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></content:encoded> <wfw:commentRss>http://www.zentut.com/php-pdo/pdo-querying-data/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>PDO Creating New Tables</title><link>http://www.zentut.com/php-pdo/pdo-creating-new-tables/</link> <comments>http://www.zentut.com/php-pdo/pdo-creating-new-tables/#comments</comments> <pubDate>Thu, 25 Apr 2013 12:47:41 +0000</pubDate> <dc:creator>Zentut Founder</dc:creator> <guid isPermaLink="false">http://www.zentut.com/?page_id=4680</guid> <description><![CDATA[<p>Summary: in this tutorial, we will introduce you to employees data model that we will use through our PDO tutorial series and show you how to create new tables using PDO API. Introducing the Employees data model We are going to use the employees database through our PDO tutorial series. The following database diagram illustrates [...]</p><p>The post <a href="http://www.zentut.com/php-pdo/pdo-creating-new-tables/">PDO Creating New Tables</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></description> <content:encoded><![CDATA[<p><strong>Summary</strong>: in this tutorial, we will introduce you to <em>employees</em> data model that we will use through our PDO tutorial series and show you how to create new tables using PDO API.</p><h2>Introducing the Employees data model</h2><p>We are going to use the <strong>employees</strong> database through our PDO tutorial series. The following database diagram illustrates the employees<b> </b>data model:</p><p><img class="alignnone size-full wp-image-4695" title="PDO Employees Data Model" alt="PDO Employees Data Model" src="http://www.zentut.com/wp-content/uploads/2013/04/PDO-Employees-Data-Model.png" width="391" height="249" /></p><p>There are two tables in the Employees database:</p><ul><li><span style="line-height: 13px;"> <code>departments</code>: stores the department data including department number and department name. Each department has one or more employees.</span></li><li><code>employees</code>: stores employees data including employee number, first name, last name, birth date, gender, hire date and department which the employee belongs to.</li></ul><p>Notice that we make the <strong>employees</strong> data model as simple as possible for the demonstration purpose only. We will use MySQL as the database management system for the PDO tutorial series.</p><p>If you don&#8217;t know anything about SQL or you want to refresh you SQL knowledge, you can check it out the <a title="SQL Tutorial" href="http://www.zentut.com/sql-tutorial/">SQL tutorial</a> section in our website.</p><p>To create a new table in a database you use the <a title="SQL CREATE TABLE" href="http://www.zentut.com/sql-tutorial/sql-create-table/">CREATE TABLE</a> statement. The following SQL statement creates the <code>departments </code>table:</p><pre class="brush: sql; gutter: true; first-line: 1">CREATE TABLE departments (
  department_no int(11) NOT NULL AUTO_INCREMENT,
  name varchar(255) DEFAULT NULL,
  PRIMARY KEY (department_no)
) ENGINE=InnoDB;</pre><p>And to create the <code>employees </code>table, you use the following SQL statement:</p><pre class="brush: sql; gutter: true; first-line: 1">CREATE TABLE employees (
  employee_no int(11) NOT NULL AUTO_INCREMENT,
  first_name varchar(40) NOT NULL,
  last_name varchar(40) NOT NULL,
  birth_date date NOT NULL,
  gender varchar(1) NOT NULL,
  hire_date date DEFAULT NULL,
  department_no int(11) DEFAULT NULL,
  PRIMARY KEY (employee_no),
  KEY emp_dept (department_no),
  CONSTRAINT emp_dept FOREIGN KEY (department_no) 
  REFERENCES departments (department_no)
) ENGINE=InnoDB;</pre><p>We execute these SQL statements to create departments and employees tables via MySQL command line tool or GUI tool like MySQL Workbench. However, we will use PDO  API to create tables from the PHP script.</p><h2>Using PDO to create new tables</h2><p>First, we need to create a new database in MySQL named <code>empdb</code> to store the employee data using the <a title="SQL CREATE DATABASE" href="http://www.zentut.com/sql-tutorial/sql-create-database/">CREATE DATABASE</a>  statement as follows:</p><pre class="brush: sql; gutter: true; first-line: 1">CREATE DATABASE empdb;</pre><p>Second, we need to create a new database configuration file <code>dbconfig.php</code> to store the database parameters including hosts, database name, username and password as follows:</p><pre class="brush: php; gutter: true; first-line: 1">&lt;?php
$host='localhost';
$db = 'empdb';
$username = 'root';
$password = '';</pre><p>Third, we develop a script file that creates new tables in the   <code>empdb</code> database. We will include the <code>dbconfig.php</code> in this script file to access the database configurations.</p><pre class="brush: php; gutter: true; first-line: 1">&lt;?php
require_once 'dbconfig.php';

try{
	$dsn = "mysql:host=$host;dbname=$db";
	$dbh = new PDO($dsn, $username, $password);

	$sql_create_dept_tbl = &lt;&lt;&lt;EOSQL
CREATE TABLE departments(
  department_no int(11) NOT NULL AUTO_INCREMENT,
  name varchar(255) DEFAULT NULL,
  PRIMARY KEY (department_no)
) ENGINE=InnoDB
EOSQL;

	$sql_create_emp_tbl = &lt;&lt;&lt;EOSQL
CREATE TABLE employees (
  employee_no int(11) NOT NULL AUTO_INCREMENT,
  first_name varchar(40) NOT NULL,
  last_name varchar(40) NOT NULL,
  birth_date date NOT NULL,
  gender varchar(1) NOT NULL,
  hire_date date DEFAULT NULL,
  department_no int(11) DEFAULT NULL,
  PRIMARY KEY (employee_no),
  KEY emp_dept (department_no),
  CONSTRAINT emp_dept FOREIGN KEY (department_no)
  REFERENCES departments (department_no)
) ENGINE=InnoDB
EOSQL;

	$msg = '';

	$r = $dbh-&gt;exec($sql_create_dept_tbl);

	if($r !== false){

		$r = $dbh-&gt;exec($sql_create_emp_tbl);

		if($r !== false){
			$msg =  "Tables are created successfully!&lt;br/&gt;";
		}else{
			$msg =  "Error creating the employees table.&lt;br/&gt;";
		}

	}else{
		$msg =  "Error creating the departments table.&lt;br/&gt;";
	}

	// display the message
	if($msg != '')
		echo $msg;

}catch (PDOException $e){
	echo $e-&gt;getMessage();
}</pre><p>How it works.</p><ul><li><span style="line-height: 13px;">First, we created a <a title="Connecting to MySQL" href="http://www.zentut.com/php-pdo/pdo-connecting-to-mysql/">connection to the MySQL database</a> by instantiating an instance of the <code>PDO </code>class and passing the <code>$dsn</code> argument to its constructor.</span></li><li>Second, we specify the SQL statements that creates the <code>departments </code>and <code>employees</code> tables and put them into string variables:   <code>$sql_create_dept_tbl</code> and  <code>$sql_create_emp_tbl</code><code><br /> </code></li><li>Third, we call the <code>exec()</code> method of the PDO class to execute the SQL statements in sequence. The <code>exec()</code> method returns the number of affected rows, including <code>0</code>, on success and <code>false </code>on failure, therefore we had to use the <code>!==</code> operator to compare its returned value with <code>false</code>.</li></ul><p>After executing the script file, you can check the database to see if the <code>departments </code>and <code>employees</code> tables were created.</p><p>In this tutorial, you have learned about the employees data model and how to create new tables in the employees database using PDO API.</p><p>The post <a href="http://www.zentut.com/php-pdo/pdo-creating-new-tables/">PDO Creating New Tables</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></content:encoded> <wfw:commentRss>http://www.zentut.com/php-pdo/pdo-creating-new-tables/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>PDO Connecting to PostgreSQL</title><link>http://www.zentut.com/php-pdo/pdo-connecting-to-postgresql/</link> <comments>http://www.zentut.com/php-pdo/pdo-connecting-to-postgresql/#comments</comments> <pubDate>Thu, 25 Apr 2013 10:20:15 +0000</pubDate> <dc:creator>Zentut Founder</dc:creator> <guid isPermaLink="false">http://www.zentut.com/?page_id=4663</guid> <description><![CDATA[<p>Summary: this tutorial shows you how to connect to a PostgreSQL database server using PHP PDO. Prerequisites Before connecting to the PostgreSQL database server using PHP PDO, you need to have: A PostgreSQL database server, a sample database and account with username and password that can access the database. PHP PDO PostgreSQL driver enabled in [...]</p><p>The post <a href="http://www.zentut.com/php-pdo/pdo-connecting-to-postgresql/">PDO Connecting to PostgreSQL</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></description> <content:encoded><![CDATA[<p><strong>Summary</strong>: this tutorial shows you how to connect to a PostgreSQL database server using PHP PDO.</p><h2>Prerequisites</h2><p>Before connecting to the PostgreSQL database server using PHP PDO, you need to have:</p><ul><li><span style="line-height: 13px;">A PostgreSQL database server, a sample database and account with username and password that can access the database.</span></li><li>PHP PDO PostgreSQL driver enabled in your web server.</li></ul><p>For example, we have a local PostgreSQL database server that has <code>pagila </code>sample database and an account with <code>postgres </code>username and <code>postgres</code> password which can access the <code>pagila </code>database. We can create a new database configuration file named <code>dbconfig.php</code> and put these database parameters into the file as shown below:</p><pre class="brush: php; gutter: true; first-line: 1">&lt;?php
$host='localhost';
$db = 'pagila';
$username = 'postgres';
$password = 'postgres';</pre><p>Later on, we will use the <code>dbconfig.php</code> configuration file in other script files that need to access this configuration parameters by using the <code>require_once()</code> function.</p><p>To check if the PDO PostgreSQL driver is enabled, you open the <code>php.ini</code> file and check if the following line is un-commented. If it is not, you can remove the semicolon ( <code>;</code>) in front of the entry.</p><pre class="brush: text; gutter: false; first-line: 1">extension=php_pdo_pgsql.dll</pre><h2>PostgreSQL data source name</h2><p>The data source name or DSN conveys the database parameters that allow you to connect to a database system. PDO defines different DSN for different database system. The data source name of the PostgreSQL is composed of the following parameters:</p><ul><li><span style="line-height: 13px;"><strong>DNS prefix:</strong> <code>pgsql:</code></span></li><li><strong>host</strong>: the database server&#8217;s host name where the PostgreSQL database locates.</li><li><strong>port</strong>: the port which PostgreSQL database is running, the default port is 5432.</li><li><strong>dbname</strong>: database name.</li><li><strong>user</strong>: The name of user that connects to the database <code>dbname</code>. You can specify the user name in either DSN or in constructor of the PDO class.</li><li><strong>password</strong>: The password of the user name. You can specify the password in either the DSN or the PDO constructor.</li></ul><p>Notice that PDO ignores the username and password in the PDO constructor if you put them in the data source name (DSN). The following is the DSN that allows us to connect to <code>pagila </code>database in the local PostgreSQL database server.</p><pre class="brush: c; gutter: false; first-line: 1">pgsql:host=localhost;port=5432;dbname=pagila;user=postgres;password=postgres</pre><h2>Connecting to PostgreSQL</h2><p>The following code illustrates how to connect to the <span style="font-family: monospace;">pagila </span>database in PostgreSQL database server:</p><pre class="brush: php; gutter: true; first-line: 1">&lt;?php

require_once 'dbconfig.php';

$dsn = "pgsql:host=$host;port=5432;dbname=$db;user=$username;password=$password";

try{
	// create a PostgreSQL database connection
	$conn = new PDO($dsn);

	// display a message if connected to the PostgreSQL successfully
	if($conn){
		echo "Connected to the &lt;strong&gt;$db&lt;/strong&gt; database successfully!";
	}
}catch (PDOException $e){
	// report error message
	echo $e-&gt;getMessage();
}</pre><p>How the script works.</p><ul><li>To connect to a PostgreSQL database, you just need to create a new <strong>connection </strong>object, which is an instance of the PDO class. When you create a new connection object, you pass the DSN as an argument to its parameter.</li><li>The <code>try catch</code> statement is used to catch any exception that may occur during connecting to the PostgreSQL database. In the catch block, we display the error message if there is anything wrong with the connection.</li></ul><p>If you have everything setup correctly, you will see the following message:</p><pre class="brush: text; gutter: false; first-line: 1">Connected to the pagila database successfully!</pre><p>If you are using WAMP server, after enabling the POD PostgreSQL driver, it is still not working and you got the following error message:</p><pre class="brush: text; gutter: false; first-line: 1">could not find driver</pre><p>You can put the following line:</p><pre class="brush: text; gutter: false; first-line: 1">LoadFile "c:/wamp/bin/php/php5.4.3/libpq.dll"</pre><p>At the end of the <code>httpd.conf </code>file in the <code>C:\wamp\bin\apache\apache2.2.22\conf</code> folder.</p><p>In this tutorial, we have shown you step by step how to connect to the PostgreSQL database server using PHP PDO.</p><p>The post <a href="http://www.zentut.com/php-pdo/pdo-connecting-to-postgresql/">PDO Connecting to PostgreSQL</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></content:encoded> <wfw:commentRss>http://www.zentut.com/php-pdo/pdo-connecting-to-postgresql/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>PDO Connecting to MySQL</title><link>http://www.zentut.com/php-pdo/pdo-connecting-to-mysql/</link> <comments>http://www.zentut.com/php-pdo/pdo-connecting-to-mysql/#comments</comments> <pubDate>Thu, 25 Apr 2013 08:41:35 +0000</pubDate> <dc:creator>Zentut Founder</dc:creator> <guid isPermaLink="false">http://www.zentut.com/?page_id=4661</guid> <description><![CDATA[<p>Summary: this tutorial shows you step by step how to connect to MySQL database using PHP PDO. Prerequisites Before creating a connection to a MySQL database server, you must have: A MySQL database server installed in your local system or in a remote server. A sample database in the MySQL database server. A MySQL account [...]</p><p>The post <a href="http://www.zentut.com/php-pdo/pdo-connecting-to-mysql/">PDO Connecting to MySQL</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></description> <content:encoded><![CDATA[<p><strong>Summary</strong>: this tutorial shows you step by step how to connect to MySQL database using PHP PDO.</p><h2>Prerequisites</h2><p>Before creating a connection to a MySQL database server, you must have:</p><ul><li><span style="line-height: 13px;">A MySQL database server installed in your local system or in a remote server.</span></li><li>A sample database in the MySQL database server.</li><li>A MySQL account with username and password that can access the sample database.</li></ul><p>Suppose we have a local MySQL database server that contains the <code>pdodemo</code> sample database and an account with <code>root </code>username and blank password, we can put these parameters into a database configuration file named <code>dbconfig.php</code> as shown below:</p><pre class="brush: php; gutter: true; first-line: 1">&lt;?php
$host='localhost';
$db = 'pdodemo';
$username = 'root';
$password = '';</pre><p>We will include the <code>dbconfig.php</code> configuration file by using the <code>require_once()</code> function in other script files that need to access this configuration information. Check it out <a title="How to include a file in other files in PHP" href="http://www.zentut.com/php-tutorial/php-include-file/">how to include a file in other files</a> in the <a title="PHP include file" href="http://www.zentut.com/php-tutorial/php-include-file/">PHP include file tutorial</a>.</p><p>To check whether the PDO MySQL driver is enabled, you need to open the  <code>php.ini</code> file and uncomment the following line by removing the semicolon ( <code>;</code>) at the front of the entry:</p><pre class="brush: php; gutter: true; first-line: 1">extension=php_pdo_mysql.dll</pre><h2>MySQL data source name</h2><p>PDO uses a data source name (DSN), which contains the database server name, database name, and other parameters, that helps create a connection to a database server. Different database system requires different data source name. To connect to MySQL, you use the following data source name:</p><pre class="brush: php; gutter: true; first-line: 1">mysql:host=host_name;dbname=db_name</pre><p>The MySQL data source name contains the host name and database name which you want to connect to. We can define the DSN for our sample database as follows:</p><pre class="brush: php; gutter: true; first-line: 1">$dsn = "mysql:host=$host;dbname=$db";</pre><h2>Connecting to MySQL</h2><p>The following <code>index.php</code> script illustrates how to connect to the <code>pdodemo</code> database in MySQL database server with the <code>root</code> account:</p><pre class="brush: php; gutter: true; first-line: 1">&lt;?php

require_once 'dbconfig.php';

$dsn= "mysql:host=$host;dbname=$db";

try{
	// create a PDO connection with the configuration data
	$conn = new PDO($dsn, $username, $password);

	// display a message if connected to database successfully
	if($conn){
		echo "Connected to the &lt;strong&gt;$db&lt;/strong&gt; database successfully!";
        }
}catch (PDOException $e){
	// report error message
	echo $e-&gt;getMessage();
}</pre><p>How it works.</p><ul><li>To connect to MySQL database server, you need to create a new <strong>connection </strong>object with the data source name, user name and password. The connection object is an instance of the PDO class.</li><li>If something went wrong while establishing a connection to the MySQL server, an error message will display. The <code>try catch</code> block is used to catch any exceptions that occurs during creating the database connection.</li></ul><p>If you have everything setup correctly, you will see the following message:</p><pre class="brush: text; gutter: false; first-line: 1">Connected to the pdodemo database successfully!</pre><p>There are some common issues when you connect to the MySQL database as indicated below:</p><ul><li>If the MySQL driver is not enabled in the <code>php.ini</code> file, you will get the error message:</li></ul><pre class="brush: text; gutter: false; first-line: 1">could not find driver</pre><ul><li>If you provide incorrect database account, you get the following error message:</li></ul><p><span style="font-family: Consolas, Monaco, monospace; font-size: 12px; line-height: 18px;">SQLSTATE[HY000] [1045] Access denied for user &#8216;root&#8217;@'localhost&#8217; (using password: YES)</span></p><ul><li>If you provide an invalid database name or the database name does not exist in the MySQL database server, you get the following error message:</li></ul><pre class="brush: text; gutter: false; first-line: 1">SQLSTATE[HY000] [1049] Unknown database 'pdodemo'</pre><ul><li>If you provide an invalid database host name, the following error message will display:</li></ul><pre class="brush: text; gutter: false; first-line: 1">SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known.</pre><p>In this tutorial, you have learned how to connect to the MySQL database server using PHP PDO.</p><p>The post <a href="http://www.zentut.com/php-pdo/pdo-connecting-to-mysql/">PDO Connecting to MySQL</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></content:encoded> <wfw:commentRss>http://www.zentut.com/php-pdo/pdo-connecting-to-mysql/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>PHP PDO</title><link>http://www.zentut.com/php-pdo/</link> <comments>http://www.zentut.com/php-pdo/#comments</comments> <pubDate>Wed, 24 Apr 2013 02:23:19 +0000</pubDate> <dc:creator>Zentut Founder</dc:creator> <guid isPermaLink="false">http://www.zentut.com/?page_id=4624</guid> <description><![CDATA[<p>PHP PDO tutorial introduces you to one of the most important PHP extensions called PHP Data Objects or PDO, which was available since PHP version 5.0. PHP Data Objects or PDO is a PHP5 extension that provides a lightweight relational database management system (RDMBS) connection abstract library. PDO provides a unified interface for working with [...]</p><p>The post <a href="http://www.zentut.com/php-pdo/">PHP PDO</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></description> <content:encoded><![CDATA[<p><a href="http://www.zentut.com/wp-content/uploads/2013/04/php-pdo.png" rel="lightbox[4624]" title="PHP PDO"><img class="alignright  wp-image-4625" title="PHP PDO" alt="PHP PDO" src="http://www.zentut.com/wp-content/uploads/2013/04/php-pdo.png" width="296" height="194" /></a><strong>PHP PDO tutorial</strong> introduces you to one of the most important PHP extensions called <strong>PHP Data Objects</strong> or <strong>PDO</strong>, which was available since PHP version 5.0.</p><p>PHP Data Objects or PDO is a PHP5 extension that provides a lightweight relational database management system (RDMBS) connection abstract library. PDO provides a unified interface for working with various RDBMS including creating database connection, performing queries, handling error, etc.</p><p>PDO relies on database specific drivers e.g., PDO_MYSQL for MySQL, PDO_PGSQL for PostgreSQL, PDO_OCI for Oracle, etc., to function properly so to use PDO for a specific database, you need to have the corresponding database driver available.</p><p>There are several libraries that provide the same functionality as PDO such as PEAR DB package and ADOdb library. However, those libraries were written in PHP, while PDO was developed in C/C++ that makes it perform faster.</p><p>In addition, PDO does not require you to include script files in your application like other libraries, which helps distribute and install the application easier and faster.</p><h2>PDO Quick Start</h2><p>This section shows you step by step how to connect to some relational database management systems including MySQL, PostgreSQL and Oracle.</p><ul><li><a title="PHP PDO - Connecting to MySQL" href="http://www.zentut.com/php-pdo/pdo-connecting-to-mysql/">Connecting to MySQL</a> &#8211; guides you step-by-step how to connect to MySQL database using PDO.</li><li><a title="Connecting to PostgreSQL" href="http://www.zentut.com/php-pdo/pdo-connecting-to-postgresql/">Connecting to PostgreSQL</a> &#8211; shows you how to connect to PostgreSQL database using PDO.</li><li>Connecting to Oracle &#8211; connects to Oracle database using PDO.</li></ul><h2>PDO Basic Operations</h2><p>This section illustrates some common operations that you often work with databases including:</p><ul><li><a title="PDO Creating New Tables" href="http://www.zentut.com/php-pdo/pdo-creating-new-tables/">Creating new tables</a> &#8211; shows you how to use PDO API to create tables for the employees sample database.</li><li><span style="line-height: 13px;"><a title="PDO Querying Data" href="http://www.zentut.com/php-pdo/pdo-querying-data/">Querying data with different fetch modes</a> &#8211; guides you how to query data from database tables with different fetch modes.</span></li><li><a title="PDO Inserting Data into Tables" href="http://www.zentut.com/php-pdo/pdo-inserting-data-into-tables/">Inserting data into table</a>s &#8211; walks you through the steps of inserting data into database tables.</li><li>Updating data &#8211; shows you how to update data in the database tables using PDO API.</li><li>Deleting data &#8211; guides you how to delete data in the database table using PDO API.</li></ul><h2>PDO Prepared Statements</h2><p>In this section, we&#8217;ll introduce you to prepared statement and show you the advantages of PDO prepared statements. We also show how to use the prepared statements to make your application more secure e.g., to avoid SQL injection.</p><ul><li>Positional and named holders.</li><li>Prepared statements and bound values.</li><li>CRUD using prepared statements.</li><li>Working with BLOBs.</li></ul><h2>PDO &amp; Stored Procedures</h2><p>This section shows you some examples of dealing with stored procedures including:</p><ul><li>Calling stored procedures.</li><li>Getting values returned from the stored procedures.</li></ul><h2>PDO Transaction</h2><p>PDO gives you some handy methods including <code>PDO::beginTransaction()</code>, <code>PDO::commit()</code> and <code>PDO::rollBack()</code> that handles transactions effectively. This section gives you an example of handling transactions in your web application.</p><ul><li>PDO handling transaction.</li></ul><h2>PDO Reference</h2><ul><li><span style="line-height: 13px;"><a href="http://www.php.net/manual/en/book.pdo.php">http://www.php.net/manual/en/book.pdo.php</a> &#8211; PHP Data Objects</span></li></ul><p>The post <a href="http://www.zentut.com/php-pdo/">PHP PDO</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></content:encoded> <wfw:commentRss>http://www.zentut.com/php-pdo/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>C Binary Search Tree</title><link>http://www.zentut.com/c-tutorial/c-binary-search-tree/</link> <comments>http://www.zentut.com/c-tutorial/c-binary-search-tree/#comments</comments> <pubDate>Thu, 18 Apr 2013 11:39:17 +0000</pubDate> <dc:creator>Zentut Founder</dc:creator> <guid isPermaLink="false">http://www.zentut.com/?page_id=4545</guid> <description><![CDATA[<p>Summary: this tutorial introduces you to binary search tree data structure and how to implement it in C. Introduction to binary search tree A binary search tree or BST is a binary tree in symmetric order. A binary search tree can: Be empty Have a key and not more than two other subtrees, which are [...]</p><p>The post <a href="http://www.zentut.com/c-tutorial/c-binary-search-tree/">C Binary Search Tree</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></description> <content:encoded><![CDATA[<p><strong>Summary</strong>: this tutorial introduces you to <strong>binary search tree</strong> data structure and how to implement it in C.</p><h2>Introduction to binary search tree</h2><div id="attachment_4546" class="wp-caption alignright" style="width: 396px"><img class="size-full wp-image-4546" title="C Binary Search Tree" alt="C Binary Search Tree" src="http://www.zentut.com/wp-content/uploads/2013/04/C-binary-search-tree.jpg" width="386" height="255" /><p class="wp-caption-text">Binary Search Tree</p></div><p>A <strong>binary search tree</strong> or <strong>BST</strong> is a <strong>binary tree</strong> in <strong>symmetric order. </strong></p><p>A binary search tree can:</p><ul><li><span style="line-height: 13px;">Be empty</span></li><li>Have a key and not more than two other subtrees, which are called left subtree and right subtree.</li></ul><p>A binary search tree is in symmetric order, it means:</p><ul><li><span style="line-height: 13px;">Each node contains a key.</span></li><li>Each node&#8217;s key is smaller than all node&#8217;s keys in the right subtree and bigger than all node&#8217;s keys in the left subtree.</li></ul><p>A binary search tree is also known as <strong>sorted</strong> or <strong>ordered binary tree</strong>.</p><h2>Binary search tree operations</h2><p>There are some common operations on the binary search tree:</p><ul><li>Insert &#8211; inserts a new node into the tree</li><li>Delete &#8211; removes an existing node from the tree</li><li>Traverse &#8211; traverse the tree in pre-order, in-order and post-order. For the binary search tree, only in-order traversal makes sense</li><li>Search &#8211; search for a given node&#8217;s key in the tree</li></ul><p>All binary search tree operations are O(H), where H is the depth of the tree. The minimum height of a binary search tree is H = log<sub>2</sub>N, where N is the number of the tree&#8217;s nodes. Therefore the complexity of a binary search tree operation in the best case is O(logN); and in the worst case, its complexity is O(N).</p><p>The worst case happens when the binary search tree is unbalanced. Many algorithms have been invented to keep a binary search tree balanced such as height-balanced tree or <a title="C AVL tree" href="http://www.zentut.com/c-tutorial/c-avl-tree/">AVL trees</a> of <strong>A</strong>delson-<strong>V</strong>elskii and <strong>L</strong>andis, B-trees, and Splay trees.</p><h2>C binary search tree implementation</h2><p>We can use a <a title="C Structure" href="http://www.zentut.com/c-tutorial/c-structure/">structure </a>to model the binary search tree node a follows:</p><pre class="brush: c; gutter: true; first-line: 1">typedef struct node
{
    int data;
    struct node* left;
    struct node* right;
} node;</pre><p>The node structure has three members:</p><ul><li><span style="line-height: 13px;"> <code>data</code>: stores node&#8217;s key, which is an <a title="C Integer" href="http://www.zentut.com/c-tutorial/c-integer/">integer</a>. You can store a <a title="C String" href="http://www.zentut.com/c-tutorial/c-string/">string</a>, a <a title="C Pointer" href="http://www.zentut.com/c-tutorial/c-pointer/">pointer </a>to a <a title="C Structure" href="http://www.zentut.com/c-tutorial/c-structure/">structure </a>or <code>(void*)</code>. For the sake of simplicity, we will use a binary search tree of integers.</span></li><li><code>left</code>: points to the left subtree.</li><li><code>right</code>: points to the right subtree.</li></ul><p>To create a new node, we use the <code>malloc()</code> function to <a title="C dynamic memory allocation" href="http://www.zentut.com/c-tutorial/c-dynamic-memory-allocation/">allocate memory dynamically</a> as follows:</p><pre class="brush: c; gutter: true; first-line: 1">/*
    create a new node
*/
node* create_node(int data)
{
    node *new_node = (node*)malloc(sizeof(node));
    if(new_node == NULL)
    {
        fprintf (stderr, "Out of memory!!! (create_node)\n");
        exit(1);
    }
    new_node-&gt;data = data;
    new_node-&gt;left = NULL;
    new_node-&gt;right = NULL;
    return new_node;
}</pre><p>To compare the data of two nodes, we can compare two integers. However to make it more extensible, we can pass a callback to any function that has comparison between two keys of nodes. The callback for comparing two nodes is defined as follows:</p><pre class="brush: c; gutter: true; first-line: 1">typedef int (*comparer)(int, int);</pre><p>Later on you may change the type of data to <code>string</code>, <code>float</code>, or even <code>void*</code>, and change the <code>comparer </code>callback accordingly.</p><h3>Insert a new node into the binary search tree</h3><p>If the binary search tree is empty, we just create a new node, otherwise we start from the root node:</p><p>We find the proper position for the new node by comparing the new node&#8217;s key with the root node&#8217;s key. If the key of the new node less than the root node&#8217;s key, we go to the left subtree. If the key of the new node is greater than the root node&#8217;s key, we go to the right subtree. We do this step recursively until we find the correct position in the tree to insert the new node.</p><p>The following illustrates the <code>insert_node</code> function:</p><pre class="brush: c; gutter: true; first-line: 1">/*
    insert a new node into the BST
*/
node* insert_node(node *root, comparer compare, int data)
{

    if(root == NULL)
    {
        root = create_node(data);
    }
    else
    {
        int is_left  = 0;
        int r        = 0;
        node* cursor = root;
        node* prev   = NULL;

        while(cursor != NULL)
        {
            r = compare(data,cursor-&gt;data);
            prev = cursor;
            if(r &lt; 0)
            {
                is_left = 1;
                cursor = cursor-&gt;left;
            }
            else if(r &gt; 0)
            {
                is_left = 0;
                cursor = cursor-&gt;right;
            }

        }
        if(is_left)
            prev-&gt;left = create_node(data);
        else
            prev-&gt;right = create_node(data);

    }
    return root;
}</pre><h3>Delete a node from the binary search tree</h3><p>Deleting an existing node in the binary search tree is little more complicated. There are three cases that we should consider:</p><p>Case 1. Delete a leaf node i.e., node that has no children. We just need to remove it. The following example illustrates how to remove the leaf node e.g., <code>13</code></p><div id="attachment_4549" class="wp-caption alignnone" style="width: 620px"><img class="size-full wp-image-4549" title="Binary Search Tree - Remove Leaf Node" alt="Binary Search Tree - Remove Leaf Node" src="http://www.zentut.com/wp-content/uploads/2013/04/bst-remove-leaf-node.png" width="610" height="215" /><p class="wp-caption-text">C Binary Search Tree &#8211; Remove Leaf Node</p></div><p>Case 2. Remove a node that has 1 child node, we replace it with its child node and remove it e.g., to remove node 10 in the following picture.</p><div id="attachment_4550" class="wp-caption alignnone" style="width: 553px"><img class="size-full wp-image-4550" alt="Binary Search Tree - Remove Node with 1 Child" src="http://www.zentut.com/wp-content/uploads/2013/04/bst-remove-node-with-1-child.png" width="543" height="217" /><p class="wp-caption-text">C Binary Search Tree &#8211; Remove Node with 1 Child</p></div><p>Case 3. To remove a node that has two child nodes or two children, we find its in-order successor node, which is the next node in in-order traversal of the tree, and replace it with the in-order success node.</p><p>For example, to remove node <code>3</code>, we find its in-order successor node, which is <code>4</code>, and replace the node <code>3</code> by <code>4</code> as illustrated in the following picture.</p><div id="attachment_4552" class="wp-caption alignnone" style="width: 529px"><img class="size-full wp-image-4552" alt="Binary Search Tree – Remove Node with Two Children" src="http://www.zentut.com/wp-content/uploads/2013/04/bst-remove-node-with-2-children.png" width="519" height="203" /><p class="wp-caption-text">Binary Search Tree – Remove Node with Two Children</p></div><p>The following is the delete node function that uses <a title="C Recursive Function" href="http://www.zentut.com/c-tutorial/c-recursive-function/">recursive function in C</a>:</p><pre class="brush: c; gutter: true; first-line: 1">/*
    delete a node in the binary search tree
*/
node* delete_node(node* root, int data,comparer compare)
{
    if(root == NULL)
        return NULL;

    node *cursor;
    int r = compare(data,root-&gt;data);
    if( r &lt; 0)
        root-&gt;left = delete_node( root-&gt;left, data,compare);
    else if( r &gt; 0 )
        root-&gt;right = delete_node(root-&gt;right,data,compare);
    else
    {
        if (root-&gt;left == NULL)
        {
            cursor = root-&gt;right;
            free(root);
            root = cursor;
        }
        else if (root-&gt;right == NULL)
        {
            cursor = root-&gt;left;
            free(root);
            root = cursor;
        }
        else    //2 children
        {
            cursor = root-&gt;right;
            node *parent = NULL;

            while(cursor-&gt;left != NULL)
            {
                parent = cursor;
                cursor = cursor-&gt;left;
            }
            root-&gt;data = cursor-&gt;data;
            if (parent != NULL)
                parent-&gt;left = delete_node(parent-&gt;left, parent-&gt;left-&gt;data,compare);
            else
                root-&gt;right = delete_node(root-&gt;right, root-&gt;right-&gt;data,compare);
        }
    }
    return root;
}</pre><h3>Search for a specific key in the binary search tree</h3><p>To search for a specific key in the binary search tree, we start from the root node. If the tree is empty, the key does not exist. Otherwise, if the root node&#8217;s key is equal to the key, the search is successful, we terminate the search. If the key is less than the root node&#8217;s key, we search the left subtree. Likewise, if the key is greater than the root node&#8217;s key, we search the right subtree. We repeat this step recursively until the key is found or subtree is NULL.</p><pre class="brush: c; gutter: true; first-line: 1">/*
    search for a specific key
*/
node* search(node *root,const int data,comparer compare)
{
    if(root == NULL)
        return NULL;

    int r;
    node* cursor = root;
    while(cursor != NULL)
    {
        r = compare(data,cursor-&gt;data);
        if(r &lt; 0)
            cursor = cursor-&gt;left;
        else if(r &gt; 0)
            cursor = cursor-&gt;right;
        else
            return cursor;
    }
    return cursor;

}</pre><h3>Traverse the binary search tree</h3><p>We can traverse the binary search tree once it is created by traversing recursively to the left subtree of the root node, accessing the root node&#8217;s data, and then recursively traversing to the right subtree of the root node. This is called in-order traversal of a binary tree.</p><p>Because of the rules of the nodes&#8217; keys in the binary search tree, this in-order traversal always creates a sorted list of nodes.</p><p>The following is the in-order traversal function of the binary search tree:</p><pre class="brush: c; gutter: true; first-line: 1">/*
    in order traversal the binary search tree
*/
void traverse(node *root,callback cb)
{
    node *cursor, *pre;

    if(root == NULL)
        return;

    cursor = root;

    while(cursor != NULL)
    {
        if(cursor-&gt;left != NULL)
        {
            cb(cursor);
            cursor = cursor-&gt;right;
        }
        else
        {
            pre = cursor-&gt;left;

            while(pre-&gt;right != NULL &amp;&amp; pre-&gt;right != cursor)
                pre = pre-&gt;right;

            if (pre-&gt;right != NULL)
            {
                pre-&gt;right = cursor;
                cursor = cursor-&gt;left;
            }
            else
            {
                pre-&gt;right = NULL;
                cb(cursor);
                cursor = cursor-&gt;right;
            }
        }
    }
}</pre><p>Notice that we pass a callback to the <code>traverse </code>function so that we can manipulate the node dynamically. The callback is defined as follows:</p><pre class="brush: c; gutter: true; first-line: 1">typedef void (*callback)(node*);</pre><h3>Remove all nodes</h3><p>We must deallocate memory allocated for all the nodes in the binary search tree. We can create a function named <code>dispose()</code> to do this:</p><pre class="brush: c; gutter: true; first-line: 1">/*
    recursively remove all nodes of the tree
*/
void dispose(node* root)
{
    if(root != NULL)
    {
        dispose(root-&gt;left);
        dispose(root-&gt;right);
        free(root);
    }
}</pre><h2>C binary search tree program</h2><p>Before creating a program to test our binary search tree, we need to create some functions for:</p><p>Comparing two integers:</p><pre class="brush: c; gutter: true; first-line: 1">/*
    compare two integers
*/
int compare(int left,int right)
{
    if(left &gt; right)
        return 1;
    if(left &lt; right)
        return -1;
    return 0;
}</pre><p>Displaying a node:</p><pre class="brush: c; gutter: true; first-line: 1">/*
    display a node's key
*/
void display(node* nd)
{
    if(nd != NULL)
        printf("%d ",nd-&gt;data);
}</pre><p>And a function for displaying the whole tree:</p><pre class="brush: c; gutter: true; first-line: 1">/*
    Recursively display tree or subtree
*/
void display_tree(node* nd)
{
    if (nd == NULL)
        return;
    /* display node data */
    printf("%d",nd-&gt;data);
    if(nd-&gt;left != NULL)
        printf("(L:%d)",nd-&gt;left-&gt;data);
    if(nd-&gt;right != NULL)
        printf("(R:%d)",nd-&gt;right-&gt;data);
    printf("\n");

    display_tree(nd-&gt;left);
    display_tree(nd-&gt;right);
}</pre><p>Now it&#8217;s time to play with the binary search tree:</p><pre class="brush: c; gutter: true; first-line: 1">#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

#include "bst.h"

#define SIZE 9

int main()
{
    node* root = NULL;
    comparer int_comp = compare;
    callback f = display;

    /* insert data into the tree */
    int a[SIZE] = {8,3,10,1,6,14,4,7,13};
    int i;
    printf("--- C Binary Search Tree ---- \n\n");
    printf("Insert: ");
    for(i = 0; i &lt; SIZE; i++)
    {
        printf("%d ",a[i]);
        root = insert_node(root,int_comp,a[i]);
    }
    printf(" into the tree.\n\n");

    /* display the tree */
    display_tree(root);

    /* remove element */
    int r;
    do
    {
        printf("Enter data to remove, (-1 to exit):");
        scanf("%d",&amp;r);
        if(r == -1)
            break;
        root = delete_node(root,r,int_comp);
        /* display the tree */
        if(root != NULL)
            display_tree(root);
        else
            break;
    }
    while(root != NULL);

    /* search for a node */
    int key = 0;
    node *s;
    while(key != -1)
    {
        printf("Enter data to search (-1 to exit):");
        scanf("%d",&amp;key);

        s = search(root,key,int_comp);
        if(s != NULL)
        {
            printf("Found it %d",s-&gt;data);
            if(s-&gt;left != NULL)
                printf("(L: %d)",s-&gt;left-&gt;data);
            if(s-&gt;right != NULL)
                printf("(R: %d)",s-&gt;right-&gt;data);
            printf("\n");
        }
        else
        {
            printf("node %d not found\n",key);
        }
    }

    /* remove the whole tree */
    dispose(root);
    return 0;
}</pre><p>The following is the output of the binary search tree program in C:</p><pre class="brush: text; gutter: false; first-line: 1">--- C Binary Search Tree ----

Insert: 8 3 10 1 6 14 4 7 13  into the tree.

8(L:3)(R:10)
3(L:1)(R:6)
1
6(L:4)(R:7)
4
7
10(R:14)
14(L:13)
13
Enter data to remove, (-1 to exit):13
8(L:3)(R:10)
3(L:1)(R:6)
1
6(L:4)(R:7)
4
7
10(R:14)
14
Enter data to remove, (-1 to exit):10
8(L:3)(R:14)
3(L:1)(R:6)
1
6(L:4)(R:7)
4
7
14
Enter data to remove, (-1 to exit):3
8(L:4)(R:14)
4(L:1)(R:6)
1
6(R:7)
7
14
Enter data to remove, (-1 to exit):-1
Enter data to search (-1 to exit):6
Found it 6(R: 7)
Enter data to search (-1 to exit):13
node 13 not found
Enter data to search (-1 to exit):-1
node -1 not found</pre><p>In this tutorial, you have learned how to implement the binary search tree in C.</p><p>The post <a href="http://www.zentut.com/c-tutorial/c-binary-search-tree/">C Binary Search Tree</a> appeared first on <a href="http://www.zentut.com">ZenTut</a>.</p>]]></content:encoded> <wfw:commentRss>http://www.zentut.com/c-tutorial/c-binary-search-tree/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> </channel> </rss>
<!-- Served from: www.zentut.com @ 2013-05-18 22:22:17 by W3 Total Cache -->