Pls check my style.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I'm very new to PHP so I have yet to develop a style. I would love to
see how you would write this fragment of code so that I might get a
better understanding of good PHP techniques and best practices.

Consider the following fragment:

class Account {
   function store() {
      switch ($this->state) {
         case 1:
            $link = mysql_connect('localhost', DBUSER, DBPASS) 
               OR die(mysql_error());
            if (!mysql_select_db(DBNAME, $link)) 
               die(mysql_error());
            $query = sprintf("INSERT INTO acct " .
                  "(name,real_name,password,email) " .
                  "VALUES (%s,%s,%s,%s)",
                        quote_smart($this->name),
                        quote_smart($this->real_name),
                        quote_smart($this->password),
                        quote_smart($this->email));
            $result = mysql_query($query);
            $e = mysql_errno();
            mysql_close($link);
            if (!$result) {
               if ($e == 1062) { 
                  global $err;
                  $err = ERR_DUPLICATE_USERNAME;
                  return FALSE;
               }
               die(mysql_error());
            }

            return $result;
         default:
            $err = ERR_INVALID_ACCT_STATE;

Some specific questions I have are:

1) It seems mysql_connect can "die" internally. At least this is what I
see if the username or password is incorrect. Is there a way to suppress
that behavior so that I can display an appropriate message rather than
too much information or nothing?

2) Must I always call mysql_select_db or can that be folded into the
connect or somehow specify a default db in some settings somewhere?

3) I use a global $err and define() custom ERR_* strings to communicate
errors similar to errno in C. Is this a respecible method or is a
different technique preferred?

4) Can I rely on mysql_errno() values as I do above to determine if a
username already exists (1062 is the value returned by mysql_errno()
when trying to insert a record with a username that already exists).

Note that I call $acct->store() and handle the error. Is this the
preferred technique? It seems redundant and racey to query the database
to determine if the username exists and then insert if available.

Thanks,
Mike

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux