1

Topic: MySQL 101 - basics for the beginner

I've decided to take the plunge and start using MySQL databases in my websites.  (Other than for pre-packaged applications like PunBB - I'm already doing that.)  I've read a couple tutorials and I have a basic beginner-level understanding.

The first step is to connect.  I want to organize the files in a "proper" way, so I studied how PunBB does it:

index.php
> include/common.php
> > config.php
> > include/functions.php
> > include/dblayer/common_db.php
> > > include/dblayer/mysql.php

I think I understand everything except for what's going on in the last file.  The 'common_db.php' points to another file depending on the type of database being used.  Simple enough.   So then you go to the 'mysql.php' file and there's about 100 lines of code that make no sense to me.

It looks like I need to, "Load the appropriate DB layer class."  What's a simple way to do this?  (as compared to the way it's done in the mysql.php file)

Here's an excerpt from mysql.php as a reminder of what it contains:

// Make sure we have built in support for MySQL
if (!function_exists('mysql_connect'))
    exit('This PHP environment doesn\'t have MySQL support built in.');

//
// Return current timestamp (with microseconds) as a float.
//
if (defined('PUN_SHOW_QUERIES'))
{
    function get_microtime()
    {
        list($usec, $sec) = explode(' ', microtime());
        return ((float)$usec + (float)$sec);
    }
}


class DBLayer
{
    var $prefix;
    var $link_id;
    var $query_result;
    var $row = array();

    var $saved_queries = array();
    var $num_queries = 0;


    function DBLayer($db_host, $db_username, $db_password, $db_name, $db_prefix, $p_connect)
    {
        $this->prefix = $db_prefix;

        if ($p_connect)
            $this->link_id = @mysql_pconnect($db_host, $db_username, $db_password);
        else
            $this->link_id = @mysql_connect($db_host, $db_username, $db_password);

        if ($this->link_id)
        {
            if (@mysql_select_db($db_name, $this->link_id))
                return $this->link_id;
            else
                error('Unable to select database. '.mysql_error(), __LINE__, __FILE__);
        }
        else
            error('Unable to connect to MySQL server. '.mysql_error(), __LINE__, __FILE__);
    }


    function query($sql = '', $transaction = 0)
    {
        unset($this->query_result);

        if ($sql != '')
        {
            if (defined('PUN_SHOW_QUERIES'))
                $q_start = get_microtime();

            $this->query_result = @mysql_query($sql, $this->link_id);
        }

        if ($this->query_result)
        {
            if (defined('PUN_SHOW_QUERIES'))
                $this->saved_queries[] = array($sql, sprintf('%.5f', get_microtime() - $q_start));

            ++$this->num_queries;

            unset($this->row[$this->query_result]);

            return $this->query_result;
        }
        else
            return ($transaction == PUN_TRANS_END) ? true : false;
    }


    function result($query_id = 0, $row = 0){}
    function fetch_array($query_id = 0){}
    function fetch_assoc($query_id = 0){}
    function fetch_row($query_id = 0){}
    function num_rows($query_id = 0){}
    function affected_rows(){}
    function insert_id(){}
    function get_num_queries(){}
    function get_saved_queries()    {}
    function free_result($query_id = false)    {}
    function error() {}
    function close() {}
}

Re: MySQL 101 - basics for the beginner

Well, "Load the appropriate DB layer class" simply means to include the PHP script, in your case mysql.php. Just make sure you've included config.php before you do that.

"Programming is like sex: one mistake and you have to support it for the rest of your life."

3

Re: MySQL 101 - basics for the beginner

I went ahead and took the simple route.  Rather than supporting other databases, I wrote it to just work with my specific database - eliminating the need for DB layer classes, and put all of the DB login info in the config file.  It turned out to be a lot easier than I thought.  Thanks though.

Re: MySQL 101 - basics for the beginner

I have written an article (in my sig) with information that everyone should know about using MySQL.

5 (edited by D9r 2005-04-24 19:12)

Re: MySQL 101 - basics for the beginner

What's a good way to set up the database for multiple categories?  I'm writing a cms for an events calendar.  Each event falls in any of several categories.  What's the best way to set up the database table so that it can be sorted by category? 

* One column with each row containing a list of categories (separated by commas or whatever)?
* One column with each row containing a list of category_ids (and a separate table 'categories')?
* One column for each category, containing the value 1 or 0?

Example:

id | date | location | category        | moderators
```````````````````````````````````````````````````
1  |      |          |meeting,cmnty,tca|                 
2  |      |          |meeting,tca      |   
3  |      |          |festival,comnty  |

6

Re: MySQL 101 - basics for the beginner

In other words, what is a good way to set up the table in order to sort by category?

cat=meeting => 1,2
cat=cmnty    => 1,3
etc

If anyone understands databases better than I do, I'd appreciate some help.  Thanks.

Re: MySQL 101 - basics for the beginner

what about
events (event id, date, ...)
eventcat (event is, cat id)
categorys (cat id, name, ...)

8 (edited by D9r 2005-04-25 22:14)

Re: MySQL 101 - basics for the beginner

Something like this?  (a lookup table that lists the categories for each event)

'events'
ID     Event_date  Etc
1             -
2             -
3             -
4             -

'categories'
ID   Category
1    meeting
2    festival
3    tca

'event_category_lookup'
Event_ID     Category_ID
1             1
1             3
2             2
2             3

Re: MySQL 101 - basics for the beginner

Classic On-To-Many relationship.  Your concept is right on.  A lookup table is a good way to set up one-to-many relationships.

Re: MySQL 101 - basics for the beginner

Actually, the above database layout represents a many-to-many relationship. An event can "belong" to more than one category and a category can contain more than one event. When implementing a one-to-many relationship, you generally don't need a "link table". Topics and posts are an example. A topic can contain more than one post, but a post can only be contained within one topic. This relationship is implemented by simply including a topic ID in the posts table.

"Programming is like sex: one mistake and you have to support it for the rest of your life."

Re: MySQL 101 - basics for the beginner

Doh, my bad. I confused myself.  At first glance it looked like a one-to-many relationship.  And your right, one-to-many does not typically need a "look-up" table.  I just got done doing a setup where I thought the structure would be one-to-many, but after finding I could not get things sorted correctly, I added a look-up table...  which made it a many-to-many relationship.

12

Re: MySQL 101 - basics for the beginner

I should probably buy a book an MySQL and learn some database basics.  I've gotten by mostly on guessing up to this point. wink

Re: MySQL 101 - basics for the beginner

Well, let us know what problems you encounter, things you want to know, etc. I'll be here to help smile

14

Re: MySQL 101 - basics for the beginner

I read your blog entry on FreeBSD.  Interesting stuff -- I might actually try that someday.

Re: MySQL 101 - basics for the beginner

Yeah, my sig changed since the first post, so my article can be found at http://www.bwongar.com/articles/

16

Re: MySQL 101 - basics for the beginner

Good article on FreeBSD, I went down similar paths.

I also began with Redhat, I'm running Debian now and my firewall is running OpenBSD.

17

Re: MySQL 101 - basics for the beginner

I'm having trouble figuring out TIMESTAMPs.
I want to create a table with a `posted_on` column and an `edited_on` column.  The first one would be set once and stay that value (not auto-update), and the second one would begin with no value and only get the current timestamp if the row is updated.  It seems a simple thing to ask, but I've spent hours studying the online manual and it still doesn't make sense.

What's a good way to do it?  This is my latest guess:

Create the table with these:
`posted_on` TIMESTAMP NULL DEFAULT 0,
`edited_on` TIMESTAMP NULL DEFAULT 0,

And insert values when posting or editing with:
INSERT INTO t2 VALUES (CURRENT_TIMESTAMP);

So there's no more auto-updating; it just updates when a query tells it to.

18

Re: MySQL 101 - basics for the beginner

What you do is that you put the Timestamp field that you want to update automatically first
MySQL automatically updates the first timestamp field it finds, but only that one.
So my tables normally look like

id int(11) not null auto-increment,
mytext varchar(48),
update_date timestamp,
create_date timestamp

This way the field "update_date" gets updated automatically.
When I first insert a row there I would go like this:

insert into MYTABLE(mytext, create_date) values('.$mytext.', NOW())

that's all, the rest is filled automatically.
On update I would do

update MYTABLE set mytext='.$mytext.' where id=$id

and the update_date field will be updated automatically.

The German PunBB Site:
PunBB-forum.de

19

Re: MySQL 101 - basics for the beginner

Oh, that is so simple.  Thanks!

20 (edited by D9r 2005-09-25 22:20)

Re: MySQL 101 - basics for the beginner

I have a simple events calendar set up:  http://tuckertoday.com/events/
*  The tables were created by writing a query and entering it through phpMyAdmin;
*  Data was entered manually through phpMyAdmin (I'll create a webform later);
*  and Results are displayed on the webpage using some basic MySQL and PHP commands.

My question is:
For a large block of text that includes several parapraphs, linebreaks, lists, links, etc, how should the HTML tags be added to the data?  I think I understand in theory what I should do -- the data from the database gets processed through a RegExp and/or parser.php and linebreaks are converted to BR tags and BBCode is converted to other tags.  Something like that anyway.  Can anyone give me some pointers?  I'll study the punBB source to see how it does it, but some guidance would be appreciated because I'm still new at this.

Related Threads:
Reg Exp -- http://punbb.org/forums/viewtopic.php?id=8899

-