<?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>Jorge Albaladejo &#187; MySQL</title>
	<atom:link href="http://jorgealbaladejo.com/category/web-architecture/mysql-databases-technology/feed/" rel="self" type="application/rss+xml" />
	<link>http://jorgealbaladejo.com</link>
	<description>Hard &#38; Soft design...</description>
	<lastBuildDate>Mon, 06 Feb 2012 22:00:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>E/R Zero or One to Many relationships</title>
		<link>http://jorgealbaladejo.com/2011/03/27/er-zero-or-one-to-many-relationships/</link>
		<comments>http://jorgealbaladejo.com/2011/03/27/er-zero-or-one-to-many-relationships/#comments</comments>
		<pubDate>Sun, 27 Mar 2011 15:34:48 +0000</pubDate>
		<dc:creator>Jorge Albaladejo</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Web Architecture]]></category>
		<category><![CDATA[database design]]></category>
		<category><![CDATA[E/R modeling]]></category>
		<category><![CDATA[mysql]]></category>

		<guid isPermaLink="false">http://jorgealbaladejo.com/?p=787</guid>
		<description><![CDATA[While 1:n, 1:1 and n:m relationships are thoroughly used to design logical database models, there another another kind, {0&#124;1}:n that may come in handy in some cases. Lets analyze this relationship carefully. Imagine a relationship between students and classrooms. Every classroom can have N students, meaning this zero, one, or many pupils. From the other [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify">While 1:n, 1:1 and n:m relationships are thoroughly used to design logical database models, there another another kind, {0|1}:n that may come in handy in some cases. Lets analyze this relationship carefully.</p>
<p style="text-align:justify">Imagine a relationship between students and classrooms. Every classroom can have N students, meaning this zero, one, or many pupils. From the other side, every student must have a classroom, otherwise she won&#8217;t be allowed to study. This is a classic 1:n relationship, used in most of the real cases that we may encounter.</p>
<p style="text-align:justify">But what if, let&#8217;s say, a student had finished her studies and, however, wasn&#8217;t deleted from the database? (just to keep the records and other sensible information). In that case, the statement &#8216;every student must have one and only one classroom&#8217; would be wrong. Instead, we could say &#8216;every student can have one classroom or none&#8217;. Now we are talking about zero or one to many relationships.</p>
<p><span id="more-787"></span></p>
<p style="text-align:justify">A practical situation for this type of relationships are tree structures on auto-referenced tables. For instance, a category tree where every tuple can have a parent or none (thus being at root level). While a possible solution to this problem might be to create a &#8216;fake&#8217; root element that all the others inherit from unless said otherwise, this approach forces the design to include a &#8216;meta element&#8217;, not meant to represent data at all. That&#8217;s to say, it has to be programmatically removed from all database queries so not to have it poking around.</p>
<p style="text-align:justify">The right solution to this problem is making the foreign key nullable so that we can effectively represent the case when there is no parent while respecting relational integrity. In addition, the cascading options on deletion should be set as &#8216;set null&#8217; so that a possible deletion of a classroom does not delete all the students that might be related:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p787code2'); return false;">View Code</a> MYSQL</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p7872"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code" id="p787code2"><pre class="mysql" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">-- ------------------------------------------</span>
<span style="color: #808080; font-style: italic;">-- Table classrooms </span>
<span style="color: #808080; font-style: italic;">-- ------------------------------------------</span>
<a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=CREATE" rel="external"><span style="color: #990099; font-weight: bold;">CREATE</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=TABLE" rel="external"><span style="color: #990099; font-weight: bold;">TABLE</span></a> classrooms<span style="color: #FF00FF;">&#40;</span>
  classroomID <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=INT" rel="external"><span style="color: #999900; font-weight: bold;">INT</span></a> <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/non-typed-operators.html" rel="external"><span style="color: #CC0099; font-weight: bold;">NOT</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=NULL" rel="external"><span style="color: #9900FF; font-weight: bold;">NULL</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=AUTO_INCREMENT" rel="external"><span style="color: #FF9900; font-weight: bold;">AUTO_INCREMENT</span></a> <span style="color: #000033;">,</span>
  classroomName <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=VARCHAR" rel="external"><span style="color: #999900; font-weight: bold;">VARCHAR</span></a><span style="color: #FF00FF;">&#40;</span><span style="color: #008080;">50</span><span style="color: #FF00FF;">&#41;</span> <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/non-typed-operators.html" rel="external"><span style="color: #CC0099; font-weight: bold;">NOT</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=NULL" rel="external"><span style="color: #9900FF; font-weight: bold;">NULL</span></a> <span style="color: #000033;">,</span>
  <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=PRIMARY%20KEY" rel="external"><span style="color: #990099; font-weight: bold;">PRIMARY KEY</span></a> <span style="color: #FF00FF;">&#40;</span>classroomID<span style="color: #FF00FF;">&#41;</span>
<span style="color: #FF00FF;">&#41;</span> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=ENGINE" rel="external"><span style="color: #990099; font-weight: bold;">ENGINE</span></a> <span style="color: #CC0099;">=</span> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=INNODB" rel="external"><span style="color: #990099; font-weight: bold;">InnoDB</span></a><span style="color: #000033;">;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">-- ------------------------------------------</span>
<span style="color: #808080; font-style: italic;">-- Table students</span>
<span style="color: #808080; font-style: italic;">-- ------------------------------------------</span>
<a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=CREATE" rel="external"><span style="color: #990099; font-weight: bold;">CREATE</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=TABLE" rel="external"><span style="color: #990099; font-weight: bold;">TABLE</span></a> students <span style="color: #FF00FF;">&#40;</span>
  studentID <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=INT" rel="external"><span style="color: #999900; font-weight: bold;">INT</span></a> <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/non-typed-operators.html" rel="external"><span style="color: #CC0099; font-weight: bold;">NOT</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=NULL" rel="external"><span style="color: #9900FF; font-weight: bold;">NULL</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=AUTO_INCREMENT" rel="external"><span style="color: #FF9900; font-weight: bold;">AUTO_INCREMENT</span></a> <span style="color: #000033;">,</span>
  studentName <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=VARCHAR" rel="external"><span style="color: #999900; font-weight: bold;">VARCHAR</span></a><span style="color: #FF00FF;">&#40;</span><span style="color: #008080;">50</span><span style="color: #FF00FF;">&#41;</span> <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/non-typed-operators.html" rel="external"><span style="color: #CC0099; font-weight: bold;">NOT</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=NULL" rel="external"><span style="color: #9900FF; font-weight: bold;">NULL</span></a> <span style="color: #000033;">,</span>
  classroomID <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=INT" rel="external"><span style="color: #999900; font-weight: bold;">INT</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=DEFAULT" rel="external"><span style="color: #990099; font-weight: bold;">DEFAULT</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=NULL" rel="external"><span style="color: #9900FF; font-weight: bold;">NULL</span></a> <span style="color: #000033;">,</span>
  <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=PRIMARY%20KEY" rel="external"><span style="color: #990099; font-weight: bold;">PRIMARY KEY</span></a> <span style="color: #FF00FF;">&#40;</span>studentID<span style="color: #FF00FF;">&#41;</span> <span style="color: #000033;">,</span>
  <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=CONSTRAINT" rel="external"><span style="color: #990099; font-weight: bold;">CONSTRAINT</span></a> fk_students_classrooms
    <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=FOREIGN%20KEY" rel="external"><span style="color: #990099; font-weight: bold;">FOREIGN KEY</span></a> <span style="color: #FF00FF;">&#40;</span>classroomID<span style="color: #FF00FF;">&#41;</span>
    <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=REFERENCES" rel="external"><span style="color: #990099; font-weight: bold;">REFERENCES</span></a> classrooms.classroomID
    <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=ON" rel="external"><span style="color: #990099; font-weight: bold;">ON</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=DELETE" rel="external"><span style="color: #990099; font-weight: bold;">DELETE</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=SET" rel="external"><span style="color: #990099; font-weight: bold;">SET</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=NULL" rel="external"><span style="color: #9900FF; font-weight: bold;">NULL</span></a>
    <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=ON" rel="external"><span style="color: #990099; font-weight: bold;">ON</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=UPDATE" rel="external"><span style="color: #990099; font-weight: bold;">UPDATE</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=CASCADE" rel="external"><span style="color: #990099; font-weight: bold;">CASCADE</span></a>
<span style="color: #FF00FF;">&#41;</span> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=ENGINE" rel="external"><span style="color: #990099; font-weight: bold;">ENGINE</span></a> <span style="color: #CC0099;">=</span> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=INNODB" rel="external"><span style="color: #990099; font-weight: bold;">InnoDB</span></a><span style="color: #000033;">;</span></pre></td></tr></table></div>

<p style="text-align:justify">Further reading: <a href="http://stackoverflow.com/questions/2530215/model-a-zero-or-one-to-many-relationship" target="_blank" rel="external">here</a> and <a href="http://stackoverflow.com/questions/925203/any-example-of-a-necessary-nullable-foreign-key" target="_blank" rel="external">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://jorgealbaladejo.com/2011/03/27/er-zero-or-one-to-many-relationships/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MySQL clean reinstall</title>
		<link>http://jorgealbaladejo.com/2010/07/27/mysql-clean-reinstall/</link>
		<comments>http://jorgealbaladejo.com/2010/07/27/mysql-clean-reinstall/#comments</comments>
		<pubDate>Tue, 27 Jul 2010 19:08:14 +0000</pubDate>
		<dc:creator>Jorge Albaladejo</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://jorgealbaladejo.com/?p=397</guid>
		<description><![CDATA[To perform a clean reinstall of the MySQL server (which regenerates start scripts, databases and config files) use: ?View Code BASH1 2 3 4 sudo apt-get install mysql-server&#60;/li&#62; sudo apt-get remove --purge mysql-server&#60;/li&#62; sudo apt-get autoremove mysql-server&#60;/li&#62; sudo apt-get install mysql-server&#60;/li&#62; Some times is useful!]]></description>
			<content:encoded><![CDATA[<p>To perform a clean reinstall of the MySQL server (which regenerates start scripts, databases and config files) use:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p397code4'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p3974"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p397code4"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #c20cb9; font-weight: bold;">apt-get</span> <span style="color: #c20cb9; font-weight: bold;">install</span> mysql-server<span style="color: #000000; font-weight: bold;">&lt;/</span>li<span style="color: #000000; font-weight: bold;">&gt;</span>
<span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #c20cb9; font-weight: bold;">apt-get</span> remove <span style="color: #660033;">--purge</span> mysql-server<span style="color: #000000; font-weight: bold;">&lt;/</span>li<span style="color: #000000; font-weight: bold;">&gt;</span>
<span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #c20cb9; font-weight: bold;">apt-get</span> autoremove mysql-server<span style="color: #000000; font-weight: bold;">&lt;/</span>li<span style="color: #000000; font-weight: bold;">&gt;</span>
<span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #c20cb9; font-weight: bold;">apt-get</span> <span style="color: #c20cb9; font-weight: bold;">install</span> mysql-server<span style="color: #000000; font-weight: bold;">&lt;/</span>li<span style="color: #000000; font-weight: bold;">&gt;</span></pre></td></tr></table></div>

<p>Some times is useful!</p>
]]></content:encoded>
			<wfw:commentRss>http://jorgealbaladejo.com/2010/07/27/mysql-clean-reinstall/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementing a database cubes system on MySQL</title>
		<link>http://jorgealbaladejo.com/2010/05/11/implementing-a-database-cubes-system-on-mysql/</link>
		<comments>http://jorgealbaladejo.com/2010/05/11/implementing-a-database-cubes-system-on-mysql/#comments</comments>
		<pubDate>Tue, 11 May 2010 09:22:01 +0000</pubDate>
		<dc:creator>Jorge Albaladejo</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Web Architecture]]></category>
		<category><![CDATA[cubes]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[hourly averages]]></category>
		<category><![CDATA[mysql]]></category>

		<guid isPermaLink="false">http://jorgealbaladejo.com/?p=321</guid>
		<description><![CDATA[I&#8217;ve already talked about how I solved the problem of managing huge amounts of data in my last post. Now, I&#8217;m going to explain how to implement one of the solutions found in order to comfortably face this continuously increasing avalanche of information. Let&#8217;s imagine that, as I explained before, I have separated data input [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">I&#8217;ve already talked about how I solved the problem of managing huge amounts of data in <a href="http://jorgealbaladejo.com/?p=319" title="Managing big data sets with MySQL">my last post</a>. Now, I&#8217;m going to explain how to implement one of the solutions found in order to comfortably face this continuously increasing avalanche of information.</p>
<p style="text-align: justify;">Let&#8217;s imagine that, as I explained before, I have separated data input into tables coded by a station ID. All of them are stored in the same database for maintenance simplicity sake. So, we have the &#8216;database&#8217; in which there are hundreds of tables called &#8216;Station_XYZ&#8217;. Every table has the same structure: to simplify, SensorID, Time (UNIX), Value. All right then, time to make cubes!</p>
<p style="text-align: justify;"><span id="more-321"></span>First of all, I define a MySQL stored procedure to extract maximum, minimum and average values from these tables and to save them in a second &#8216;database_cubes_1h&#8217;, named so because this process will run every hour. Also, there is a table Stations in &#8216;database_main&#8217; (a third database to keep other application&#8217;s configurations), where all the stations ever installed are registered. We will use this table to know if a station exists and therefore its related table in database. A first draft would look like this:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p321code10'); return false;">View Code</a> MYSQL</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p32110"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
</pre></td><td class="code" id="p321code10"><pre class="mysql" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">-- -----------------------------------------------------</span>
<span style="color: #808080; font-style: italic;">-- Procedure `fill_cubes_1h`</span>
<span style="color: #808080; font-style: italic;">-- -----------------------------------------------------</span>
&nbsp;
<a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=DROP" rel="external"><span style="color: #990099; font-weight: bold;">DROP</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=PROCEDURE" rel="external"><span style="color: #990099; font-weight: bold;">PROCEDURE</span></a> <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">IF</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=EXISTS" rel="external"><span style="color: #990099; font-weight: bold;">EXISTS</span></a> fill_cubes_1h<span style="color: #000033;">;</span>
&nbsp;
DELIMITER <span style="color: #CC0099;">//</span>
&nbsp;
<a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=CREATE" rel="external"><span style="color: #990099; font-weight: bold;">CREATE</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=PROCEDURE" rel="external"><span style="color: #990099; font-weight: bold;">PROCEDURE</span></a> fill_cubes_1h<span style="color: #FF00FF;">&#40;</span>$StationID <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=INT" rel="external"><span style="color: #999900; font-weight: bold;">INT</span></a><span style="color: #FF00FF;">&#41;</span>
<a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=BEGIN" rel="external"><span style="color: #990099; font-weight: bold;">BEGIN</span></a>
  <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">IF</span></a> Station_ID <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=IN" rel="external"><span style="color: #990099; font-weight: bold;">IN</span></a> <span style="color: #FF00FF;">&#40;</span><a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=SELECT" rel="external"><span style="color: #990099; font-weight: bold;">SELECT</span></a> StationID <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=FROM" rel="external"><span style="color: #990099; font-weight: bold;">FROM</span></a> <span style="color: #008000;">`database`</span>.<span style="color: #008000;">`Stations`</span><span style="color: #FF00FF;">&#41;</span>
  <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">THEN</span></a>
    <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=SET" rel="external"><span style="color: #990099; font-weight: bold;">SET</span></a> @strSQL <span style="color: #CC0099;">=</span> <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/string-functions.html" rel="external"><span style="color: #000099;">CONCAT</span></a><span style="color: #FF00FF;">&#40;</span><span style="color: #008000;">'
      INSERT INTO `database<span style="color: #008080; font-weight: bold;">_</span>cubes<span style="color: #008080; font-weight: bold;">_</span>1h`.`Station<span style="color: #008080; font-weight: bold;">_</span>'</span><span style="color: #000033;">,</span>$StationID<span style="color: #000033;">,</span><span style="color: #008000;">'`
      SELECT
        SensorID,
        UNIX<span style="color: #008080; font-weight: bold;">_</span>TIMESTAMP(DATE<span style="color: #008080; font-weight: bold;">_</span>FORMAT(FROM<span style="color: #008080; font-weight: bold;">_</span>UNIXTIME(Time),&quot;<span style="color: #008080; font-weight: bold;">%</span>Y-<span style="color: #008080; font-weight: bold;">%</span>m-<span style="color: #008080; font-weight: bold;">%</span>d <span style="color: #008080; font-weight: bold;">%</span>H:00:00&quot;)) AS Hour,
        AVG(Value) AS Value,
        MAX(Value) AS ValueMax,
        MIN(Value) AS ValueMin
      FROM `database`.`Station<span style="color: #008080; font-weight: bold;">_</span>'</span><span style="color: #000033;">,</span>$StationID<span style="color: #000033;">,</span><span style="color: #008000;">'`
      WHERE
        Time &amp;gt;= UNIX<span style="color: #008080; font-weight: bold;">_</span>TIMESTAMP(DATE<span style="color: #008080; font-weight: bold;">_</span>FORMAT(NOW() - INTERVAL 1 HOUR,&quot;<span style="color: #008080; font-weight: bold;">%</span>Y-<span style="color: #008080; font-weight: bold;">%</span>m-<span style="color: #008080; font-weight: bold;">%</span>d <span style="color: #008080; font-weight: bold;">%</span>H:00:00&quot;))
      GROUP BY
        HOUR, SensorID
      ORDER BY
        HOUR ASC
    '</span><span style="color: #FF00FF;">&#41;</span><span style="color: #000033;">;</span>
&nbsp;
    PREPARE statement <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=FROM" rel="external"><span style="color: #990099; font-weight: bold;">FROM</span></a> @strSQL<span style="color: #000033;">;</span>
    EXECUTE statement <span style="color: #000033;">;</span>
    DEALLOCATE PREPARE statement <span style="color: #000033;">;</span>
&nbsp;
  <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">ELSE</span></a>
    <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=SET" rel="external"><span style="color: #990099; font-weight: bold;">SET</span></a> @foo <span style="color: #CC0099;">=</span> <span style="color: #008000;">&quot;&quot;</span><span style="color: #000033;">;</span>
&nbsp;
  <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">END</span></a> <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">IF</span></a><span style="color: #000033;">;</span>
&nbsp;
<a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">END</span></a><span style="color: #000033;">;</span><span style="color: #CC0099;">//</span>
&nbsp;
DELIMITER <span style="color: #000033;">;</span></pre></td></tr></table></div>

<p style="text-align: justify;">Basically, it composes a query to extract averages from one table and insert into another at once. This query is run as a prepared statement so that we can reuse the function for all the stations in our database, as long as tables are always named as Station_XYZ. But, what does exactly it do?</p>
<ol style="text-align: justify;">
<li>Use a statement like &#8216;INSERT INTO table SELECT * FROM another_table. It will copy data automatically if the number and format of columns of the SELECT output and the INSERT INTO input are the same.</li>
<li>As Time is stored in UNIX EPOCH time, it is converted to ISO time, then only the hour is extracted, then it is converted back to UNIX. The result of this process is be able to group the result set by hour, getting rid off minutes and seconds. &#8220;UNIX_TIMESTAMP(DATE_FORMAT(FROM_UNIXTIME(Time),&#8221;%Y-%m-%d %H:00:00&#8243;)) AS Hour&#8221;</li>
<li>A WHERE condition filters the results for the last hour: &#8216;Time &gt;= UNIX_TIMESTAMP(DATE_FORMAT(NOW() &#8211; INTERVAL 1 HOUR,&#8221;%Y-%m-%d %H:00:00&#8243;))&#8217;.</li>
<li>Finally, the whole result set is grouped by Time, to be able to calculate averages, maximums and minimums. This statement does the grouping by respecting the different sensors that might have sent data on the same hourly interval &#8220;GROUP BY HOUR, SensorID&#8221; and the following ones perform calculations &#8220;AVG(Value) AS Value, MAX(Value) AS ValueMax, MIN(Value) AS ValueMin&#8221;.</li>
</ol>
<p style="text-align: justify;">Up to now we seem to have resolved the performance problem. Hourly cubes can be constructed and we only would need to add a sort of cron job. But, it is not so easy&#8230; I haven&#8217;t mentioned yet that data is not received synchronously. That means, within a time frame of three or four hours we could receive the data from a lazy or out of range station. That may be problematic, so&#8230;</p>
<p style="text-align: justify;">I&#8217;ve changed my stored procedure to do as follows:</p>
<ol style="text-align: justify;">
<li>Calculate the whole last day in hourly tranches, while keep running every hour. &#8220;WHERE Time &gt;= UNIX_TIMESTAMP(DATE_FORMAT(NOW() &#8211; INTERVAL 1 DAY,&#8221;%Y-%m-%d %H:00:00&#8243;)) AND Time &lt;= UNIX_TIMESTAMP(DATE_FORMAT(NOW() &#8211; INTERVAL 1 HOUR,&#8221;%Y-%m-%d %H:59:59&#8243;))&#8221;</li>
<li>Modify the query to allow update in case that a hourly cube was already calculated. &#8220;ON DUPLICATE KEY UPDATE `Value` = VALUES(`Value`)&#8221;</li>
</ol>
<p style="text-align: justify;">Please note that in order to get it correctly running, there should be an effective way to detect a duplicate key. In my case, I&#8217;ve used all fields but the value as primary keys, instead of defining a new artificial key field. Thus, SensorID and Time are primary keys, so there should never be more than one value for each combination of both. Doing so, MySQL detects duplicate and updates the third column, value, by throwing no errors. The whole stored procedure would look like this:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p321code11'); return false;">View Code</a> MYSQL</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p32111"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
</pre></td><td class="code" id="p321code11"><pre class="mysql" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">-- -----------------------------------------------------</span>
<span style="color: #808080; font-style: italic;">-- Procedure `fill_cubes_1h`</span>
<span style="color: #808080; font-style: italic;">-- -----------------------------------------------------</span>
&nbsp;
<a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=DROP" rel="external"><span style="color: #990099; font-weight: bold;">DROP</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=PROCEDURE" rel="external"><span style="color: #990099; font-weight: bold;">PROCEDURE</span></a> <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">IF</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=EXISTS" rel="external"><span style="color: #990099; font-weight: bold;">EXISTS</span></a> fill_cubes_1h<span style="color: #000033;">;</span>
&nbsp;
DELIMITER <span style="color: #CC0099;">//</span>
&nbsp;
<a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=CREATE" rel="external"><span style="color: #990099; font-weight: bold;">CREATE</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=PROCEDURE" rel="external"><span style="color: #990099; font-weight: bold;">PROCEDURE</span></a> fill_cubes_1h<span style="color: #FF00FF;">&#40;</span>$StationID <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=INT" rel="external"><span style="color: #999900; font-weight: bold;">INT</span></a><span style="color: #FF00FF;">&#41;</span>
<a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=BEGIN" rel="external"><span style="color: #990099; font-weight: bold;">BEGIN</span></a>
&nbsp;
  <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">IF</span></a> Station_ID <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=IN" rel="external"><span style="color: #990099; font-weight: bold;">IN</span></a> <span style="color: #FF00FF;">&#40;</span><a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=SELECT" rel="external"><span style="color: #990099; font-weight: bold;">SELECT</span></a> StationID <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=FROM" rel="external"><span style="color: #990099; font-weight: bold;">FROM</span></a> <span style="color: #008000;">`database`</span>.<span style="color: #008000;">`Stations`</span><span style="color: #FF00FF;">&#41;</span>
  <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">THEN</span></a>
    <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=SET" rel="external"><span style="color: #990099; font-weight: bold;">SET</span></a> @strSQL <span style="color: #CC0099;">=</span> <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/string-functions.html" rel="external"><span style="color: #000099;">CONCAT</span></a><span style="color: #FF00FF;">&#40;</span><span style="color: #008000;">'
      INSERT INTO `database<span style="color: #008080; font-weight: bold;">_</span>cubes<span style="color: #008080; font-weight: bold;">_</span>1h`.`Station<span style="color: #008080; font-weight: bold;">_</span>'</span><span style="color: #000033;">,</span>$StationID<span style="color: #000033;">,</span><span style="color: #008000;">'`
      SELECT
        SensorID,
        UNIX<span style="color: #008080; font-weight: bold;">_</span>TIMESTAMP(DATE<span style="color: #008080; font-weight: bold;">_</span>FORMAT(FROM<span style="color: #008080; font-weight: bold;">_</span>UNIXTIME(Time),&quot;<span style="color: #008080; font-weight: bold;">%</span>Y-<span style="color: #008080; font-weight: bold;">%</span>m-<span style="color: #008080; font-weight: bold;">%</span>d <span style="color: #008080; font-weight: bold;">%</span>H:00:00&quot;)) AS Hour,
        AVG(Value) AS Value,
        MAX(Value) AS ValueMax,
        MIN(Value) AS ValueMin
        FROM `database`.`Station<span style="color: #008080; font-weight: bold;">_</span>'</span><span style="color: #000033;">,</span>$StationID<span style="color: #000033;">,</span><span style="color: #008000;">'`
      WHERE
        Time &amp;gt;= UNIX<span style="color: #008080; font-weight: bold;">_</span>TIMESTAMP(DATE<span style="color: #008080; font-weight: bold;">_</span>FORMAT(NOW() - INTERVAL 1 DAY,&quot;<span style="color: #008080; font-weight: bold;">%</span>Y-<span style="color: #008080; font-weight: bold;">%</span>m-<span style="color: #008080; font-weight: bold;">%</span>d <span style="color: #008080; font-weight: bold;">%</span>H:00:00&quot;)) AND
        Time &amp;lt;= UNIX<span style="color: #008080; font-weight: bold;">_</span>TIMESTAMP(DATE<span style="color: #008080; font-weight: bold;">_</span>FORMAT(NOW() - INTERVAL 1 HOUR,&quot;<span style="color: #008080; font-weight: bold;">%</span>Y-<span style="color: #008080; font-weight: bold;">%</span>m-<span style="color: #008080; font-weight: bold;">%</span>d <span style="color: #008080; font-weight: bold;">%</span>H:59:59&quot;))
      GROUP BY
        HOUR, SensorID
      ORDER BY
        HOUR ASC
      ON DUPLICATE KEY UPDATE `Value` = VALUES(`Value`)
    '</span><span style="color: #FF00FF;">&#41;</span><span style="color: #000033;">;</span>
&nbsp;
    PREPARE statement <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=FROM" rel="external"><span style="color: #990099; font-weight: bold;">FROM</span></a> @strSQL<span style="color: #000033;">;</span>
    EXECUTE statement <span style="color: #000033;">;</span>
    DEALLOCATE PREPARE statement <span style="color: #000033;">;</span>
&nbsp;
  <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">ELSE</span></a>
    <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=SET" rel="external"><span style="color: #990099; font-weight: bold;">SET</span></a> @foo <span style="color: #CC0099;">=</span> <span style="color: #008000;">&quot;&quot;</span><span style="color: #000033;">;</span>
&nbsp;
  <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">END</span></a> <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">IF</span></a><span style="color: #000033;">;</span>
&nbsp;
<a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">END</span></a> <span style="color: #000033;">;</span><span style="color: #CC0099;">//</span>
&nbsp;
DELIMITER <span style="color: #000033;">;</span></pre></td></tr></table></div>

<p style="text-align: justify;">The next step is to get this procedure running every hour for all the stations in the database. Now we are going to use our Stations table. The steps to follow are:</p>
<ol style="text-align: justify;">
<li>Request the highest station ID in Stations table</li>
<li>Since station ID&#8217;s are not sequential, get a way to determine if related table should exist</li>
<li>Tell the procedure to keep going if any exception raises</li>
<li>Run the loop until reach final station ID, and call the previous procedure passing current index as a parameter</li>
</ol>
<p style="text-align: justify;">The final result looks like:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p321code12'); return false;">View Code</a> MYSQL</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p32112"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
</pre></td><td class="code" id="p321code12"><pre class="mysql" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">-- -----------------------------------------------------</span>
<span style="color: #808080; font-style: italic;">-- Procedure `climaps_main`.`fill_all_cubes_1h`</span>
<span style="color: #808080; font-style: italic;">-- -----------------------------------------------------</span>
&nbsp;
<a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=DROP" rel="external"><span style="color: #990099; font-weight: bold;">DROP</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=PROCEDURE" rel="external"><span style="color: #990099; font-weight: bold;">PROCEDURE</span></a> <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">IF</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=EXISTS" rel="external"><span style="color: #990099; font-weight: bold;">EXISTS</span></a> fill_all_cubes_1h<span style="color: #000033;">;</span>
&nbsp;
DELIMITER <span style="color: #CC0099;">//</span>
&nbsp;
<a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=CREATE" rel="external"><span style="color: #990099; font-weight: bold;">CREATE</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=PROCEDURE" rel="external"><span style="color: #990099; font-weight: bold;">PROCEDURE</span></a> fill_all_cubes_1h<span style="color: #FF00FF;">&#40;</span><span style="color: #FF00FF;">&#41;</span>
<a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=BEGIN" rel="external"><span style="color: #990099; font-weight: bold;">BEGIN</span></a>
  <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=DECLARE" rel="external"><span style="color: #990099; font-weight: bold;">DECLARE</span></a> v <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=INTEGER" rel="external"><span style="color: #999900; font-weight: bold;">INTEGER</span></a><span style="color: #000033;">;</span>
  <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=DECLARE" rel="external"><span style="color: #990099; font-weight: bold;">DECLARE</span></a> m <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=INTEGER" rel="external"><span style="color: #999900; font-weight: bold;">INTEGER</span></a><span style="color: #000033;">;</span>
&nbsp;
  <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=DECLARE" rel="external"><span style="color: #990099; font-weight: bold;">DECLARE</span></a> CONTINUE <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=HANDLER" rel="external"><span style="color: #990099; font-weight: bold;">HANDLER</span></a> FOR SQLEXCEPTION <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=BEGIN" rel="external"><span style="color: #990099; font-weight: bold;">BEGIN</span></a> <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">END</span></a><span style="color: #000033;">;</span>
&nbsp;
  <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=SET" rel="external"><span style="color: #990099; font-weight: bold;">SET</span></a> v <span style="color: #CC0099;">=</span> <span style="color: #008080;">0</span><span style="color: #000033;">;</span>
  <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=SET" rel="external"><span style="color: #990099; font-weight: bold;">SET</span></a> m <span style="color: #CC0099;">=</span> <span style="color: #FF00FF;">&#40;</span><a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=SELECT" rel="external"><span style="color: #990099; font-weight: bold;">SELECT</span></a> StaID <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=FROM" rel="external"><span style="color: #990099; font-weight: bold;">FROM</span></a> climaps_main.Stations <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=ORDER%20BY" rel="external"><span style="color: #990099; font-weight: bold;">ORDER BY</span></a> StaID <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=DESC" rel="external"><span style="color: #990099; font-weight: bold;">DESC</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=LIMIT" rel="external"><span style="color: #990099; font-weight: bold;">LIMIT</span></a> <span style="color: #008080;">1</span><span style="color: #FF00FF;">&#41;</span><span style="color: #000033;">;</span>
&nbsp;
  WHILE v <span style="color: #CC0099;">&amp;</span>lt<span style="color: #000033;">;</span><span style="color: #CC0099;">=</span> m <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=DO" rel="external"><span style="color: #990099; font-weight: bold;">DO</span></a>
&nbsp;
    <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=CALL" rel="external"><span style="color: #990099; font-weight: bold;">CALL</span></a> fill_cubes_1h<span style="color: #FF00FF;">&#40;</span>v<span style="color: #FF00FF;">&#41;</span><span style="color: #000033;">;</span>
    <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=SET" rel="external"><span style="color: #990099; font-weight: bold;">SET</span></a> v <span style="color: #CC0099;">=</span> v <span style="color: #CC0099;">+</span> <span style="color: #008080;">1</span><span style="color: #000033;">;</span>
&nbsp;
  <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">END</span></a> WHILE<span style="color: #000033;">;</span>
&nbsp;
<a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">END</span></a><span style="color: #000033;">;</span><span style="color: #CC0099;">//</span>
&nbsp;
DELIMITER <span style="color: #000033;">;</span></pre></td></tr></table></div>

<p style="text-align: justify;">We&#8217;ve nearly finished! We have a way to build hourly cubes for a variable number of stations, and solving the problem of asynchronous data. We just need to create an event to run this last procedure, as we have stated above, every hour. This should work on MySQL 5.1</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p321code13'); return false;">View Code</a> MYSQL</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p32113"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code" id="p321code13"><pre class="mysql" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">-- -----------------------------------------------------</span>
<span style="color: #808080; font-style: italic;">-- Event `database_main`.`fill_cubes_1h`</span>
<span style="color: #808080; font-style: italic;">-- -----------------------------------------------------</span>
&nbsp;
<a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=DROP" rel="external"><span style="color: #990099; font-weight: bold;">DROP</span></a> EVENT <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">IF</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=EXISTS" rel="external"><span style="color: #990099; font-weight: bold;">EXISTS</span></a> fill_cubes_1h<span style="color: #000033;">;</span>
&nbsp;
DELIMITER <span style="color: #CC0099;">//</span>
&nbsp;
<a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=CREATE" rel="external"><span style="color: #990099; font-weight: bold;">CREATE</span></a> EVENT fill_cubes_1h
  <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=ON" rel="external"><span style="color: #990099; font-weight: bold;">ON</span></a> SCHEDULE EVERY <span style="color: #008080;">1</span> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=HOUR" rel="external"><span style="color: #9900FF; font-weight: bold;">HOUR</span></a>
  <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=DO" rel="external"><span style="color: #990099; font-weight: bold;">DO</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=BEGIN" rel="external"><span style="color: #990099; font-weight: bold;">BEGIN</span></a>
      <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=CALL" rel="external"><span style="color: #990099; font-weight: bold;">CALL</span></a> fill_all_cubes_1h<span style="color: #FF00FF;">&#40;</span><span style="color: #FF00FF;">&#41;</span><span style="color: #000033;">;</span>
  <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">END</span></a> <span style="color: #CC0099;">//</span>
&nbsp;
DELIMITER <span style="color: #000033;">;</span></pre></td></tr></table></div>

<p style="text-align: justify;">If for any reason we are not allowed to create events (all this stuff should be run as a user with whole access to the tables involved), or we are running a MySQL version lower than 5.1, a cron job should be run instead. Just get EXECUTE access on the database where the procedures have been created (on my case, database_main), and add this line to crontab:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p321code14'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p32114"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p321code14"><pre class="bash" style="font-family:monospace;"><span style="color: #000000;">0</span> <span style="color: #000000; font-weight: bold;">*</span> <span style="color: #000000; font-weight: bold;">*</span> <span style="color: #000000; font-weight: bold;">*</span> <span style="color: #000000; font-weight: bold;">*</span> mysql <span style="color: #660033;">-e</span> <span style="color: #ff0000;">'CALL database_main.fill_all_cubes_1h()'</span></pre></td></tr></table></div>

<p style="text-align: justify;">Please note that to get this statement running without asking for a password, you need to create a .my.cnf file in your home directory (UNIX systems)</p>
<p style="text-align: justify;">And that&#8217;s all!</p>
<p style="text-align: justify;">So, what do you think? What&#8217;s your method? Comments and feedback are much appreciated <img src='http://jorgealbaladejo.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://jorgealbaladejo.com/2010/05/11/implementing-a-database-cubes-system-on-mysql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Managing big data sets with MySQL</title>
		<link>http://jorgealbaladejo.com/2010/05/05/managing-big-data-sets-with-mysql/</link>
		<comments>http://jorgealbaladejo.com/2010/05/05/managing-big-data-sets-with-mysql/#comments</comments>
		<pubDate>Wed, 05 May 2010 15:23:31 +0000</pubDate>
		<dc:creator>Jorge Albaladejo</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Web Architecture]]></category>
		<category><![CDATA[big data sets]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[mysql]]></category>

		<guid isPermaLink="false">http://jorgealbaladejo.com/?p=319</guid>
		<description><![CDATA[I&#8217;m currently working on a database which stores, literally, a million of new data registers every day. They come from several hundred weather stations spread along the world, and need to be processed on real time. That&#8217;s a huge amount to be managed with a simple &#8211; but powerful &#8211; MySQL server, so I&#8217;ve had [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">I&#8217;m currently working on a database which stores, literally, a million of new data registers every day. They come from several hundred weather stations spread along the world, and need to be processed on real time. That&#8217;s a huge amount to be managed with a simple &#8211; but powerful &#8211; MySQL server, so I&#8217;ve had to design and implement a few tricks in order to succeed.</p>
<p style="text-align: justify;">In this post I&#8217;d like to talk about the main three techniques we&#8217;ve used to engage our high performance database, and the reasons to choose these solutions.</p>
<p style="text-align: justify;">First of all, MySQL innodb tables start <strong>degrading </strong>at some million registers  (7-10M on my current server, but not tested further), so the first though I had was: we need to <strong>divide if we want to conquer</strong>. Then, after some thinking about, I decided to split the big table into small chunks, and use a table for each station. That made the whole problem more affordable, and tables smaller enough not to become scary: the new problem was how to store about 5 M registers per year per table in our database.</p>
<p style="text-align: justify;">Of course, some logic in both the application controller and the data input server was needed to correctly place data registers. Additionally, tables get often fragmented so some cron jobs were needed to keep the database running smoothly. But there was still the problem of data growing. As long as registers were separated depending on the station, the scalability problem was solved: more tables can be added, even more servers with ranges of stations and a hash function to calculate what server is a given station hosted in. Once again were we talking about several million registers per year per table, and with a standart MySQL 5.1 server (the main problem with an start-up company tends to be funding, so we didn&#8217;t have anything better).</p>
<p style="text-align: justify;"><span id="more-319"></span></p>
<p style="text-align: justify;">Then a second solution came out: since 80% of queries are performed over the last few years of data, let&#8217;s <strong>move oldest registers to depot tables</strong>! This way, data used most often will be kept on relatively small (affordable, at least) tables, and the rest will be just stored.  So a big problem had turned into a matter of designing some queries over a bunch of tables, in a way that can be easily automated. Great! And it&#8217;s been so for a while, until we&#8217;ve realized that even with small tables, we are handing huge sets of data to represent evolution of physical variables along time. I&#8217;m talking about high resolution data, let&#8217;s say a measure every minute for some types of sensor, which makes sense to study minor variations along the day.</p>
<p style="text-align: justify;">It&#8217;s now when we start thinking about cubes &#8211; resumes. The real headache with big data sets starts when comparing a whole month range of values, which will produce several thousand registers to represent on a 800px wide plot graph&#8230; that&#8217;s basically a waste of server processor and memory resources, since we are providing a resolution which is not adapted to the circumstances.</p>
<p style="text-align: justify;">So now we have a third solution which is based on <strong>averages</strong>. MySQL &#8211; as other database engines &#8211; allows creating averages on the fly which is further better than relying these operations on the application layer. The problem beneath is that a big data set must be evaluated on demand, and this for every user on the website (we barely can cache MySQL responses because values change every 10 minutes). To fix it, we&#8217;ve decided to run these operations just once every hour, and store the results on cubes &#8211; tables with resumes &#8211; which would be consulted instead of the high density original ones. The algorithm to determine the table to look is simple: if the range of data is larger than several days, just use the hourly resolution instead. To automate this, we&#8217;ve added some naming convention, let&#8217;s say, all data tables are named the same way (based on the station ID), and only the database name (based on the data resolution) changes.</p>
<p style="text-align: justify;">To finish with, I&#8217;d like to advance the construction of this cubes generation process:</p>
<ol style="text-align: justify;">
<li> A stored procedure calculates averages for a given period for a given table</li>
<li>Another stored procedure launches the first one for all the tables; it is defined to be called from whatever time event handler we use</li>
<li>The event handler is defined, well in MySQL engine, well as a cron job</li>
</ol>
<p style="text-align: justify;">I&#8217;ll talk about the implementation details in further posts&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://jorgealbaladejo.com/2010/05/05/managing-big-data-sets-with-mysql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating Triggers in MySQL from PHP</title>
		<link>http://jorgealbaladejo.com/2009/02/25/creating-triggers-in-mysql-from-php/</link>
		<comments>http://jorgealbaladejo.com/2009/02/25/creating-triggers-in-mysql-from-php/#comments</comments>
		<pubDate>Wed, 25 Feb 2009 13:01:43 +0000</pubDate>
		<dc:creator>Jorge Albaladejo</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Php]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Architecture]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[stored procedures]]></category>
		<category><![CDATA[triggers]]></category>

		<guid isPermaLink="false">http://jorgealbaladejo.com/?p=283</guid>
		<description><![CDATA[On my last project, I needed to create tables periodically on a database, to partition data in several identical tables, named according to the year quarter. Instead of using MySQL 5.1 automatic partition, I preferred doing it in a more manual way, to allow accessing individual partitions if suitable to speed up queries. So I [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">On my last project, I needed to create tables periodically on a database, to partition data in several identical tables, named according to the year quarter. Instead of using MySQL 5.1 automatic partition, I preferred doing it in a more manual way, to allow accessing individual partitions if suitable to speed up queries.</p>
<p style="text-align: justify;">So I wrote a php script that would run with a cron job and every three months, create a new table, add it some triggers, and remap a MyISAM merged table on another database. Clear and easy, at the beginning. Everything went right until I went for the triggers creation&#8230;</p>
<p style="text-align: justify;"><span id="more-283"></span></p>
<p style="text-align: justify;">First of all, there is no way to use the values returned from a SELECT or SHOW statement on MySQL stored procedures: that means that tasks like remapping the merged table cannot be done with stored procedures on 5.1. Well, I would need a PHP script anyway so this wasn&#8217;t really disappointing. After all, I would create a couple of stored procedures (one to create table, another to create triggers) on the database definition, so that I would never need to know both table and triggers structure from any external script.</p>
<p style="text-align: justify;">That run with the table creation statement, but not with the triggers. As I used a prepared statement on MySQL to allow dynamic definition of tables and triggers (every quarter, a new table name), these technique has some limitations. One of them is as follows: prepared statements do not support yet create trigger sentences. So finally I had to move this part to the external script.</p>
<p style="text-align: justify;">And then started fun: mysql_query or mysqli_query php functions do not support multiple &#8211; statements (and triggers often use several because delimiters and some code is executed). What would I do?</p>
<p style="text-align: justify;">Well, perhaps there are smarter solutions, but I chose to write first a temporary file, and use it then as source for MySQL. Using &#8216;SOURCE file.sql&#8217; was tricky, because SOURCE is an instruction available on the MySQL client, not the server, so PHP cannot execute it. &#8216;LOAD DATA INFILE&#8217; was suggested in some forum&#8217;s solutions but this is limited to only data &#8211; and I wanted advanced SQL statements.</p>
<p style="text-align: justify;">Finally, the function &#8216;system&#8217; on PHP core gave me the solution: if I can call server&#8217;s system, I can just run mysql client telling it where the source SQL file is. This way &#8216;mysql -u user &#8211;password=pass &lt; file.sql&#8217; is actually mysql client who is doing the job for me.</p>
<p style="text-align: justify;">It is running, and working <img src='http://jorgealbaladejo.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://jorgealbaladejo.com/2009/02/25/creating-triggers-in-mysql-from-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Avoid deletions with triggers and MySQL</title>
		<link>http://jorgealbaladejo.com/2009/02/09/avoid-deletions-with-triggers-and-mysql/</link>
		<comments>http://jorgealbaladejo.com/2009/02/09/avoid-deletions-with-triggers-and-mysql/#comments</comments>
		<pubDate>Mon, 09 Feb 2009 12:22:05 +0000</pubDate>
		<dc:creator>Jorge Albaladejo</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[triggers]]></category>

		<guid isPermaLink="false">http://jorgealbaladejo.com/?p=277</guid>
		<description><![CDATA[Some times, we store valuable data that we would never want to lose. This is a particular fact when working with data for scientific, statistical purposes, like environmental analysis. In such a situation, we can rely on our software, but&#8230; what happens if any error is introduced on the application layer? Some valuable registers could [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">Some times, we store valuable data that we would never want to lose. This is a particular fact when working with data for scientific, statistical purposes, like environmental analysis.</p>
<p style="text-align: justify;">In such a situation, we can rely on our software, but&#8230; what happens if any error is introduced on the application layer? Some valuable registers could be lost and hard to identify and recover later. To avoid this effect, we&#8217;d rather prefer to implement some constraints in our database. I wouldn&#8217;t think that all the applications that connect to our database are going to be free of bugs, and our data is so valuable!</p>
<p style="text-align: justify;"><span id="more-277"></span></p>
<p style="text-align: justify;">A good way to implement this protection is using triggers. Triggers are SQL sentences that execute when (or after, or before) some action happens over the registers of a table. Usually, they can be defined to be executed BEFORE or AFTER an UPDATE, INSERT or DELETE action happens.</p>
<p style="text-align: justify;">So, the approach is: each time a register is told to be deleted from a certain table, the trigger we are going to set up will raise and tell the user (application, interface, whatsoever): &#8216;hey, listen, you cannot do that&#8217;. This trigger will be executed after the DELETE action, and will break the operation avoiding the deletion.</p>
<p style="text-align: justify;">Unfortunately, this is quite easy in other database servers like Oracle and MSSQL, where exceptions and errors can be handled and created by the user. With these servers, the content of the trigger would like more or less like this:</p>
<pre>throw_exception('cannot delete registers from this table');</pre>
<p style="text-align: justify;">And that&#8217;s all: the exception makes the entire request fail.</p>
<p style="text-align: justify;">But we don&#8217;t have this feature in MySQL (at least not in 5.1 version), and the way to get the same behavior is a bit tricky. If we cannot send an exception to alert the user that something has failed&#8230; well, at least we would be able to make some thing crash, and the server itself will tell the user about this failure!</p>
<p style="text-align: justify;">I guess that there are several ways of doing the same. This is my particular one: I try to insert empty values on the same table a register is about to be deleted. This throws an error because a trigger cannot modify the same table it has been raised from, and operation fails. An external user will not know, however that this error is due to the trigger I&#8217;ve added but OK, I&#8217;ll tell them. At least, I&#8217;ve prevented my table to lose data if it is not correctly managed by some applications. This is the code:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p277code16'); return false;">View Code</a> MYSQL</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p27716"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code" id="p277code16"><pre class="mysql" style="font-family:monospace;">DELIMITER <span style="color: #CC0099;">//</span>
&nbsp;
<a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=DROP" rel="external"><span style="color: #990099; font-weight: bold;">DROP</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=TRIGGER" rel="external"><span style="color: #990099; font-weight: bold;">TRIGGER</span></a> <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">IF</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=EXISTS" rel="external"><span style="color: #990099; font-weight: bold;">EXISTS</span></a> no_deletion_data<span style="color: #000033;">;</span>
&nbsp;
<a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=CREATE" rel="external"><span style="color: #990099; font-weight: bold;">CREATE</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=TRIGGER" rel="external"><span style="color: #990099; font-weight: bold;">TRIGGER</span></a> no_deletion_data
  BEFORE <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=DELETE" rel="external"><span style="color: #990099; font-weight: bold;">DELETE</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=ON" rel="external"><span style="color: #990099; font-weight: bold;">ON</span></a> <span style="color: #008000;">`Data`</span>
  <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=FOR%20EACH%20ROW" rel="external"><span style="color: #990099; font-weight: bold;">FOR EACH ROW</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=BEGIN" rel="external"><span style="color: #990099; font-weight: bold;">BEGIN</span></a>
    <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=INSERT" rel="external"><span style="color: #990099; font-weight: bold;">INSERT</span></a> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=INTO" rel="external"><span style="color: #990099; font-weight: bold;">INTO</span></a> <span style="color: #008000;">`Data`</span> <a href="http://search.mysql.com/search?site=refman-%35%31&amp;q=VALUES" rel="external"><span style="color: #990099; font-weight: bold;">VALUES</span></a><span style="color: #FF00FF;">&#40;</span><span style="color: #FF00FF;">&#41;</span><span style="color: #000033;">;</span>
  <a href="http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html" rel="external"><span style="color: #009900;">END</span></a><span style="color: #000033;">;</span><span style="color: #CC0099;">//</span>
&nbsp;
DELIMITER <span style="color: #000033;">;</span></pre></td></tr></table></div>

<p style="text-align: justify;">I know is not the smartest way to solve the problem, but at least is the cleanest I&#8217;ve got. Any suggestions? Well, at least, it works! <img src='http://jorgealbaladejo.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://jorgealbaladejo.com/2009/02/09/avoid-deletions-with-triggers-and-mysql/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PHP class dbhandler to deal with databases</title>
		<link>http://jorgealbaladejo.com/2007/05/24/clase-dbhandler-para-manejar-datos-de-una-base-de-datos/</link>
		<comments>http://jorgealbaladejo.com/2007/05/24/clase-dbhandler-para-manejar-datos-de-una-base-de-datos/#comments</comments>
		<pubDate>Thu, 24 May 2007 09:34:45 +0000</pubDate>
		<dc:creator>Jorge Albaladejo</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Php]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Architecture]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[handler]]></category>
		<category><![CDATA[mysql]]></category>

		<guid isPermaLink="false">http://labs.abc-webs.net/2007/05/24/clase-dbhandler-para-manejar-datos-de-una-base-de-datos/</guid>
		<description><![CDATA[Notice: Article only available in Spanish! Hemos visto en publicaciones anteriores cómo conectar a una base de datos mysql desde php, y cómo usar la función mysql_query para consultar datos. También hemos visto algunas nociones de seguridad en scripts y aplicaciones php. Ahora vamos a ver cómo encapsular estas funciones en una práctica clase que [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p><strong>Notice</strong>: Article only available in <strong>Spanish</strong>!</p></blockquote>
<p>Hemos visto en publicaciones anteriores <a href="http://jorgealbaladejo.com/?p=16" title="Cómo conectar a una base de datos mysql desde php">cómo conectar a una base de datos mysql desde php</a>, y <a href="http://jorgealbaladejo.com/?p=17" title="Cómo usar la función mysql_query para consultar datos">cómo usar la función mysql_query para consultar datos</a>. También hemos visto <a href="http://jorgealbaladejo.com/?p=18" title="seguridad en scripts y aplicaciones php">algunas nociones de seguridad</a> en scripts y aplicaciones php. Ahora vamos a ver cómo encapsular estas funciones en una práctica clase que nos permitirá instanciar objetos dbhandler y trabajar cómodamente con ellos.</p>
<p>Parto de  que el lector conoce el paradigma de la <a href="http://es.wikipedia.org/wiki/Programaci%C3%B3n_orientada_a_objetos" title="Programación Orientada a Objetos" target="_blank" rel="external">Programación Orientada a Objetos</a>. Básicamente, una clase es un molde que tiene ciertas peculiaridades como métodos y atributos, que pueden ser públicos (de libre acceso) o privados (sólo accesibles dentro de la propia clase). Con esta clase, se pueden instanciar objetos pertenecientes a dicha clase. si estuviéramos en la arena de la playa con un cubo, el cubo sería la clase, y las torres de arena serían los objetos o instancias del cubo de playa.</p>
<p><span id="more-19"></span>Las clases tienen una sintaxis especial, se trabaja con ellas de un modo distinto a como hacemos con la programación estructurada. Veamos un ejemplo:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p19code23'); return false;">View Code</a> PHP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p1923"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
</pre></td><td class="code" id="p19code23"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> dbhandler
<span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">//</span>
  <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$user</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$pass</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$host</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$database</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$identifier</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$results</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$resultset</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$query</span><span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">//</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/** 
   * constructor. initializes the object
   */</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> dbhandler<span style="color: #009900;">&#40;</span><span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$pass</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$database</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span> <span style="color: #339933;">,</span> <span style="color: #000088;">$host</span><span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;localhost&quot;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$user</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">&quot;&quot;</span> <span style="color: #339933;">||</span> <span style="color: #000088;">$pass</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">&quot;&quot;</span> <span style="color: #339933;">||</span> <span style="color: #000088;">$database</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #b1b100;">return</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">user</span>     <span style="color: #339933;">=</span> <span style="color: #000088;">$user</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">pass</span>     <span style="color: #339933;">=</span> <span style="color: #000088;">$pass</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">host</span>     <span style="color: #339933;">=</span> <span style="color: #000088;">$host</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">database</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$database</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Es decir, todo objeto de la clase dbhandler almacenará unos valores como clave, usuario, base de datos y host, lo que nos permitirá tener varios manejadores apuntando a distintas bases de datos, a distintos servidores en distintas máquinas, o autenticados con distintos usuarios con distintos permisos; esto nos deja la puerta abierta para usar esta clase en entornos bastante versátiles.</p>
<p>Ya tenemos lo que la clase debe &#8216;saber&#8217;. Ahora queremos que haga cosas. Queremos que se conecte, queremos que seleccione la base de datos, queremos que permita desconectar y queremos que lea una tabla concreta. Vamos con los métodos:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p19code24'); return false;">View Code</a> PHP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p1924"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
</pre></td><td class="code" id="p19code24"><pre class="php" style="font-family:monospace;"><span style="color: #009933; font-style: italic;">/**
 * connect to server
 */</span>
<span style="color: #000000; font-weight: bold;">function</span> connect<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">identifier</span><span style="color: #339933;">=</span> <span style="color: #339933;">@</span><a href="http://www.php.net/mysql_connect" rel="external"><span style="color: #990000;">mysql_connect</span></a> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">host</span><span style="color: #339933;">,</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">user</span><span style="color: #339933;">,</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">pass</span><span style="color: #009900;">&#41;</span>
    or <a href="http://www.php.net/die" rel="external"><span style="color: #990000;">die</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Error connecting to database with user &quot;</span><span style="color: #339933;">.</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">user</span> <span style="color: #339933;">.</span> <a href="http://www.php.net/mysql_error" rel="external"><span style="color: #990000;">mysql_error</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/**
 * select database
 */</span>
<span style="color: #000000; font-weight: bold;">function</span> selectDB<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #339933;">@</span><a href="http://www.php.net/mysql_select_db" rel="external"><span style="color: #990000;">mysql_select_db</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">database</span><span style="color: #339933;">,</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">identifier</span><span style="color: #009900;">&#41;</span>
    or <a href="http://www.php.net/die" rel="external"><span style="color: #990000;">die</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Error selecting database: &quot;</span><span style="color: #339933;">.</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">database</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/**
 * retrieves data from the selected fields of a certain table
 * @param table to read from
 * @param fields to be retrieved
 */</span>
<span style="color: #000000; font-weight: bold;">function</span> readTable<span style="color: #009900;">&#40;</span><span style="color: #000088;">$table</span><span style="color: #339933;">,</span><span style="color: #000088;">$fields</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">//variables</span>
  <span style="color: #000088;">$resultsArray</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/array" rel="external"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">//fields</span>
  <span style="color: #000088;">$fieldsList</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fields</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$key</span><span style="color: #339933;">=&gt;</span><span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$fieldsList</span> <span style="color: #339933;">.=</span> <span style="color: #000088;">$value</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;,&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">//remove last comma</span>
  <span style="color: #000088;">$fieldsList</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/substr" rel="external"><span style="color: #990000;">substr</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fieldsList</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span><a href="http://www.php.net/strlen" rel="external"><span style="color: #990000;">strlen</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fieldsList</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">//query</span>
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">query</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;SELECT &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$fieldsList</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot; FROM &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$table</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">resultset</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span><a href="http://www.php.net/mysql_query" rel="external"><span style="color: #990000;">mysql_query</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">query</span><span style="color: #339933;">,</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">identifier</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">results</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span><a href="http://www.php.net/mysql_num_rows" rel="external"><span style="color: #990000;">mysql_num_rows</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">resultset</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">results</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$result</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/mysql_fetch_array" rel="external"><span style="color: #990000;">mysql_fetch_array</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">resultset</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000088;">$resultsArray</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$result</span> <span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #b1b100;">return</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$resultsArray</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/**
 * close connection and free resources
 */</span>
<span style="color: #000000; font-weight: bold;">function</span> disconnect<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <a href="http://www.php.net/mysql_close" rel="external"><span style="color: #990000;">mysql_close</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">identifier</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Como acabamos de ver, a las variables de la clase o <strong>atributos</strong> se les llama mediante $this->nombredeatributo, siendo $this el objeto actual, instanciado de la clase dbhandler. Para llamar a los métodos de la clase, igualmente usaremos $this->nombredemetodo(); por ejemplo ahora que hemos definido métodos para conectar y seleccionar la base de datos, podemos hacer esto automáticamente cada vez que se crea un objeto de la clase dbhandler. ¿Cómo? poniendo las correspondientes lí­neas en el <strong>constructor</strong>, por supuesto.</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p19code25'); return false;">View Code</a> PHP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p1925"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code" id="p19code25"><pre class="php" style="font-family:monospace;"><span style="color: #009933; font-style: italic;">/**
 * constructor. initializes object
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> dbhandler<span style="color: #009900;">&#40;</span><span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$pass</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$database</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span> <span style="color: #339933;">,</span> <span style="color: #000088;">$host</span><span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;localhost&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$user</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">&quot;&quot;</span> <span style="color: #339933;">||</span> <span style="color: #000088;">$pass</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">&quot;&quot;</span> <span style="color: #339933;">||</span> <span style="color: #000088;">$database</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">return</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">user</span>     <span style="color: #339933;">=</span> <span style="color: #000088;">$user</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">pass</span>     <span style="color: #339933;">=</span> <span style="color: #000088;">$pass</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">host</span>     <span style="color: #339933;">=</span> <span style="color: #000088;">$host</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">database</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$database</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">connect</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">selectDB</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Esto nos da una idea de lo cómodo que va a ser trabajar con clases a partir de ahora. Puesto que los atributos $database, $host, $user, $pass, etc., son comunes para todos los métodos de la clase, no necesitan ser pasados como parámetros en las funciones, lo que agiliza mucho la programación y permite código más legible. Ya tenemos nuestra clase con atributos y métodos definida, ahora tenemos que usarla. Si guardamos todo el código de la clase en un archivo llamado class.dbhandler.php, podemos crear un script que lo use del siguiente modo:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p19code26'); return false;">View Code</a> PHP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p1926"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code" id="p19code26"><pre class="php" style="font-family:monospace;"><span style="color: #009933; font-style: italic;">/** 
 * script to connect to a database and read data from tables, with classes
 * @author Jorge Albaladejo Pomares [correo@jorgealbaladejo.com]
 * @license Creative Commons License http://creativecommons.org/licenses/by-sa/3.0/
 */</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//main classes</span>
<span style="color: #b1b100;">include</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'class.dbhandler.php'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//main script</span>
<span style="color: #000088;">$db</span>      <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> dbhandler<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'john_smith'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'h01y_GRail'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'pastafarian_food'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'localhost'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$fields</span>  <span style="color: #339933;">=</span> <a href="http://www.php.net/array" rel="external"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'id'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'name'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'special_powers'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$results</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$db</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">readTable</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'superheroes'</span><span style="color: #339933;">,</span><span style="color: #000088;">$fields</span><span style="color: #339933;">,</span><span style="color: #000088;">$token</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$results</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$result</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'id =&gt; '</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$result</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'id'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'title =&gt; '</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$result</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'title'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$db</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">disconnect</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Y la clase dbhandler finalmente quedará así­:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p19code27'); return false;">View Code</a> PHP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p1927"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
</pre></td><td class="code" id="p19code27"><pre class="php" style="font-family:monospace;"><span style="color: #009933; font-style: italic;">/** 
 * class to handle database connections and reading from tables
 * @author Jorge Albaladejo Pomares [correo@jorgealbaladejo.com]
 * @license Creative Commons License http://creativecommons.org/licenses/by-sa/3.0/
 */</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> dbhandler
<span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">//</span>
  <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$user</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$pass</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$host</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$database</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$identifier</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$results</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$resultset</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$query</span><span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">//</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/**
   * constructor. initializes object
   * @param user
   * @param pass
   * @param database
   * @param host
   */</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> dbhandler<span style="color: #009900;">&#40;</span><span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$pass</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$database</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span> <span style="color: #339933;">,</span> <span style="color: #000088;">$host</span><span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;localhost&quot;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$user</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">&quot;&quot;</span> <span style="color: #339933;">||</span> <span style="color: #000088;">$pass</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">&quot;&quot;</span> <span style="color: #339933;">||</span> <span style="color: #000088;">$database</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #b1b100;">return</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">user</span>     <span style="color: #339933;">=</span> <span style="color: #000088;">$user</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">pass</span>     <span style="color: #339933;">=</span> <span style="color: #000088;">$pass</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">host</span>     <span style="color: #339933;">=</span> <span style="color: #000088;">$host</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">database</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$database</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">connect</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">selectDB</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/**
   * connect to server
   */</span>
  <span style="color: #000000; font-weight: bold;">function</span> connect<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">identifier</span><span style="color: #339933;">=</span> <span style="color: #339933;">@</span><a href="http://www.php.net/mysql_connect" rel="external"><span style="color: #990000;">mysql_connect</span></a> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">host</span><span style="color: #339933;">,</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">user</span><span style="color: #339933;">,</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">pass</span><span style="color: #009900;">&#41;</span>
      or <a href="http://www.php.net/die" rel="external"><span style="color: #990000;">die</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Error connecting to database with user '&quot;</span><span style="color: #339933;">.</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">user</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;': &quot;</span> <span style="color: #339933;">.</span> <a href="http://www.php.net/mysql_error" rel="external"><span style="color: #990000;">mysql_error</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/**
   * select database
   */</span>
  <span style="color: #000000; font-weight: bold;">function</span> selectDB<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #339933;">@</span><a href="http://www.php.net/mysql_select_db" rel="external"><span style="color: #990000;">mysql_select_db</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">database</span><span style="color: #339933;">,</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">identifier</span><span style="color: #009900;">&#41;</span>
      or <a href="http://www.php.net/die" rel="external"><span style="color: #990000;">die</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Error selecting database: &quot;</span><span style="color: #339933;">.</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">database</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/**
   * queries the selected fields from a certain table in the database
   * @param table
   * @param fields
   */</span>
  <span style="color: #000000; font-weight: bold;">function</span> readTable<span style="color: #009900;">&#40;</span><span style="color: #000088;">$table</span><span style="color: #339933;">,</span><span style="color: #000088;">$fields</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">//variables</span>
    <span style="color: #000088;">$resultsArray</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/array" rel="external"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">//fields</span>
    <span style="color: #000088;">$fieldsList</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fields</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$key</span><span style="color: #339933;">=&gt;</span><span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000088;">$fieldsList</span> <span style="color: #339933;">.=</span> <span style="color: #000088;">$value</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;,&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">//remove last comma</span>
    <span style="color: #000088;">$fieldsList</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/substr" rel="external"><span style="color: #990000;">substr</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fieldsList</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span><a href="http://www.php.net/strlen" rel="external"><span style="color: #990000;">strlen</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fieldsList</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">//query</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">query</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;SELECT &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$fieldsList</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot; FROM &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$table</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">resultset</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span><a href="http://www.php.net/mysql_query" rel="external"><span style="color: #990000;">mysql_query</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">query</span><span style="color: #339933;">,</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">identifier</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">results</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span><a href="http://www.php.net/mysql_num_rows" rel="external"><span style="color: #990000;">mysql_num_rows</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">resultset</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">results</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$result</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/mysql_fetch_array" rel="external"><span style="color: #990000;">mysql_fetch_array</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">resultset</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
      <span style="color: #009900;">&#123;</span>
        <span style="color: #000088;">$resultsArray</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$result</span> <span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">return</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$resultsArray</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #009933; font-style: italic;">/**
   * close connection and free resources
   */</span>
  <span style="color: #000000; font-weight: bold;">function</span> disconnect<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <a href="http://www.php.net/mysql_close" rel="external"><span style="color: #990000;">mysql_close</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">identifier</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Esta clase se puede completar añadiendo métodos para todo tipo de propósitos: búsquedas sobre la base de datos, consulta de datos según orden y paginación, se le puede implementar un método que devuelva los resultados en html o xml en lugar de devolverlos en un array, se le puede añdir un destructor que se encargue de liberar los recursos cuando se deja de utilizar el objeto&#8230;</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p19code28'); return false;">View Code</a> PHP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p1928"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code" id="p19code28"><pre class="php" style="font-family:monospace;"><span style="color: #009933; font-style: italic;">/** 
 * destruct
 */</span>
<span style="color: #000000; font-weight: bold;">function</span> destroy<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> 
<span style="color: #009900;">&#123;</span>
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">disconnect</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">//settype(&amp;amp;$this, 'null'); //may not work with php4</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Y lo mejor de todo, podemos reutilizar fácilmente el código para cualquiera de nuestras aplicaciones. Y podemos escribir aplicaciones de una forma muchísimo más sencilla y cómoda que con programación estructurada. En general, todo son ventajas <img src='http://jorgealbaladejo.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://jorgealbaladejo.com/2007/05/24/clase-dbhandler-para-manejar-datos-de-una-base-de-datos/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Reading data from a MySQL database with PHP</title>
		<link>http://jorgealbaladejo.com/2007/05/19/lectura-de-una-tabla-de-una-base-de-datos/</link>
		<comments>http://jorgealbaladejo.com/2007/05/19/lectura-de-una-tabla-de-una-base-de-datos/#comments</comments>
		<pubDate>Sat, 19 May 2007 20:06:27 +0000</pubDate>
		<dc:creator>Jorge Albaladejo</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Php]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Architecture]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[queries]]></category>

		<guid isPermaLink="false">http://labs.abc-webs.net/2007/05/19/lectura-de-una-tabla-de-una-base-de-datos/</guid>
		<description><![CDATA[Notice: article only available in Spanish! Ya he explicado en otro post cómo conectar a una base de datos mysql desde php. Ahora voy a explicar cómo trabajar con esta base de datos, en concreto mostrar los datos de una tabla. Parto de la premisa de que se ha aprendido a utilizar el script anteriormente [...]]]></description>
			<content:encoded><![CDATA[<blockquote style="text-align: justify;"><p><strong>Notice</strong>: article only available in <strong>Spanish</strong>!</p></blockquote>
<p style="text-align: justify;">Ya he explicado en otro post <a href="http://jorgealbaladejo.com/?p=16"title="Cómo conectar a una base de datos mysql desde php" >cómo conectar a una base de datos mysql desde php</a>. Ahora voy a explicar cómo trabajar con esta base de datos, en concreto mostrar los datos de una tabla.</p>
<p style="text-align: justify;">Parto de la premisa de que se ha aprendido a utilizar el script anteriormente citado para la conexión y selección de base de datos, y que se ha configurado correctamente para acceder a una BD donde existe la tabla &#8216;superheroes&#8217;, con los campos &#8216;id&#8217;, &#8216;name&#8217;, &#8216;special_powers&#8217;.</p>
<p style="text-align: justify;"><strong>Vamos allá</strong> <strong>: </strong>leemos los datos de la tabla. Para ello, usamos la función php mysql_query(); para ejecutar código sql en el servidor de bases de datos. Vamos a leer los campos importantes (en este caso, los tres) de la tabla superheroes.</p>
<p style="text-align: justify;"><span id="more-17"></span></p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p17code35'); return false;">View Code</a> PHP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p1735"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code" id="p17code35"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$query</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;SELECT id, name, special_powers FROM superheroes&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$resultset</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span><a href="http://www.php.net/mysql_query" rel="external"><span style="color: #990000;">mysql_query</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$query</span><span style="color: #339933;">,</span><span style="color: #000088;">$identifier</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">@</span><a href="http://www.php.net/mysql_num_rows" rel="external"><span style="color: #990000;">mysql_num_rows</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$resultset</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$result</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/mysql_fetch_array" rel="external"><span style="color: #990000;">mysql_fetch_array</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$resultset</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$result</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'id'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">' | '</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$result</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'name'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">' | '</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$result</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'special_powers'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span>  <span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p style="text-align: justify;">Una vez hemos leído los datos podemos inmediatamente mostrarlos por pantalla, o almacenarlos en una matriz asociativa para emplearlos más adelante. Por ejemplo, cambiando el código</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p17code36'); return false;">View Code</a> PHP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p1736"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p17code36"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$result</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/mysql_fetch_array" rel="external"><span style="color: #990000;">mysql_fetch_array</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$resultset</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$result</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'id'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">' | '</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$result</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'name'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">' | '</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$result</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'special_powers'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span>  <span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p style="text-align: justify;">por</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p17code37'); return false;">View Code</a> PHP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p1737"><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code" id="p17code37"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$i</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$result</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/mysql_fetch_array" rel="external"><span style="color: #990000;">mysql_fetch_array</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$resultset</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #000088;">$resultsArray</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$i</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$result</span>  <span style="color: #339933;">;</span>
  <span style="color: #000088;">$i</span><span style="color: #339933;">++;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p style="text-align: justify;">de modo que más adelante podremos mostrar estos datos como mejor nos convenga.</p>
<p style="text-align: justify;">Hay que tener en cuenta que el script de <a href="http://jorgealbaladejo.com/?p=16"title="Cómo conectar a una base de datos mysql desde php" >conexión a base de datos</a> que ya vimos, abre y cierra la conexión en un mismo paso. Por tanto, ahora tendremos que integrarlo con la parte de lectura de datos que acabamos de ver. El código resultante quedará así­:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p17code38'); return false;">View Code</a> PHP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p1738"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
</pre></td><td class="code" id="p17code38"><pre class="php" style="font-family:monospace;"><span style="color: #009933; font-style: italic;">/** 
 * script to connect to a database and read tables
 * @author Jorge Albaladejo Pomares [correo@jorgealbaladejo.com]
 * @license Creative Commons License http://creativecommons.org/licenses/by-sa/3.0/
 */</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//variables</span>
<span style="color: #000088;">$host</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;localhost&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;john_smith&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$pass</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;h01y_GRail&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$db</span>   <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;pastafarian_food&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//connection</span>
<span style="color: #000088;">$identifier</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span><a href="http://www.php.net/mysql_connect" rel="external"><span style="color: #990000;">mysql_connect</span></a> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$host</span><span style="color: #339933;">,</span><span style="color: #000088;">$user</span><span style="color: #339933;">,</span><span style="color: #000088;">$pass</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$identifier</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <a href="http://www.php.net/die" rel="external"><span style="color: #990000;">die</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Error connecting to database: &quot;</span><span style="color: #339933;">.</span><a href="http://www.php.net/mysql_error" rel="external"><span style="color: #990000;">mysql_error</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//selecting the database</span>
<span style="color: #000088;">$db_selected</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/mysql_select_db" rel="external"><span style="color: #990000;">mysql_select_db</span></a> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$db</span><span style="color: #339933;">,</span> <span style="color: #000088;">$identifier</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$db_selected</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <a href="http://www.php.net/die" rel="external"><span style="color: #990000;">die</span></a> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Cannot select database: &quot;</span> <span style="color: #339933;">.</span> <a href="http://www.php.net/mysql_error" rel="external"><span style="color: #990000;">mysql_error</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000088;">$query</span>     <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;SELECT id, name, special_powers FROM superheroes&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$resultset</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span><a href="http://www.php.net/mysql_query" rel="external"><span style="color: #990000;">mysql_query</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$query</span><span style="color: #339933;">,</span><span style="color: #000088;">$identifier</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">@</span><a href="http://www.php.net/mysql_num_rows" rel="external"><span style="color: #990000;">mysql_num_rows</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$resultset</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$result</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/mysql_fetch_array" rel="external"><span style="color: #990000;">mysql_fetch_array</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$resultset</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$result</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'id'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">' | '</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$result</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'name'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">' | '</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$result</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'special_powers'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span> <span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//close connection</span>
<a href="http://www.php.net/mysql_close" rel="external"><span style="color: #990000;">mysql_close</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$identifier</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p style="text-align: justify;">Como vemos, el código queda un poco sucio, así que lo vamos a organizar un poquito creando tres funciones: la primera, conectará con la base de datos, la segunda, leerá la tabla, y la tercera realizará la conexión. Vamos allá.</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p17code39'); return false;">View Code</a> PHP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p1739"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
</pre></td><td class="code" id="p17code39"><pre class="php" style="font-family:monospace;"><span style="color: #009933; font-style: italic;">/** 
 * script to connect to a database and read from tables, organized with functions
 * @author Jorge Albaladejo Pomares [correo@jorgealbaladejo.com]
 * @license Creative Commons License http://creativecommons.org/licenses/by-sa/3.0/
 */</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/**
 * Connect to a database with default parameters
 * @return the connection identifier
 */</span>
<span style="color: #000000; font-weight: bold;">function</span> connect<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">//variables</span>
  <span style="color: #000088;">$host</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;localhost&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;john_smith&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$pass</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;h01y_GRail&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$db</span>   <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;pastafarian_food&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">//</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">//connection</span>
  <span style="color: #000088;">$identifier</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span><a href="http://www.php.net/mysql_connect" rel="external"><span style="color: #990000;">mysql_connect</span></a> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$host</span><span style="color: #339933;">,</span><span style="color: #000088;">$user</span><span style="color: #339933;">,</span><span style="color: #000088;">$pass</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$identifier</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <a href="http://www.php.net/die" rel="external"><span style="color: #990000;">die</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Error connecting to database: &quot;</span><span style="color: #339933;">.</span><a href="http://www.php.net/mysql_error" rel="external"><span style="color: #990000;">mysql_error</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">//selecting database</span>
  <span style="color: #000088;">$db_selected</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/mysql_select_db" rel="external"><span style="color: #990000;">mysql_select_db</span></a> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$db</span><span style="color: #339933;">,</span> <span style="color: #000088;">$identifier</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$db_selected</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <a href="http://www.php.net/die" rel="external"><span style="color: #990000;">die</span></a> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Cannot select database: &quot;</span> <span style="color: #339933;">.</span> <a href="http://www.php.net/mysql_error" rel="external"><span style="color: #990000;">mysql_error</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #b1b100;">return</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$identifier</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/** 
 * retrieves the selected fields from a certain table in a database
 * @param table to retrieve from
 * @param fields to retrieve
 */</span>
<span style="color: #000000; font-weight: bold;">function</span> readTable<span style="color: #009900;">&#40;</span><span style="color: #000088;">$table</span><span style="color: #339933;">,</span><span style="color: #000088;">$fields</span><span style="color: #339933;">,</span><span style="color: #000088;">$identifier</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">//variables</span>
  <span style="color: #000088;">$resultsArray</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/array" rel="external"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">//fields</span>
  <span style="color: #000088;">$fieldsList</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fields</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$key</span><span style="color: #339933;">=&gt;</span><span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$fieldsList</span> <span style="color: #339933;">.=</span> <span style="color: #000088;">$value</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;,&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">//remove last comma</span>
  <span style="color: #000088;">$fieldsList</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/substr" rel="external"><span style="color: #990000;">substr</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fieldsList</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span><a href="http://www.php.net/strlen" rel="external"><span style="color: #990000;">strlen</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fieldsList</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">//query</span>
  <span style="color: #000088;">$query</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;SELECT &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$fieldsList</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot; FROM &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$table</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$resultset</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span><a href="http://www.php.net/mysql_query" rel="external"><span style="color: #990000;">mysql_query</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$query</span><span style="color: #339933;">,</span><span style="color: #000088;">$identifier</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">@</span><a href="http://www.php.net/mysql_num_rows" rel="external"><span style="color: #990000;">mysql_num_rows</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$resultset</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$i</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$result</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/mysql_fetch_array" rel="external"><span style="color: #990000;">mysql_fetch_array</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$resultset</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000088;">$resultsArray</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$i</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$result</span>  <span style="color: #339933;">;</span>
      <span style="color: #000088;">$i</span><span style="color: #339933;">++;</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #b1b100;">return</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$resultsArray</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/** 
 * closes connection and frees resources
 * @param identifier of the connection to close
 */</span>
<span style="color: #000000; font-weight: bold;">function</span> disconnect<span style="color: #009900;">&#40;</span><span style="color: #000088;">$identifier</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">//TODO: some routines to clean resources, data, variables, etc.</span>
  <a href="http://www.php.net/mysql_close" rel="external"><span style="color: #990000;">mysql_close</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$identifier</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/**
 * main script 
 */</span>
<span style="color: #000088;">$token</span>   <span style="color: #339933;">=</span> connect<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$fields</span>  <span style="color: #339933;">=</span> <a href="http://www.php.net/array" rel="external"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'id'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'name'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'special_powers'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$results</span> <span style="color: #339933;">=</span> readTable<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'superheroes'</span><span style="color: #339933;">,</span><span style="color: #000088;">$fields</span><span style="color: #339933;">,</span><span style="color: #000088;">$token</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$results</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$result</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fields</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$key</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$key</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot; =&gt; &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$result</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$key</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;&lt;br /&gt;&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;&lt;br /&gt;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
disconnect<span style="color: #009900;">&#40;</span><span style="color: #000088;">$token</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p style="text-align: justify;">Hecho esto, lo más práctico es almacenar las funciones que acabamos de crear en un archivo externo de librerías y funciones útiles, y así reducir al mínimo el tamaño de nuestro script. En este ejemplo, las funciones connect(), readTable() y disconnect() han sido movidas a un archivo llamado functions.php en el mismo directorio que el script principal. El código finalmente queda como sigue­:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p17code40'); return false;">View Code</a> PHP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p1740"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code" id="p17code40"><pre class="php" style="font-family:monospace;"><span style="color: #009933; font-style: italic;">/** 
 * script to connect to a database and read from tables, organized with functions
 * @author Jorge Albaladejo Pomares [correo@jorgealbaladejo.com]
 * @license Creative Commons License http://creativecommons.org/licenses/by-sa/3.0/
 */</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//main functions</span>
<span style="color: #b1b100;">include</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'functions.php'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// main script</span>
<span style="color: #000088;">$token</span>   <span style="color: #339933;">=</span> connect<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$fields</span>  <span style="color: #339933;">=</span> <a href="http://www.php.net/array" rel="external"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'id'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'name'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'special_powers'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$results</span> <span style="color: #339933;">=</span> readTable<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'superheroes'</span><span style="color: #339933;">,</span><span style="color: #000088;">$fields</span><span style="color: #339933;">,</span><span style="color: #000088;">$token</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$results</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$result</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fields</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$key</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$key</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot; =&gt; &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$result</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$key</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;&lt;br /&gt;&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;&lt;br /&gt;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
disconnect<span style="color: #009900;">&#40;</span><span style="color: #000088;">$token</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p style="text-align: justify;">Hay que tener en cuenta que este script puede ser <strong>inseguro</strong> si se le ataca con sql injection, de esto hablaré más adelante en otras publicaciones.</p>
]]></content:encoded>
			<wfw:commentRss>http://jorgealbaladejo.com/2007/05/19/lectura-de-una-tabla-de-una-base-de-datos/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Connecting to a MySQL database from PHP</title>
		<link>http://jorgealbaladejo.com/2007/05/18/conexion-a-una-base-de-datos-mysql/</link>
		<comments>http://jorgealbaladejo.com/2007/05/18/conexion-a-una-base-de-datos-mysql/#comments</comments>
		<pubDate>Fri, 18 May 2007 23:23:44 +0000</pubDate>
		<dc:creator>Jorge Albaladejo</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Php]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Architecture]]></category>
		<category><![CDATA[connection]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[mysql]]></category>

		<guid isPermaLink="false">http://labs.abc-webs.net/2007/05/18/conexion-a-una-base-de-datos-mysql/</guid>
		<description><![CDATA[Notice: Article only available in Spanish! El primer paso para trabajar con scripts y aplicaciones en php que conectan con bases de datos mysql, es crear una conexión. Una conexión en php devuelve un identificador que será utilizado para cada transacción, consulta, etc, que se realice sobre la base de datos. Para comenzar, hacen falta [...]]]></description>
			<content:encoded><![CDATA[<blockquote style="text-align: justify;"><p><strong>Notice</strong>: Article only available in <strong>Spanish</strong>!</p></blockquote>
<p style="text-align: justify;">El primer paso para trabajar con scripts y aplicaciones en php que conectan con bases de datos mysql, es crear una conexión. Una conexión en php devuelve un identificador que será utilizado para cada transacción, consulta, etc, que se realice sobre la base de datos.</p>
<p style="text-align: justify;">Para comenzar, hacen falta tres datos del proveedor de servicios de alojamiento: nombre de la base de datos, nombre de usuario y contraseña de acceso. En php desde la versión 3 existe la función mysql_connect();</p>
<p style="text-align: justify;"><span id="more-16"></span></p>
<p style="text-align: justify;"><code>mysql_connect($host,$usuario,$clave);</code></p>
<p style="text-align: justify;">Donde host suele ser &#8216;localhost&#8217; (a menos que se quiera conectar a bases de datos en distintas máquinas, en cuyo caso el proveedor de servicio debe proporcionar este dato), y usuario y clave son los datos de acceso a dicho servidor de base de datos.</p>
<p style="text-align: justify;">Una vez establecida la conexión, se obtiene un identificador que se usará en cada operación que se realice sobre la base de datos. El siguiente paso es seleccionar una base de datos. Ésta debe haber sido creada de antemano, y el usuario con el que se realiza la conexión debe tener permisos de acceso a ella.</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p16code44'); return false;">View Code</a> PHP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p1644"><td class="line_numbers"><pre>1
2
</pre></td><td class="code" id="p16code44"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$identifier</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/mysql_connect" rel="external"><span style="color: #990000;">mysql_connect</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$host</span><span style="color: #339933;">,</span><span style="color: #000088;">$usuario</span><span style="color: #339933;">,</span><span style="color: #000088;">$clave</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<a href="http://www.php.net/mysql_select_db" rel="external"><span style="color: #990000;">mysql_select_db</span></a> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$database</span> <span style="color: #339933;">,</span> <span style="color: #000088;">$identifier</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p style="text-align: justify;">Por último, una vez terminada la ejecución, hay que liberar los recursos utilizados cerrando la conexión</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p16code45'); return false;">View Code</a> PHP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p1645"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p16code45"><pre class="php" style="font-family:monospace;"><a href="http://www.php.net/mysql_close" rel="external"><span style="color: #990000;">mysql_close</span></a> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$identifier</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p style="text-align: justify;">A partir de ahora, todas las consultas realizadas se efectuarán sobre la base de datos seleccionada. Un script completo para conexión a base de datos quedaría como sigue:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?" rel="external"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p16code46'); return false;">View Code</a> PHP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p1646"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
</pre></td><td class="code" id="p16code46"><pre class="php" style="font-family:monospace;"><span style="color: #009933; font-style: italic;">/**
 * script to connect to a database
 * @author Jorge Albaladejo Pomares [correo@jorgealbaladejo.com]
 * @license Creative Commons License http://creativecommons.org/licenses/by-sa/3.0/
 */</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//variables</span>
<span style="color: #000088;">$host</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;localhost&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;john_smith&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$pass</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;h01y_GRail&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$db</span>   <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;pastafarian_food&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//connection</span>
<span style="color: #000088;">$identifier</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span><a href="http://www.php.net/mysql_connect" rel="external"><span style="color: #990000;">mysql_connect</span></a> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$host</span><span style="color: #339933;">,</span><span style="color: #000088;">$user</span><span style="color: #339933;">,</span><span style="color: #000088;">$pass</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$identifier</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <a href="http://www.php.net/die" rel="external"><span style="color: #990000;">die</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Error connecting to database: &quot;</span><span style="color: #339933;">.</span><a href="http://www.php.net/mysql_error" rel="external"><span style="color: #990000;">mysql_error</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//selecting database</span>
<span style="color: #000088;">$db_selected</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/mysql_select_db" rel="external"><span style="color: #990000;">mysql_select_db</span></a> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$db</span><span style="color: #339933;">,</span> <span style="color: #000088;">$identifier</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$db_selected</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <a href="http://www.php.net/die" rel="external"><span style="color: #990000;">die</span></a> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Cannot use database: &quot;</span> <span style="color: #339933;">.</span> <a href="http://www.php.net/mysql_error" rel="external"><span style="color: #990000;">mysql_error</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Close connection</span>
<a href="http://www.php.net/mysql_close" rel="external"><span style="color: #990000;">mysql_close</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$identifier</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://jorgealbaladejo.com/2007/05/18/conexion-a-una-base-de-datos-mysql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

