blob: b45a0ceff8f1b57fdc37ca167203282ce5ab6caa [file] [log] [blame]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--
Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
-->
<html>
<head>
<title>Creating a Database Driven Application With PHP. Optimizing PHP code. Refactoring. Include files. MySQL database access functions</title>
<meta name="KEYWORDS" content="CRUD, Update, Delete, MySQL, PHP, NetBeans">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="DESCRIPTION" content="Creating a Database Driven Application With PHP. Optimizing PHP code. Refactoring. Include files. MySQL Database access functions" >
<link rel="stylesheet" type="text/css" href="../../../netbeans.css" media="screen">
</head>
<body>
<h1>Creating a Database Driven Application With PHP </h1>
<h1>Lesson 4: Optimizing the Code with Classes and Objects</h1>
<div style="margin-left:-3px">
<div class="feedback-box margin-around float-left" style="margin-right:15px">
<h4>Tutorial contents:</h4>
<ol start="0">
<li><a href="wish-list-tutorial-main-page.html">Creating a Database Driven Application With PHP - Main page</a></li>
<li><p>Creating the Database</p> <ol type="a"><li><a href="wish-list-lesson1.html">Creating a MySQL Database</a></li>
<li><a href="wish-list-oracle-lesson1.html">Creating Oracle Database Tables</a></li>
</ol></li>
<li><a href="wish-list-lesson2.html">Designing the Application. Reading from the Database
</a></li>
<li><a href="wish-list-lesson3.html">Creating a New Application User</a></li>
<li><p><b>=&gt; Optimizing the Code</b></p>
<ul>
<li><a href="#previousLessonSourceCode">Application Source Code from the Previous Lesson</a></li>
<li><a href="#createDbPhpFile">Creating the db.php File</a></li>
<li><a href="#wishDBClass">Creating the WishDB Class</a></li>
<li><a href="#instantiate-wishdb">Instantiating the WishDB Class</a></li>
<li><a href="#wishdb-constructor">Adding a Constructor to the WishDB Class</a></li>
<li><a href="#includedFunctions">Functions in the WishDB Class</a>
<ul>
<li><a href="#getIDByName">Function get_wisherID_by_name</a></li>
<li><a href="#getWishesByID">Function get_wishes_by_wisher_id</a></li>
<li><a href="#createWisher">Function create_wisher</a></li>
</ul>
</li>
<li><a href="#refactoring">Refactoring Your Application Code</a>
<ul>
<li><a href="#refactoringWishlistFile">Refactoring the wishlist.php File</a></li>
<li><a href="#refactoringCreateNewWisher">Refactoring the createNewWisher.php File</a></li>
</ul>
</li>
<li><a href="#lessonResultSourceCode">Application Source Code after the Current Lesson Is Completed</a></li>
</ul>
</li>
<li><a href="wish-list-lesson5.html">Adding Security. Implementing Application User Logon</a></li>
<li><a href="wish-list-lesson6.html">Adding a New Wish to the Database</a></li>
<li><a href="wish-list-lesson7.html">Updating and Deleting Entries in the Database</a></li>
<li><a href="wish-list-lesson8.html">Making the Application Look Better Using the CSS Technology</a></li>
<li><a href="wish-list-lesson9.html">Deploying the Application on a Remote Web Server</a></li>
</ol>
</div>
</div>
<img src="../../../images_www/articles/73/netbeans-stamp-80-74-73.png" class="stamp" alt="Content on this page applies to NetBeans IDE 7.2, 7.3, 7.4 and 8.0" title="Content on this page applies to the NetBeans IDE 7.2, 7.3, 7.4 and 8.0" >
<p>In this lesson you optimize the code to facilitate maintaining it in the future. This affects the files <tt>createNewWisher.php</tt> and <tt>wishlist.php</tt>. Additionally, a new file called <tt>db.php</tt> is created.</p>
<p>Your application's code contains several similar blocks
with queries to the database. To make the code easier to read and maintain in the future,
you can extract these blocks, implement them as functions of a separate class called <tt>WishDB</tt>, and place <tt>WishDB</tt> in <tt>db.php</tt>. Afterwards you can
include the <tt>db.php</tt> file in any PHP file and use any <a href="#includedFunctions">function from WishDB</a> without code duplication. Such an approach ensures that any changes to queries or functions will be made in one place and you will not have to parse the entire application code. </p>
<p>When you use a function from WishDB, you do not change the value of any of WishDB's variables. Instead, you use the WishDB class as a blueprint for creating an object of WishDB, and you change the values of variables in that object. When you finish working with that object, it is destroyed. Because the values of the WishDB class itself are never changed, you can reuse the class an unlimited number of times. In some cases you may want to have multiple instances of a class in existance at the same time, and in other cases you may prefer a &quot;singleton&quot; class, where you only have one instance in existance at any one time. WishDB in this tutorial is a singleton class.</p>
<p>Note that the term for creating an object of a class is &quot;instantiating&quot; that class, and that another word for an object is an &quot;instance&quot; of a class. The general term for programming with classes and objects is &quot;object-oriented programming,&quot; or OOP. PHP 5 uses a sophisticated OOP model. See <a target="_blank" href="http://us3.php.net/zend-engine-2.php">php.net</a> for more information.</p>
<p>In this tutorial, you move the database call functionality from individual PHP files to the WishDB class. Users of MySQL also replace the procedural-style <tt>mysqli</tt> calls with object-oriented calls. This is in keeping with new, object-oriented design of the application</p>
<p>The current document is a part of the Creating a CRUD Application in the NetBeans IDE for PHP tutorial. </p>
<br style="clear:left">
<h2><a name="previousLessonSourceCode"></a>Application Source Code from the Previous Lesson</h2>
<p>MySQL users: Click <a target="_blank" href="https://netbeans.org/files/documents/4/1929/lesson3.zip">here</a> to download the source code that reflects the project state after the previous lesson is completed. </p>
<p>Oracle Database users: Click <a target="_blank" href="https://netbeans.org/projects/www/downloads/download/php%252Foracle-lesson3.zip">here</a> to download the source code that reflects the project state after the previous lesson is completed.</p>
<h2><a name="createDbPhpFile"></a>Creating the db.php File</h2>
<p>Create a new subfolder in the Source Files folder. Name the folder Includes. Create a new file named db.php and place it in Includes. Later you can add more files to this folder that
will be included in other PHP files. </p>
<p><b>To create db.php in a new folder:</b></p>
<ol>
<li>Click the right mouse button on the Source files node and choose New &gt; Folder from the context menu. The New Folder dialog opens. </li>
<li>In the Folder Name field, type Includes. Then click Finish.</li>
<li>Click the right mouse button on the Includes node and choose New &gt; PHP File from the context menu. The New PHP File dialog opens.</li>
<li>In the File Name field, type db. Then click Finish. </li>
</ol>
<h2><a name="wishDBClass"></a>Creating the WishDB Class</h2>
<p>To create the WishDB class, you need to initialize the variables of the class and implement a constructor of the class. MySQL users please note that the WishDB class <em>extends</em> <tt>mysqli</tt>. This means that WishDB <em>inherits</em> the functions and other characteristics of the PHP mysqli class. You will see the importance of this when you add <tt>mysqli </tt>functions to the class.</p>
<p>Open the file db.php and create the WishDB class. In the class, declare database configuration variables for storing the name and password of the database owner (user), the name of the database, and the database host. All these variable declarations are &quot;private,&quot; meaning that the initial values in the declarations cannot be accessed from outside the WishDB class (See <a target="_blank" href="http://us3.php.net/manual/en/language.oop5.visibility.php">php.net</a>). You also declare the private <em> static</em> <tt>$instance</tt> variable, which stores the instance of WishDB. The &quot;static&quot; keyword means that functions in the class can access the variable even when there is no instance of the class.</p>
<p><strong>For MySQL Database:</strong></p>
<pre class="examplecode">class WishDB extends mysqli {
// single instance of self shared among all instances
private static $instance = null;
// db connection config vars
private $user = "phpuser";
private $pass = "phpuserpw";
private $dbName = "wishlist";
private $dbHost = "localhost";
}</pre>
<p><strong>For Oracle Database: </strong></p>
<pre class="examplecode">
class WishDB {<br><br>
// single instance of self shared among all instances
private static $instance = null;<br><br>
// db connection config vars
private $user = "phpuser";
private $pass = "phpuserpw";
private $dbName = "wishlist";
private $dbHost = "localhost/XE";
private $con = null;<br><br>
} </pre>
<h2 id="instantiate-wishdb">Instantiating the WishDB class</h2>
<p>For other PHP files to use functions in the WishDB class, these PHP files need to call a function that creates an object of (&quot;instantiates&quot;) the WishDB class. WishDB is designed as a <a target="_blank" href="http://www.phpclasses.org/browse/package/1151.html">singleton class</a>, meaning that only one instance of the class is in existance at any one time. It is therefore useful to prevent any external instantiation of WishDB, which could create duplicate instances.</p>
<p>Inside the WishDB class, type or paste the following code:</p>
<pre class="examplecode"> //This method must be static, and must return an instance of the object if the object
//does not already exist.
public static function getInstance() {
if (!self::$instance instanceof self) {
self::$instance = new self;
}
return self::$instance;
}
// The clone and wakeup methods prevents external instantiation of copies of the Singleton class,
// thus eliminating the possibility of duplicate objects.
public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public function __wakeup() {
trigger_error('Deserializing is not allowed.', E_USER_ERROR);
}</pre>
<p>The <tt>getInstance</tt> function is &quot;public&quot; and &quot;static.&quot; &quot;Public&quot; means that it can be freely accessed from outside the class. &quot;Static&quot; means that the function is available even when the class has not been instantiated. As the <tt>getInstance</tt> function is called to instantiate the class, it must be static.
Note that this function accesses the static <tt>$instance</tt> variable and sets its value as the instance of the class.
<p>The double-colon (::), called the Scope Resolution Operator, and the <tt>self</tt> keyword are used to access static functions. <tt>Self</tt> is used from within the class definition to refer to the class itself. When the double-colon is used from outside the class definition, the name of the class is used instead of <tt>self</tt>. See <a target="_blank" href="http://us3.php.net/manual/en/language.oop5.paamayim-nekudotayim.php">php.net on the Scope Resolution Operator</a>.
<h2 id="wishdb-constructor">Adding a Constructor to the WishDB Class</h2>
<p>A class can contain a special method known as a 'constructor' which is automatically processed whenever an instance of that class is created. In this tutorial, you add a constructor to WishDB that connects to the database whenever WishDB is instantiated.</p>
<p>Add the following code to WishDB:</p>
<p><b>For the MySQL database:</b></p>
<pre class="examplecode">// private constructor<br>private function __construct() {<br> parent::__construct($this-&gt;dbHost, $this-&gt;user, $this-&gt;pass, $this-&gt;dbName);<br> if (mysqli_connect_error()) {<br> exit('Connect Error (' . mysqli_connect_errno() . ') '<br> . mysqli_connect_error());<br> }<br> parent::set_charset('utf-8');<br>}</pre>
<p><b>For the Oracle database:</b></p>
<pre class="examplecode">// private constructor
private function __construct() {
$this->con = oci_connect($this->user, $this->pass, $this->dbHost);
if (!$this->con) {
$m = oci_error();
echo $m['message'], "\n";
exit;
}
}</pre>
<p>Note the use of the pseudovariable <tt>$this</tt> instead of the variables <tt>$con</tt>, <tt>$dbHost</tt>, <tt>$user</tt>, or <tt>$pass</tt>. The pseudovariable <tt>$this</tt> is used when a method is called from within an object context. It refers to the value of a variable within that object.</p>
<h2><a name="includedFunctions" id="includedFunctions"></a>Functions in the WishDB Class </h2>
<p>In this lesson you will implement the following functions of the WishDB class:</p>
<ul>
<li><a href="#getIDByName">get_wisher_id_by_name</a> for retrieving the id of a wisher based on the wisher's name </li>
<li><a href="#getWishesByID">get_wishes_by_wisher_id</a> for retrieving a list of wishes of the wisher with a specific id </li>
<li><a href="#createWisher">create_wisher</a> for adding a new wisher record to the table wishers </li>
</ul>
<div class="indent"><h3><a name="getIDByName" id="getIDByName"></a>Function get_wisher_id_by_name</h3>
The function requires the name of a wisher as the input parameter and returns the wisher's id. <br>
<p>
Type or paste the following function into the WishDB class, after the WishDB function:</p>
<p><b>For the MySQL database:</b></p>
<pre class="examplecode">public function get_wisher_id_by_name($name) {<br>
$name = $this-&gt;real_escape_string($name);<br>
$wisher = $this-&gt;query(&quot;SELECT id FROM wishers WHERE name = '&quot;<br>
. $name . &quot;'&quot;);
if ($wisher-&gt;num_rows &gt; 0){<br> $row = $wisher-&gt;fetch_row();<br> return $row[0];<br> } else<br> return null;
}</pre>
<p><b>For the Oracle database:</b></p>
<pre class="examplecode">public function get_wisher_id_by_name($name) {
$query = "SELECT id FROM wishers WHERE name = :user_bv&quot;;
$stid = oci_parse($this->con, $query);
oci_bind_by_name($stid, ':user_bv', $name);
oci_execute($stid);
//Because user is a unique value I only expect one row
$row = oci_fetch_array($stid, OCI_ASSOC);<br> if ($row) <br> return $row[&quot;ID&quot;];<br> else<br> return null;
}</pre>
The code block executes the query
<tt>SELECT ID FROM wishers WHERE name = [variable for name of the wisher]</tt>.
The query result is an array of IDs from the records that meet the query. If the array is not empty this automatically means that it contains one element because the field name is specified as UNIQUE during the table creation. In this case the function returns the first element of the <tt>$result</tt> array (the element with the zero numbered).
If the array is empty the function returns null.
<p class="notes"><b>Security Note:</b> For the MySQL database, the <tt>$name </tt>string is escaped in order to prevent SQL injection attacks. See <a target="_blank" href="http://en.wikipedia.org/wiki/SQL_injection">Wikipedia on SQL injections</a> and the <a target="_blank" href="http://us3.php.net/mysql_real_escape_string">mysql_real_escape_string documentation</a>. Although in the context of this tutorial you are not at risk of harmful SQL injections, it is best practice to escape strings in MySQL queries that would be at risk of such an attack. The Oracle database avoids this issue by using bind variables.</p>
<h3><a name="getWishesByID" id="getWishesByID"></a>Function get_wishes_by_wisher_id</h3>
<p>The function requires the id of a wisher as the input parameter and returns the wishes registered for the wisher. </p>
<p>Enter the following code block:</p>
<p><b>For the MySQL database:</b></p>
<pre class="examplecode">public function get_wishes_by_wisher_id($wisherID) {<br> return $this->query(&quot;SELECT id, description, due_date FROM wishes WHERE wisher_id=&quot; . $wisherID);<br>}</pre>
<p><b>For the Oracle database:</b></p>
<pre class="examplecode">public function get_wishes_by_wisher_id($wisherID) {
$query = "SELECT id, description, due_date FROM wishes WHERE wisher_id = :id_bv";
$stid = oci_parse($this->con, $query);
oci_bind_by_name($stid, ":id_bv", $wisherID);
oci_execute($stid);
return $stid;
}</pre>
<p>The code block executes the query <tt>"SELECT id, description, due_date FROM wishes WHERE wisherID=" . $wisherID</tt> and returns a resultset which is an array of records that meet the query. (The Oracle database uses a bind variable for database performance and security reasons.) The selection is performed by the wisherID, which is the foreign key for the <tt>wishes </tt>table. </p>
<p class="notes"><b>Note:</b> You do not need the <tt>id</tt> value until Lesson 7.</p>
<h3><a name="createWisher" id="createWisher"></a>Function create_wisher</h3>
<p>The function creates a new record in the wishers table. The function requires the name and password of a new wisher as the input parameters and does not return any data.</p>
Enter the following code block:
<p><b>For the MySQL database:</b></p>
<pre class="examplecode">public function create_wisher ($name, $password){
$name = $this-&gt;real_escape_string($name);<br> $password = $this-&gt;real_escape_string($password);<br> $this-&gt;query(&quot;INSERT INTO wishers (name, password) VALUES ('&quot; . $name . &quot;', '&quot; . $password . &quot;')&quot;);
}</pre>
<p><b>For the Oracle database:</b></p>
<pre class="examplecode">public function create_wisher($name, $password) {
$query = "INSERT INTO wishers (name, password) VALUES (:user_bv, :pwd_bv)";
$stid = oci_parse($this->con, $query);
oci_bind_by_name($stid, ':user_bv', $name);
oci_bind_by_name($stid, ':pwd_bv', $password);
oci_execute($stid);
}</pre>
The code block executes the query
<tt>&quot;INSERT wishers (Name, Password) VALUES ([variables representing name and password of new wisher])</tt>. The query adds a new record to the &quot;wishers&quot; table with the fields &quot;name&quot; and &quot;password&quot; filled in with the values of <tt>$name</tt> and <tt>$password</tt> respectively. </div>
<h2><a name="refactoring"></a>Refactoring Your Application Code</h2>
<p>Now that you have a separate class for working with the database, you can replace duplicated blocks with calls to the relevant functions from this class. This will help avoid misspelling and inconsistency in the future. Code optimization that does not affect the functionality is called refactoring.</p>
<div class="indent">
<h3><a name="refactoringWishlistFile"></a>Refactoring the wishlist.php File </h3>
Start with the wishlist.php file because it is short and the improvements will be more illustrative.
<ol>
<li>At the top of the &lt;?php ?&gt; block, enter the following line to enable the use of the <tt>db.php</tt> file:
<pre class="examplecode">require_once("Includes/db.php");</pre>
</li>
<li>Replace the code that connects to the database
and gets the ID of the wisher with a call to the <tt>get_wisher_id_by_name</tt> function.
<p>For the <b>MySQL database</b>, the code you replace is:
<pre class="examplecode"><del>$con = mysqli_connect("localhost", "phpuser", "phpuserpw");
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
//set the default client character set
mysqli_set_charset($con, 'utf-8');
mysqli_select_db($con, "wishlist");
$user = mysqli_real_escape_string($con, $_GET['user']);
$wisher = mysqli_query($con, "SELECT id FROM wishers WHERE name='" . $user . "'");
if (mysqli_num_rows($wisher) &lt; 1) {
exit("The person " . $_GET['user'] . " is not found. Please check the spelling and try again");
}
$row = mysqli_fetch_row($wisher);<br>$wisherID = $row[0];
mysqli_free_result($wisher);</del><br><br>
<b>$wisherID = WishDB::getInstance()-&gt;get_wisher_id_by_name($_GET[&quot;user&quot;]);
if (!$wisherID) {
exit(&quot;The person &quot; .$_GET[&quot;user&quot;]. &quot; is not found. Please check the spelling and try again&quot; );
}</b></pre>
<p>For the <b>Oracle database</b>, the code you replace is:</p>
<pre class="examplecode"><del>$con = oci_connect(&quot;phpuser&quot;, &quot;phpuserpw&quot;, &quot;localhost/XE&quot;, &quot;AL32UTF8&quot;);
if (!$con) {
$m = oci_error();
echo $m['message'], &quot;\n&quot;;
exit;
}
$query = &quot;SELECT id FROM wishers WHERE name = :user_bv&quot;;
$stid = oci_parse($con, $query);
$user = $_GET[&quot;user&quot;];
oci_bind_by_name($stid, ':user_bv', $user);
oci_execute($stid);
//Because user is a unique value I only expect one row<br>
$row = oci_fetch_array($stid, OCI_ASSOC);
if (!$row) {
echo(&quot;The person &quot; . $user . &quot; is not found. Please check the spelling and try again&quot; );<br> exit;<br>
}
$wisherID = $row[&quot;ID&quot;]; </del>
<br>
<b>$wisherID = WishDB::getInstance()-&gt;get_wisher_id_by_name($_GET[&quot;user&quot;]);
if (!$wisherID) {
exit(&quot;The person &quot; .$_GET[&quot;user&quot;]. &quot; is not found. Please check the spelling and try again&quot; );
}</b></pre>
<p>The new code first calls the <tt>getInstance</tt> function in WishDB. The <tt>getInstance</tt> function returns an instance of WishDB, and the code calls the <tt>get_wisher_id_by_name</tt> function within that instance. If the requested wisher is not found in the database, the code kills the process and displays an error message.</p><p>No code is necessary here for opening a connection to the database. The connection is opened by the constructor of the WishDB class. If the name and/or password changes, you need to update only the relevant variables of the WishDB class.</p>
</li>
<li>Replace the code that gets wishes for a wisher identified by ID with code that calls the <tt>get_wishes_by_wisher_id</tt> function.
<p>For the <b>MySQL database</b>, the code you replace is:
<pre class="examplecode"><del>$result = mysqli_query($con, "SELECT description, due_date FROM wishes WHERE wisher_id=". $wisherID);</del>
<strong>$result = WishDB::getInstance()-&gt;get_wishes_by_wisher_id($wisherID);</strong></pre>
<p>For the <b>Oracle database</b>, the code you replace is: </p>
<pre class="examplecode"><del>$query = &quot;select * from wishes where wisher_id = :id_bv&quot;;<br>$stid = oci_parse($con, $query);<br>oci_bind_by_name($stid, &quot;:id_bv&quot;, $wisherID);<br>oci_execute($stid);</del>
<strong>$stid = WishDB::getInstance()-&gt;get_wishes_by_wisher_id($wisherID);</strong></pre>
</li>
<li>Remove the line that closes the database connection.
<pre class="examplecode"> <del>mysqli_close($con);</del>
or
<del>oci_close($con);</del> </pre>
The code is not necessary because the connection to the database is automatically closed when the WishDB object is destroyed. However, keep the code that frees the resource. You need to free all resources that use a connection to ensure that a connection is properly closed, even if you call a <tt>close</tt> function or destroy the instance with the database connection.</li>
</ol>
<h3>&nbsp;</h3>
<h3><a name="refactoringCreateNewWisher"></a>Refactoring the createNewWisher.php File </h3>
<p>Refactoring will not affect the HTML input form or the code for displaying the related error messages.</p>
<ol>
<li>At the top of the &lt;?php?&gt; block, enter the following code to enable the use of the <tt>db.php</tt> file:
<pre class="examplecode">require_once("Includes/db.php");</pre>
</li>
<li>Delete the database connection credentials (<tt>$dbHost,</tt> etc). These are now in <tt>db.php</tt>.</li>
<li>Replace the code that connects to the database
and gets the ID of the wisher with a call to the <tt>get_wisher_id_by_name</tt> function.
<p>For the <b>MySQL database</b>, the code you replace is:</p>
<pre class="examplecode"><del>
$con = mysqli_connect("localhost", "phpuser", "phpuserpw");
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
//set the default client character set
mysqli_set_charset($con, 'utf-8');
<br>/** Check whether a user whose name matches the "user" field already exists */
mysqli_select_db($con, "wishlist");
$user = mysqli_real_escape_string($con, $_POST['user']);
$wisher = mysqli_query($con, "SELECT id FROM wishers WHERE name='".$user."'");
$wisherIDnum=mysqli_num_rows($wisher);
if ($wisherIDnum) {
$userNameIsUnique = false;
}</del>
<br>
<strong>$wisherID = WishDB::getInstance()-&gt;get_wisher_id_by_name($_POST[&quot;user&quot;]);<br>if ($wisherID) {<br> $userNameIsUnique = false;<br>}</strong></pre>
<p>For the <b>Oracle database</b>, the code you replace is: </p>
<pre class="examplecode"><del>
$con = oci_connect("phpuser", "phpuserpw", "localhost");
if (!$con) {
$m = oci_error();
echo $m['message'], "\n";
exit;
}
$query = "select ID from wishers where name = :user_bv";
$stid = oci_parse($con, $query);
$user = $_POST['user'];
$wisherID = null;
oci_bind_by_name($stid, ':user_bv', $user);
oci_execute($stid);
//Each user name should be unique. Check if the submitted user already exists.
$row = oci_fetch_array($stid, OCI_ASSOC);<br>if ($row) {<br> $wisherID = $row[&quot;ID&quot;]; <br>}<br>if ($wisherID != null) {<br> $userNameIsUnique = false;<br>}</del>
<strong>$wisherID = WishDB::getInstance()-&gt;get_wisher_id_by_name($_POST[&quot;user&quot;]);<br>if ($wisherID) {<br> $userNameIsUnique = false;<br>}</strong></pre>
The <tt>WishDB</tt> object exists as long as the current page is being processed. It is destroyed after the processing is completed or interrupted. The code for opening a connection to the database is not necessary because this is done by the WishDB function. The code for closing the connection is not necessary because the connection is closed as soon as the <tt>WishDB</tt> object is destroyed.</li>
<li>Replace the code that inserts new wishers into the database with code that calls the <tt>create_wisher</tt> function.
<p>For the <b>MySQL database</b>, the code you replace is:</p>
<pre class="examplecode"><del>if (!$userIsEmpty &amp;&amp; $userNameIsUnique &amp;&amp; !$passwordIsEmpty &amp;&amp; !$password2IsEmpty &amp;&amp; $passwordIsValid) {
$password = mysqli_real_escape_string($con, $_POST[&quot;password&quot;]);<br> mysqli_select_db($con, &quot;wishlist&quot;);<br> mysqli_query($con, &quot;INSERT wishers (name, password) VALUES ('&quot; . $user . &quot;', '&quot; . $password . &quot;')&quot;);<br> mysqli_free_result($wisher);<br> mysqli_close($con);<br> header('Location: editWishList.php');<br> exit;<br>}
</del>
<strong>if (!$userIsEmpty &amp;&amp; $userNameIsUnique &amp;&amp; !$passwordIsEmpty &amp;&amp; !$password2IsEmpty &amp;&amp; $passwordIsValid) {<br> WishDB::getInstance()-&gt;create_wisher($_POST[&quot;user&quot;], $_POST[&quot;password&quot;]);<br> header('Location: editWishList.php' );<br> exit;<br>}</strong></pre>
<p>For the <b>Oracle database</b>, the code you replace is: </p>
<pre class="examplecode"><del>
if (!$userIsEmpty && $userNameIsUnique && !$passwordIsEmpty && !$password2IsEmpty && $passwordIsValid) {
$query = "INSERT INTO wishers (name, password) VALUES (:user_bv, :pwd_bv)";
$stid = oci_parse($con, $query);
$pwd = $_POST['password'];
oci_bind_by_name($stid, ':user_bv', $user);
oci_bind_by_name($stid, ':pwd_bv', $pwd);
oci_execute($stid);
oci_close($con);
header('Location: editWishList.php');
exit;
}</del>
<strong>if (!$userIsEmpty &amp;&amp; $userNameIsUnique &amp;&amp; !$passwordIsEmpty &amp;&amp; !$password2IsEmpty &amp;&amp; $passwordIsValid) {<br> WishDB::getInstance()-&gt;create_wisher($_POST[&quot;user&quot;], $_POST[&quot;password&quot;]);<br> header('Location: editWishList.php' );<br> exit;<br>}</strong></pre>
</li>
</ol>
</div>
<h2><a name="lessonResultSourceCode"></a>Application Source Code after the Current Lesson Is Completed </h2>
<p>MySQL users: Click <a target="_blank" href="https://netbeans.org/projects/www/downloads/download/php%252Flesson4.zip">here</a> to download the source code that reflects the project state after the lesson is completed.</p>
<p>Oracle Database users: Click <a target="_blank" href="https://netbeans.org/projects/www/downloads/download/php%252Foracle-lesson4.zip"> here</a> to download the source code that reflects the project state after the lesson is completed.</p>
<h2><a name="nextSteps"></a>Next Steps</h2>
<p>
<a href="wish-list-lesson3.html">&lt;&lt; Previous lesson</a><br>
<br>
<a href="wish-list-lesson5.html">Next lesson >></a><br>
<br>
<a href="wish-list-tutorial-main-page.html">Back to the Tutorial main page</a><br>
<br>
</p>
<h2><a name="usefulLinks"></a>Useful Links</h2>
<p>Learn more about using classes in PHP:</p>
<ul>
<li><a target="_blank" href="http://us3.php.net/manual/en/language.oop5.php">Classes and Objects</a> </li>
</ul>
<p>Learn more about refactoring PHP code: </p>
<ul>
<li><a target="_blank" href="http://www.slideshare.net/spriebsch/seven-steps-to-better-php-code-presentation/">Seven Steps To Better PHP Code</a></li>
<li> <a target="_blank" href="http://www.dokeos.com/wiki/index.php/Refactoring">PHP Refactoring</a></li>
</ul>
<br>
<div class="feedback-box" ><a href="/about/contact_form.html?to=3&amp;subject=Feedback:%20PHP%20Wish%20List%20CRUD%204:%20Optimizing%20Code">Send Feedback on This Tutorial</a></div>
<br style="clear:both;" >
<p>To send comments and suggestions, get support, and keep informed on the latest
developments on the NetBeans IDE PHP development features, <a href="../../../community/lists/top.html">join
the users@php.netbeans.org mailing list</a>.</p>
<p><a href="../../trails/php.html">Back to the PHP Learning Trail</a><br>
</p>
</body>
</html>