Agent and exception customization in PHP5 OOP programming

Source: Internet
Author: User
Tags date comparison functions ini integer mysql mysql insert string back
php5| programming

I have not learned PHP before, just a project need to use recently, I decided to learn while doing PHP.

1 in the SQL statement you can add a restriction condition: Left (text,20) only the first 20 words of the text;

2 can be used as pagination using limit FromRecord, recordnum, for example, limit 0,30 indicates that 30 records are traversed from the first record;

The 32-table connection can be: Table1 join table2 using X (x is a common field for two tables), or table1 join table2 on table1.x = table2.x

4 PHP Access querystring can be used $page = $_get[' page '];

Or

$page = $_request[' page '];

Which request can obtain post,get,querystring and other characters;

Before that, I saw a more stupid way:

Parse_str ($_server[' query_string '), $output); First, save the query string into an array $output

$page = $output [' page ']; And then indexed by variable name

5 The comparison of date functions in PHP is actually a string comparison;

6 Date type data in MySQL can be: 2000-02-03,2002.02.03,2002.2.3,02.02.03,02.2.3, which means there must be a month and a day, and must be '-' or '. ' Apart.

7 data () to get the time zone problem, I found that the time is less than 8 hours, because php.ini inside the default configuration is GTM U.S. time zone;

WORKAROUND: You can modify the php.ini:

[Date]

; Defines the default timezone used by the date functions

Date.timezone = "Asia/shanghai"

Alternatively, use the date () function plus date_default_timezone_set ("PRC");

81 period of time, debugging in the body always said I was missing ")", the cost of a half-day is intval ($_post[' Consumetype '), the field in the database is varchar (50), in the Zengsong table I do not use the Intval function, Because its ID is 1,2 ... integers and char can convert to each other, but in the other two tables it's a5a,sp07-01, but how does it convert to int?

Let's look at the declaration of the Intval function:

The Intval function is used to get the integer value of the variable: int intval (mixed var [, int base])

Returns the integer value of the variable var by using a specific binary conversion (the default is decimal).

var can be any scalar type. Intval () cannot be used for array or object.

9 Another inexplicable problem, with user name 1 login can be, change a ' Bo ' Landing, the system is in place error: Said I run time error: Missing ""), Nnd. Check that the variable type in the SQL statement is inconsistent with the database,

In PHP when you convert from floating-point numbers to integers, the digits are rounded up (drop decimal places).

11 in the MySQL INSERT statement, if the self-added field is to be replaced with (NULL).

PHP in Chinese garbled??? Problem solving:

Adding mysql_query ("Set names ' gb2312") after mysql_connect;

Or the full use of UTF8 code, you do not have to add the above statement.

There are function Iconv ("GBK", "UTF8", "strings"), and various character encoding conversions can be implemented.

Iv. using inheritance to throw custom exceptions

In PHP, you can throw any object as an exception, but first the exception should inherit from PHP's built-in exception class. By creating your own custom exception, you can record other information about the error, such as creating an entry in a log file or doing anything you like. Your custom exception is going to do the following several things:

· Log the error message from the DB object generated by the query.

· Give exact details of the line code where the query error occurred-by checking the call stack.

· Displays error messages and query text-when converted to a string.

To get error messages and query text, you need to make multiple changes to the Dbquery object.

1. A new protected property-compiledquery-needs to be added to the class.

2. The compile () function updates the query CompiledQuery properties using query text.

3. A function that retrieves the compiled query text should be added.

4. You should also add a function-it gets the DB object that is currently associated with the Dbquery object.

Listing 4. Throws an exception.

Class Dbquery
{
/**
* Store the compiled version of the query after calling compile () or execute ()
*
* @var String $compiledQuery
*/
protected $compiledQuery;
/**
* Returns a compiled query without executing it.
* @ parameter: Mixed $params, ... Query parameters
* @ return: string-compiled query
*/
Public function compile ($params = ')
{
if (! $this->stored_procedure) {
throw new Exception ("stored procedure not initialized.");
}
/* Instead of parameters * *
$params = Func_get_args (); Get the function parameters
$query = Preg_replace ("/() Compile_callback ($params, 1," 2 ") ', $this->query);
return ($this->compiledquery = $this->add_strings ($query)); Put the string back in the query
}
Public Function Getdb ()
{
return $this->db;
}
Public Function Getcompiledquery ()
{
return $this->compiledquery;
}
}
Now you can implement the Queryexception class. Notice how you traverse the call stack to find the location in the script that actually caused the error. This applies precisely when the Dbquery object that throws an exception is a subclass of a Dbquery object that inherits from it.

List 5:queryexception class.

/**
* Query exception
*
* If an error occurs when an attempt is made to execute a query, an error is thrown by the {@link Dbquery} object
*/
Class Queryexception extends Exception
{
/**
* Query Text
*
* @var string $querytext;
*/
protected $QueryText;
/**
* Error number/code from the database
*
* @var String $errorcode
*/
protected $ErrorNumber;
/**
* Error messages from the database
*
* @var String $errormessage
*/
protected $ErrorMessage;
/**
* Class Builder
*
* @ parameter: Dbquery $db, is the query object that throws an exception
*/
Public function __construct (dbquery $query)
{
/* Get Call stack * *
$backtrace = $this->gettrace ();
/* Set the rows and files to where the error actually occurred.
if (count ($backtrace) > 0) {
$x = 1;
/* If the query class is inherited, then we need to ignore the call made by the subclass.
while (! isset ($backtrace [$x] [' line ']) | |
(Isset ($backtrace [$x] [' class ']) && is_subclass_of ($backtrace [$x] [' class '], ' dbquery ')] | |
(Strpos (Strtolower (@ $backtrace [$x] [' function ']), ' Call_user_func ')!== false) {
/* loop execution, as long as there is no line number or called function is a subclass of the Dbquery class * *
+ + $x;
/* If we reach the bottom of the stack, then we use the first caller/
if (($x) >= count ($backtrace)) {
$x = count ($backtrace);
Break
}
}
/* If the above loop is executed at least once, then we can subtract it by 1 to find the actual line of code that caused the error
*/
if ($x!= 1) {
$x-= 1;
}
/* Finally, we can set the file and line number, which should reflect the SQL statement that caused the error.
$this->line = $backtrace [$x] [' line '];
$this->file = $backtrace [$x] [' file '];
}
$this->querytext = $query->getcompiledquery ();
$this->errornumber = $query->getdb ()->errno ();
$this->errormessage = $query->getdb ()->error ();
/* Call exception constructor for superclass * *
Parent::__construct (' Query Error ', 0);
}
/**
* Get the query text
*
* @ return string query text
*/
Public Function Getquerytext ()
{
return $this->querytext;
}
/**
* Get the error number
*
* @ return string error number
*/
Public Function Geterrornumber ()
{
return $this->errornumber;
}
/**
* Get the error message
*
* @ return string error message
*/
Public Function GetErrorMessage ()
{
return $this->errormessage;
}
/**
* Called when the object is converted to a string.
* @ return string
*/
Public Function __tostring ()
{
$output = "Query Error in {$this->file} to line {$this->line}nn";
$output. = "Query: {$this->querytext}n";
$output. = "Error: {$this->errormessage} ({$this->errornumber}) nn";

return $output;
}
}

At this point, the code you see at the beginning of this section works.

V. Conclusion

In this article, you see how the agent maps the DB interface associated with the query to an operation on a particular query result. The Dbquery object exposes the same function, such as FETCH_ASSOC (), as the DB object. However, these all work against a single query. You also learned how to use custom exceptions to give details-when and where an error occurred, and how they better control the handling of the error



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.