Built with PHP4 and PostgreSQL by Xu Yongjun published on October 16, 2001 09:06. This article demonstrates the application of PHP and PostgressQL in e-commerce through a simple web application. Not long ago, if you want to archite a serious web application, you means that you buy a price of Cold Fusion licenses, as well as a business database service program like Sybase, add Sun Server. Fortunately, this day is not returned. With a large number of newly matured free database markets and Apache users, some alternative products have been equivalent, and even more than these proprietary software. One of the better open source software is PHP, a very much like Perl script language, as well as PostgreSQL, a very powerful object-oriented database. If you combine both, you can design from a simple message book to a huge web-based financial software. PHP provides brain and Postgres offers developed muscles. Here is a very basic PHP shopping cart and inventory applications to make full use of Postgres's transaction function. Source code push the tidal source? PhpBuilder.com download. The first thing to mention is the structure of the application. In my PHP web application, I always set a comprehensive library, and every page of the website will be used, and it is called Common.php to store in the include directory. This library will handle daily tasks, such as database connections, user authentication, head / tail files, etc. Place these functions in a place, our application looks very clean and easy to maintain. Table 1: Demonstration library code common.php: Php // Connect Postgres database $ conn = pg_pconnect ("user = TIM DBNAME = DB_EXAMPLE"); // See if the connection is successful if (! $ Conn) {// If Failure reports an error echo pg_errorMessage ($ conn); exit;} // site header file Function site_header ($ title) {return '
However, the method of PHP uses function calls, the disadvantage is that there is no standard error handling process, if there is an error inside the function, the program of the call function cannot pass the error message to the user. In other languages, such as Java, you can use the TRY / CATCH statement to process. My solution is that each function always returns true or false, set a $ feedback global variable, so that the result can be tested. There is now a project called PEAR (http://pear.php.net/) in making standardized error handling and data inventory efforts, but so far, it is not stable. Below is an example of using my true / false method call function: Php $ result = function_call_name (); if (! $ Result) {// Display error Echo $ feedback;} else {// There is no error, continue} ?> Ok, let us start thinking about shopping! We need some basic data structures to store data from the shopping cart. For example, we need an inventory database to list the name, part number, price and quantity. We also need to record the items purchased by customers ... too complicated, write these. Table 2, shopping cart data structure Cart.SQL: # Establish a sequential table to generate customer numbers. # Each ID is separated from a number of numbers to prevent others to guess shopping cart numbers. create sequence seq_customer_id increment 26 start 1; create table customers (customer_id int not null default 0 primary key, name text, address text, credit_card text, total_order MONEY DEFAULT '$ 0.00'); create table cart_items (cart_item serial, customer_id int, part_number int , quantity int); create index idx_cart_customer on cart_items (customer_id); create table item_inventory (part_number serial, name text, price float, inventory int); this structure gives us a basic shopping cart, in order to standardize the database schema, I set up an independent The table is used to list the contents of the customer's shopping cart. In this way, let customers' shopping carts can have multiple items and can be easily connected to inventory databases. Now we need to consider the 鲈 谙 痰 甑 甑 甑 δ 芰 δ 芫 芫>>>>>> 芫 芫 芫 芫>>>> 徊>>>>> >>> >>>>>>>> >鍪 鍪 童 鞯 呱 辏 剐 剐 芏 芏 芏 δ δ δ 埽 芏 δ These will wait for yourself to do it. I started from a simple generation of a customer, all of which is actually acquired in the customer's information, inserting the customer table, and registering the customer number in the session management of PHP4 built-in.
Table 3, establish a new customer PHP Function Cart_New () {Global $ Conn, $ Customer_ID, $ feedback; // Start a transaction Query ("Begin Work"); // Query Next Customer Number $ RES = Query "SELECT NextVAL ('seq_customer_id')"); // Check error if (! $ Res || pg_numrows ($ res) <1) {$ feedback. = Pg_errorMessage ($ conn); $ feedback. = 'Error - Database DIDN 't return next value'; Query ("rollback"); return false;} else {$ Customer_ID = PG_RESULT ($ RES, 0, 0); // Register to Session Session_register ('Customer_ID'); // Insert New Customer $ RES = Query ("INSERT INTO CUSTOMERS (" $ CUSTOMER_ID ') ""); // Check error if (! $ RES || pg_cmdtuples ($ res) <1) {$ feedback. = pg_errorMessage ($ conn) ); $ feedback. = 'Error - COULDN' @ qRRRRE ("rollback"); return false;} else {// commit this transaction query ("commit"); return true;}}}? > This code is relatively long, although I don't like it, but it demonstrates how to properly start and end postgres transactions and how to check the query statements. I want to use the same error monitoring program in all the code, I think you should do this. Need to plan if you check the wrong handling method, are you directly terminated? Still re-run the query statement, or continue to execute, and if there is anything? Carefully consider the results of each option. For example, if you can't get the next customer's Customer_ID, then create a new customer's record, you can't update her address, you can't add items to your shopping cart, right? Now, let's take a look at the process of adding items, this step is relatively easy, before adding items, check if the item is in the database. This is safe because the item number comes from the browser, which may be tampered with. Once you know the existence of items, we can test whether it is already in the shopping cart, if you have already put it, add one, rather than inserting a line, otherwise, insert a number of records to the shopping cart.
Table IV, adding items to cart
By using this statement in a transaction, you can guarantee the consistency of the data. In other databases, such as MySQL, you cannot lock the specified data rows, and get incorrect data and use inventory statistics. This statement can also utilize subqueries, and the standard feature of another database. Subqueries allow you to combine two queries, after locking, we need to reduce the corresponding stock in accordance with the items of the shopping cart. For the sake of simplicity, we don't report the wrong inventory, and turn the inventory into negative numbers. You can write a management page, check items for negative stocks, and order. Finally, we update the credit card in the customer table, purchase information, total purchase amount, withdraw the session of this customer. Table 5, checkout, reduce Stock PHP Function Cart_Checkout ($ Credit_Card, $ Address, $ Name) {Global $ Conn, $ Customer_ID, $ feedback; // Transaction Start Query ("Begin Work"); // Lock inventory The corresponding line of the table is handled by a simple subquery. $ SQL = "Select * from item_inventory". "WHERE Part_Number". "IN (SELECT Part_Number from Cart_Items". "WHERE CUSTOMER_ID = '$ CUSTOMER_ID')". "for update"; $ res = query ($ sql); if ($ RES || PG_NUMROWS <1) {$ feedback. = pg_errorMessage ($ conn); $ feedback. = 'Error - no items locked'; query ("end work); return false;} Else The {// Inventory of the inventory has been locked, and the items and quantities from the shopping cart.
$ SQL = "SELECT Part_Number, Quantity". "WHERE CUSTOMER_ID = '$ Customer_ID'". "ORDER BY Part_Number Desc"; $ RES2 = query ($ sque); if (! $ r2 || pg_numrows $ RES2) <1) {$ feedback. = pg_errorMessage ($ conn); $ feedback. = 'error - no items in cart'; query ("end work"; returnif false;} else {$ rows = pg_numrows ($ RES2); // Update inventory balance for ($ I = 0; $ I <$ ) {// Read Shopping Cart Data $ Quantity = PG_RESULT ($ RES2, $ I, 'Quantity'); $ Item_ID = pg_result ($ RES2, $ I, 'Part_Number'); $ RES3 = Query ("Update Item_Inventory". "" Where part_number = '$ item_id'); if (! $ r3 || pg_cmdtuples ($ RES3) <1) {$ feedback. = Pg_errorMessage ($ conn); $ feedback. = 'Error - Updating Inventory failed'; query ("rollback"); return false;}} // Inventory update end Get the total amount of this order and update the customer record $ RES = query ("Select SUM (CART_ITEMS.QUANTITITY * ITEM_INVENTORY.PRICE". "" "" "" "Where cart_items.customer_id = '$ customer_id'". " And cart_items.part_number = item_inventory.part_number "); if (! $ R || pg_numrow s ($ RES) <1) {// couldn't get Order Total $ feedback. = pg_errorMessage ($ conn); $ feedback. = 'error - couldn't get Order Total'; query ("rollback); return False;} else {// Update customer table $ total = pg_result ($ RES, 0, 0); $ RES = Query ("Update Customers", Name = '$ Name', " "total_order = '$ total', CREDIT_CARD = '$ CREDIT_CARD'". "Where customer_id = '$ customer_id'