Build an e-commerce application with PHP4 and PostgreSQL

zhaozj2021-02-16  46

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: '. $ Title. '</ Title> </ Head> <body> ';} // HTML code FUNCTION Site_footer () {return' </ body> </ html> ';} // is used to reduce the code function query ($ SQL) {Global $ conn; return pg_exec ($ conn, $ sql);} // let each page automatically start session or save the session status session_start ();> So, our first version of the library is already available It is connected to the database, providing simple HTML code. Each page in our site includes: <? Php <n> Require ($ document_root. '/ Include / common.php'); echo site_header ('Demonstration page'); / * page logic processing * / echo site_footer () Generally, when building an application, it is wise to separate logic and actual representation (in us is HTML). So I put the logic in the function.</p> <p>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.</p> <p>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.</p> <p>Table IV, adding items to cart <php function cart_add_item ($ item_id, $ quantity = 1) {global $ customer_id, $ feedback, $ conn;? $ Res = query ( "SELECT * FROM item_inventory WHERE part_number = '$ item_id' "); if (! $ res || pg_numrows ($ RES) <1) {$ feedback. = pg_errorMessage ($ conn); $ feedback. = 'error-item not found'; return false;} else {// Check Whether the item is placed in a shopping cart, if yes, add the quantity // Start transaction Query ("Select * from cart_Items". "Where part_number = '$ itm_id' and customer_id = '$ Customer_ID 'For update "); if (! $ Res || pg_numrows ($ r) <1) {// If there is no item, a newly inserted $ res = query (" INSERT INTO CART_ITEMS "(Customer_ID, Part_Number, Quantity "." "Values ​​($ Customer_ID, $ ITEM_ID, $ Quantity)"); if (! $ Res || pg_cmdtuples ($ res) <1) {$ feedback. = Pg_errorMessage ($ conn); $ feedback. = 'Error -couldn't INSERT INTO CART '; // Despite no things changed, it is best to roll back the transaction Query ("rollback");} else {query ("commit"); return true;}}} Else {// There is already this item $ res = query ("Update Cart_Items Set Quantity = Quantity $ Quantity". "WHERE Part_NUMBER = '$ item_ID' AND Customer_id = '$ CUSTOMER_ID' "); if (! $ res || pg_cmdtuples ($ res) <1) {$ feedback. = pg_errorMessage ($ conn); $ feedback. = 'Error-Couldn't Increment Quantity In Cart' Query ("rollback"); Return False;} else {// Submit change, formally updated the database. Query ("commit"); return true;}}}}?> Now we can build new customers, and they add items. We need to check out and lose stocks. This part is the most complex, fully utilizing the transaction function of Postgres and the advanced lock mechanism. We start with Postgres's Select ... for update syntax, which can effectively lock the currently selected row to update and submit changes in a transaction.</p> <p>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.</p> <p>$ 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'</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-26054.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="26054" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.036</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'k5RRUyg5SkDpDuXq_2FhtWJ14mhO5EyxTFIe3XjR7nHfpvm48Q2bV0vl05DL9IKscwOoPqnTvJ9qc5Jh2rj6rdxg_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>