PHP - Apply Different Tax Rate Based On Customer Roles
Hi My website is a Wordpress WooCommerce. I modified the PHP function that worked well before I added the multiple customer roles. I have regular customers and regular and tier-level wholesalers. I live in Canada and with have two taxes to apply (GST & PST). We also have customers/wholesalers that get exempted from one tax (PST) only or both taxes. I have one regular wholesale role with two tax exemption roles: 'wholesale_customer', 'wholesale_pst_exempt', 'wholesale_tax_exempt'. I have 4 tier levels wholesale roles with each their own tax exemption roles: 'wholesale_silvia_silver', 'wholesale_silvia_gold', 'wholesale_silvia_premium', 'wholesale_silvia_union' 'wholesale_silvia_silver_pst_exempt', 'wholesale_silvia_gold_pst_exempt', 'wholesale_silvia_premium_pst_exempt', 'wholesale_silvia_union_pst_exempt' 'wholesale_silvia_silver_tax_exempt', 'wholesale_silvia_gold_tax_exempt', 'wholesale_silvia_premium_tax_exempt', 'wholesale_silvia_union_tax_exempt' The tier levels are new and I'm trying to update my existing function that applies different tax rates based on customer user roles. I also have filters to alter the shipping tax for the different tax class based on the customer role. Here are the function and filter that I have updated to add the additional tier level wholesale roles. The changes I've made are not working because I don't see the tax exemptions. Both taxes are always being applied. Can someone help me figure out what I've done wrong to the code that stopped it from working? I'm not proficient in PHP, so was trying my best to make this work. /* * APPLY DIFFERENT TAX RATE BASED ON CUSTOMER USER ROLE * (Code compacted in one unique hook instead of 5 functions with the same hook) */ function all_custom_tax_classes( $tax_class, $product ) { global $current_user; // Getting the current user $curr_user = wp_get_current_user(); $curr_user_data = get_userdata($current_user->ID); // 1 customer_tax_exempt /* special tax rate: zero if role: Customer Tax Exempt */ /*if ( in_array( 'customer_tax_exempt', $curr_user_data->roles ) ) $tax_class = 'CustomerTaxExemptClass'; // 2 customer_pst_exempt // special tax rate: charge only GST if role: Customer PST Exempt if ( in_array( 'customer_pst_exempt', $curr_user_data->roles ) ) $tax_class = 'CustomerPSTExemptClass'; */ // 3, 4 & 5 WHOLESLE SUITE SPECIAL WHOLESALE TAX RATES if (isset($current_user) && class_exists('WWP_Wholesale_Roles')) { $wwp_wholesale_roles = WWP_Wholesale_Roles::getInstance(); $wwp_wholesale_role = $wwp_wholesale_roles->getUserWholesaleRole(); // special tax rate: charge both PST and GST if roles: Wholesale Customer, Wholesale Silvia Silver, Wholesale Silvia Gold, Wholesale Silvia Premium, Wholesale Silvia Union if (!empty($wwp_wholesale_role) && in_array('wholesale_customer', $wwp_wholesale_role) && in_array('wholesale_silvia_silver', $wwp_wholesale_role) && in_array('wholesale_silvia_gold', $wwp_wholesale_role) && in_array('wholesale_silvia_premimum', $wwp_wholesale_role) && in_array('wholesale_silvia_union', $wwp_wholesale_role)) { // Where 'wholesale_customer, wholesale_silvia_silver, wholesale_silvia_gold, wholesale_silvia_premium, wholesale_silvia_union' are the names of the wholesale roles to target $tax_class = 'WholesalePSTGST'; } // special tax rate: charge only GST if roles: Wholesale PST Exempt, Wholesale Silvia Silver PST Exempt, Wholesale Silvia Gold PST Exempt, Wholesale Silvia Premium PST Exempt, Wholesale Silvia Union PST Exempt if (!empty($wwp_wholesale_role) && in_array('wholesale_pst_exempt', $wwp_wholesale_role) && in_array('wholesale_silvia_silver_pst_exempt', $wwp_wholesale_role) && in_array('wholesale_silvia_gold_pst_exempt', $wwp_wholesale_role) && in_array('wholesale_silvia_premium_pst_exempt', $wwp_wholesale_role) && in_array('wholesale_silvia_union_pst_exempt', $wwp_wholesale_role)) { // Where 'wholesale_pst_exempt, wholesale_silvia_silver_pst_exempt, wholesale_silvia_gold_pst_exempt, wholesale_silvia_premium_pst_exempt, wholesale_silvia_union_pst_exempt' are the names of the wholesale roles to target $tax_class = 'WholesalePSTExempt'; } // special tax rate: zero if roles: Wholesale Tax Exempt, Wholesale Silvia Silver Tax Exempt, Wholesale Silvia Gold Tax Exempt, Wholesale Silvia Premium Tax Exempt, Wholesale Silvia Union Tax Exempt if (!empty($wwp_wholesale_role) && in_array('wholesale_tax_exempt', $wwp_wholesale_role) && in_array('wholesale_silvia_silver_tax_exempt', $wwp_wholesale_role)&& in_array('wholesale_silvia_gold_tax_exempt', $wwp_wholesale_role) && in_array('wholesale_silvia_premium_tax_exempt', $wwp_wholesale_role) && in_array('wholesale_silvia_union_tax_exempt', $wwp_wholesale_role)) { // Where 'wholesale_tax_exempt, wholesale_silvia_silver_tax_exempt, wholesale_silvia_gold_tax_exempt, wholesale_silvia_premium_tax_exempt, wholesale_silvia_union_tax_exempt' are the names of the wholesale role to target $tax_class = 'WholesaleZeroTax'; } } return $tax_class; } /* ADDITIONAL FILTERS TO ALTER THE SHIPPING TAX FOR DIFFERENT TAX CLASSES BASED ON CUSTOMER USER ROLE */ add_filter( 'woocommerce_product_get_tax_class', 'all_custom_tax_classes', 1, 2 ); add_filter( 'woocommerce_product_variation_get_tax_class', 'all_custom_tax_classes', 1, 2 ); add_filter( 'option_woocommerce_shipping_tax_class' , function( $option_value ) { global $wc_wholesale_prices; if ( $wc_wholesale_prices && is_a( $wc_wholesale_prices , 'WooCommerceWholeSalePrices' ) ) { $current_user_wholesale_roles = $wc_wholesale_prices->wwp_wholesale_roles->getUserWholesaleRole(); if ( in_array( 'wholesale_customer', $current_user_wholesale_roles ) ){ return 'wholesalepstgst'; } elseif (in_array( 'wholesale_silvia_silver', $current_user_wholesale_roles) ){ return 'wholesalepstgst'; } elseif (in_array( 'wholesale_silvia_gold', $current_user_wholesale_roles) ){ return 'wholesalepstgst'; } elseif (in_array( 'wholesale_silvia_premium', $current_user_wholesale_roles) ){ return 'wholesalepstgst'; } elseif (in_array( 'wholesale_silvia_union', $current_user_wholesale_roles) ){ return 'wholesalepstgst'; } elseif (in_array( 'wholesale_pst_exempt', $current_user_wholesale_roles) ){ return 'wholesalepstexempt'; } elseif (in_array( 'wholesale_silvia_silver_pst_exempt', $current_user_wholesale_roles) ){ return 'wholesalepstexempt'; } elseif (in_array( 'wholesale_silvia_gold_pst_exempt', $current_user_wholesale_roles) ){ return 'wholesalepstexempt'; } elseif (in_array( 'wholesale_silvia_premium_pst_exempt', $current_user_wholesale_roles) ){ return 'wholesalepstexempt'; } elseif (in_array( 'wholesale_silvia_union_pst_exempt', $current_user_wholesale_roles) ){ return 'wholesalepstexempt'; } elseif (in_array( 'wholesale_tax_exempt', $current_user_wholesale_roles) ){ return 'wholesalezerotax'; } elseif (in_array( 'wholesale_silvia_silver_tax_exempt', $current_user_wholesale_roles) ){ return 'wholesalezerotax'; } elseif (in_array( 'wholesale_silvia_gold_tax_exempt', $current_user_wholesale_roles) ){ return 'wholesalezerotax'; } elseif (in_array( 'wholesale_silvia_premium_tax_exempt', $current_user_wholesale_roles) ){ return 'wholesalezerotax'; } elseif (in_array( 'wholesale_silvia_union_tax_exempt', $current_user_wholesale_roles) ){ return 'wholesalezerotax'; } } return $option_value; } , 10 , 1 );
Thank you Lyse Edited June 18, 2019 by LyseSpecify website platforms Similar TutorialsHi guys, I want something to be clarified. The supervisor of my system is responsible for approving accounts. When he logged into the system he should be able to view the customer records based on customer ID. That is when he types the relevant customer ID and clicks on search button the relevant record is displayed in a form. That part is OK. Thereafter he should approve the account by clicking on "Approve Account" button. I want to know how can he make sure relevant customer_id is approved or not. customer table includes fields of, customer_id, nic, full_name, name_with_initials, address, contact_number, gender. I want to whether i have add an extra field to my customer table saying "approves status" or whatever. Can anyone give me a suggestion?? Thanks, Heshan /* Output of the table will display the Suite based on the distinct date. The pass rate percentage calculate based on the Suite1 and app1 and the specific date. For example at Apr 4 2011, I need to Sum the total passcount,failcount,errorcount of Bluetooth, GPSA, EMIReceiver($app1) of XA9 on Real MXE($suite1) , then calculate the passrate percentages. But I fail to get the correct value of the passcount, failcount, errorcount value.Helps! Output of the table suite Date Percentages(pass rate) XA9 on Real MXE Apr 4 2011 9:47AM 99.94% XA9 on Real MXE Apr 5 2011 10:48AM 99.94% XA9 on Real MXE Apr 6 2011 9:49AM 99.95% XA9.5 on Real EXA_B40 Apr 4 2011 7:06AM 99.94% XA9.5 on Real EXA_B40 Apr 5 2011 7:14AM 99.93% XA9.5 on Real EXA_B40 Apr 6 2011 7:29AM 99.93% */ $suite1 --> array value (XA9 on Real MXE, XA9.5 on Real EXA_B40) $app1 --> array value (Bluetooth, GPSA, EMIReceiver) if(is_array($suite_type1)){ foreach($suite_type1 as $suite1) { $sql222="Select Distinct a.StopDTTM from Suite a,Test b where a.SuiteID=b.SuiteID and b.SuiteID=a.SuiteID and a.StopDTTM>='$fromdate' and a.StopDTTM<='$to_date' and a.SuiteFilePath like '%$Program%' and a.SuiteFileName='$suite1'"; $result222=mssql_query($sql222,$connection) or die("Failed Query of".$sql222); while($row222 = mssql_fetch_array($result222)) { $datetotest = $row222[0]; $days_to_add = 1; $tilldate = fnc_date_calc($datetotest,$days_to_add); //Query the result based on the date $sql223="Select Distinct a.SuiteFileName, a.SuiteID,a.StopDTTM from Suite a,Test b where a.SuiteID=b.SuiteID and b.SuiteID=a.SuiteID and a.StopDTTM>='$row222[0]' and a.StopDTTM<='$tilldate' and a.SuiteFilePath like'%$Program%' and a.SuiteFileName='$suite1' order by a.StopDTTM"; $result223=mssql_query($sql223,$connection) or die("Failed Query of".$sql223); while($row223 = mssql_fetch_row($result223)){ foreach($app_type1 as $app1) { $sql3="Select Sum(b.passcount),Sum(b.failcount),Sum(b.errorcount) from Suite a,Test b where a.SuiteID=b.SuiteID and b.SuiteID=a.SuiteID and a.StopDTTM>='$row222[0]' and a.StopDTTM<='$tilldate' and a.SuiteFilePath like '%$program%' and a.SuiteFileName = '$suite1' and b.Product='$app1'"; $result3=mssql_query($sql3,$connection) or die("Failed Query of ". $sql3); $row3 = mssql_fetch_row($result3); $total_passcount+=$row3[0]; $total_failcount+=$row3[1]; $total_errorcount+=$row3[2]; } $overall_total=$total_passcount+$total_failcount+$total_errorcount; echo "<tr>"; echo "<td><a href='detailsreport.php?suiteID=".$row223[1]."&suitetype=".$row223[0]."&fromdate=".$fromdate."&to_date=".$to_date."&date=".$row222[0]."&tilldate=".$tilldate."&SuiteFilePath=".$Fprogram."'>" . $row223[0] . "</a></td>"; //Suite File Name echo "<td>" . $row223[2] . "</td>"; //Pass percentage if($total_passcount>0){ echo "<td bgcolor=00FF33>" . number_format((($total_passcount/$overall_total)*100),2)."%</td>"; } else{ echo "<td bgcolor=00FF33>0%</td>"; } } } } echo "</table>"; } Hi all,
I am building a random prize assigner function based on weighted percentages.
I am able to assign a basic true/false weighting but am struggling to form a way of selecting an array based prize based on the win rate.
Heres my current code:
function selectPrize() { $prizes = array( 0 => array( 'name' => 'Top Prize', 'rate' => 50 ), 1 => array( 'name' => 'Middle Prize', 'rate' => 30 ), 2 => array( 'name' => 'Bottom Prize', 'rate' => 20 ), ); // oops } selectPrize();Could somebody please give me pointers on how i could approach this? Thanks. Edited by biggieuk, 19 June 2014 - 05:14 AM. I'm not sure what am I doing wrong? I want to check if match1, match2 or match 3 has "W" and the continues count ($numOfWinsCount) to be maximum of 2. If $numOfWinsCount is more than 2 do not continue with Code: [Select] $matchresult . $matchWcounter = "Qualified for Quarter Finals!"; My Code: Code: [Select] $match1 = "W" $match2 = "W" $match3 = "L" $getawayr="Group A"; if($getawayr=="Group A"){ for ( $matchWcounter = 1; $matchWcounter <= 3; $matchWcounter ++) { $numOfWinsCount = 0; if($match . $matchWcounter=="W" and $numOfWinsCount <3){ $numOfWinsCount=$numOfWinsCount+1; $matchresult . $matchWcounter = "Qualified for Quarter Finals!"; } } } I have two css external style sheets. One for the 800x600 screen resolution and other for 1200x768. How can I detect the screen resolution and apply the according style sheet using PHP. If I use Javascript, It is possible that the Javascript may not be enable on client side. has some one a better solution? While I am impressed with much of Symfony, the needing to know everything the "symfony way" is a little annoying. For an application, I will have several types of users: Admin Users. They can create a project, add new vendors, assign vendors to a given project, add new normal or admin users, etc. Vendors. They can view projects which they are assigned to and upload documents for that project. Normal Users. They will have the ability to view documents related to a given project which are submitted by vendors. Super Users. There will be multiple Accounts where all of the above user's will be assigned to a single, and they can only interact with others assigned to that same account. The super user can create an account and add the initial Admin User to that account.To expose the data, I am using api-platform. Currently, I am just trying to create endpoints to retrieve a list of vendors, normal users, etc. One possible solution I know how to accomplish but don't believe is the correct way is to create an AbstractUser and create VendorUser, NormalUser, etc which extend AbstractUser. Doing so will create routes for each of these user types and meet my immediate needs. Alternatively, I can create only a single User entity, and then assign roles such as ROLE_ADMIN, ROLE_VENDOR, ROLE_USER, or ROLE_SUPER. Ideally, I could then add new routes such as /vendors instead of making it /users?type=vendor. Or maybe I should be doing something totally different. If I was building this from scratch, I can definitely figure something out, however, would like to take advantage of symfony and do it their way. But I am a complete newbie when it comes to symfony, and don't even know where to start, and would appreciate a strategy to go which won't lead me down to bad of wrong path. To apply please click: https://hire.jobvite.com/j?cj=o0URYfwt&s=phpfreaks
This is an exciting opportunity to work on emerging and exciting products within an Agile development organisation in a growing, dynamic software company. Focused on developing the next generation of GFI’s cloud based products, the successful candidates will be part of a new team responsible for an exciting help desk and customer service platform based on a LAMP technology stack, the product allows our clients to efficiently manage communication and issues tracking over multiple channels (social, web, email and mobile) across their range of managed assets and end-users. The successful candidates will have experience in Object Oriented Programming in PHP (use of MVC frameworks such as CodeIgniter advantageous), experience with relational database design and front-end development (HTML/CSS/JavaScript). You will be Involved in every aspect of the SDLC, including specification and design, the successful candidates will have a hand in shaping the future of this exciting product. You will work in a highly collaborative environment where everyone is encouraged to understand and learn all areas of the system, the successful candidates will have a real say in how the system is developed, as well as SCRUM, Continuous Integration and Test Driven Development before seeing their code deployed and used online by our clients. But the words of some of our developers put it much better than we can: “Every one of our products carries the imprint of the people who built it.” “Being a software developer at GFI is challenging, fun and most of all rewarding: watching the code you’ve written deployed into production to become part of something bigger.” “The role is dynamic, you never know what issues will arise or what new features customers will request. GFI are willing to give you the time to cross-train to new languages and the close-knit teams of developers and testers provide all the support you need to succeed” “GFI may be an international company but they have successfully retained the small company feel where it is a pleasure to socialise with people inside and outside of work.” “In my role, I don't work on one boring CRUD application; instead I work on lots of cool things. We work with a diverse range of technologies, so there is always an opportunity to get your hands dirty with something new, and develop with the latest tech.” Check out this video showing A Visual Guide to Programming at GFI Software Developer - LAMP - Edinburgh Required Skills OOP Web Development with PHP5 Strong understanding of relational databases and design (MySQL) Strong HTML, CSS and JavaScript skills (Knowledge of HTML5 and CSS3) SVN Version Control Beneficial Skills Exposure to CodeIgniter (or similar MVC based framework) Test Driven Development Mobile Development Design Patterns Practical knowledge of implementing web services Understanding of email servers / MTA’s Knowledge of Linux/Apache ExtJS / jQuery Experience Software development experience in a professional environment is required. Experience of high-availability, high-volume applications in a cloud based environment would be beneficial. Qualifications The successful candidate will be educated to degree level in a software related discipline. Software Developer - LAMP - Edinburgh The Company The GFI Help Desk and Customer Service platform allows our clients to manage communication and issue tracking with their customers through multiple channels, such as social networking, email and web based communication. GFI Software provides web and mail security, archiving and fax, networking and security software and hosted IT solutions for small to medium-sized enterprises (SME) via an extensive global partner community. GFI products are available either as on-premise solutions, in the cloud or as a hybrid of both delivery models. To apply please click: https://hire.jobvite.com/j?cj=o0URYfwt&s=phpfreaks Hello. I have written this script where user restaurant owner can add his place to the database of all local restaurants. (insert basic information into database, add up to 3 images, thumbnail creation, insert image information to database). It works well on localhost, but i would like some suggestions for improvement. Im not very sure of its structure, it may not execute well once it is online. And i also think there are too many "IF's". But i really have no idea how to do it any other way. Thanks for all the suggestions. Code: [Select] <?php if(!defined('PROTECTION') || constant('PROTECTION') != 'demover') { echo "fuck off intruder!"; exit; } $naziv = mysql_real_escape_string($_POST['Naziv']); $naslov = mysql_real_escape_string($_POST['Naslov']); $kraj = mysql_real_escape_string($_POST['Kraj']); $telefon = mysql_real_escape_string($_POST['Telefon']); $web = "http://www.".mysql_real_escape_string($_POST['Spletna']); $gm = mysql_real_escape_string($_POST['Lokacija']); //$gmaps = gmParse($gm); $gmaps = 10; $fill="INSERT INTO bpoint (sName, sAddr, placeID, sPhone, sWeb, sGMaps, companyID) VALUES ('$naziv','$naslov','$kraj','$telefon','$web','$gmaps','$cID')"; if (mysql_query($fill)) { $lastID=mysql_insert_id(); $path="./truck/".$cID."/".$lastID; $pname=$_FILES["pic"]["tmp_name"]; $num=0; if (count($_FILES["pic"]) && mkdir($path, 0777)) { include "thumbs.php"; foreach($pname as $imag){ $bname=date("YmdHis").$num; $num++; $finalpath=$path."/".$bname.".jpg"; $finalthumb=$path."/".$bname."_thumb.jpg"; if($imag!="") { if (move_uploaded_file($imag, $finalpath)) { make_thumb($finalpath,$finalthumb,150); mysql_query("INSERT INTO images (name, companyID) VALUES ('$finalpath', '$cID')"); } } } } unset($_FILES["pic"]); } else {die(mysql_error());} ?> I use the Wholesale Suite Premium Prices plugin with WooCommerce. I have 6 specific wholesale roles out of 15 that I wish to hide two specific shipping methods from being selected for the 6 exceptions. I'm just trying this on my staging server at this time using a code snippet example that I found and modified for my specific conditions. Would the following work for this purpose? /* Hide specific shipping methods for specific wholesale roles */ add_filter( 'woocommerce_package_rates', function( $shipping_rates ) { // User role and shipping method ID to hide for the user role $role_shipping_method_arr = array( 'ws_silvia_silver' => array( 'Silvia Premium Standard Shipping (Tracking Service)'), 'ws_silvia_silver_pst_exempt' => array( 'Silvia Premium Standard Shipping (Tracking Service)'), 'ws_silvia_silver_tax_exempt' => array( 'Silvia Premium Standard Shipping (Tracking Service)'), 'ws_silvia_silver' => array( 'Silvia Union Standard Shipping (Tracking Service)'), 'ws_silvia_silver_pst_exempt' => array( 'Silvia Union Standard Shipping (Tracking Service)'), 'ws_silvia_silver_tax_exempt' => array( 'Silvia Union Standard Shipping (Tracking Service)'), 'ws_silvia_gold' => array( 'Silvia Premium Standard Shipping (Tracking Service)'), 'ws_silvia_gold_pst_exempt' => array( 'Silvia Premium Standard Shipping (Tracking Service)'), 'ws_silvia_gold_tax_exempt' => array( 'Silvia Premium Standard Shipping (Tracking Service)'), 'ws_silvia_gold' => array( 'Silvia Union Standard Shipping (Tracking Service)'), 'ws_silvia_gold_pst_exempt' => array( 'Silvia Union Standard Shipping (Tracking Service)'), 'ws_silvia_gold_tax_exempt' => array( 'Silvia Union Standard Shipping (Tracking Service)'), ); // Getting the current user role $curr_user = wp_get_current_user(); $curr_user_data = get_userdata($current_user->ID); // Wholesale Suite Roles if (isset($current_user) && class_exists('WWP_Wholesale_Roles')) { $wwp_wholesale_roles = WWP_Wholesale_Roles::getInstance(); $wwp_wholesale_role = $wwp_wholesale_roles->getUserWholesaleRole(); // Loop through the user role and shipping method pair foreach( $role_shipping_method_arr as $role => $shipping_methods_to_hide ) { // Check if defined role exist in current user role or not if( in_array( $role, $current_user->roles) ) { // Loop through all the shipping rates foreach( $shipping_rates as $shipping_method_key => $shipping_method ) { $shipping_id = $shipping_method->get_id(); // Unset the shipping method if found if( in_array( $shipping_id, $shipping_methods_to_hide) ) { unset($shipping_rates[$shipping_method_key]); } } } } } return $shipping_rates; }); Any insights as to how to accomplish this would be greatly appreciated. Lyse How do you establish a tax rate in a MySQL database to use in a form calculation, then be able to change the value to a new constant value from the form? Php Folks, I started learning php originally from 2015. On & off. Part time. Started getting into it seriously around 2017. From home. No classes. From forums and php manual and tutorial sites. Still at oop & mysqli. Had ups & downs as first learnt a lot of old stuffs then found out they been deprecated. For example, if I had originally known pdo is modern over mysqli then I would started on pdo from beginning. Got no real guidance anywhere. Just learnt things the hard way, coming across obstacles and bugging forums. Half-way learning mysqli I come across pdo. So you see, if I had taken school classes then they would have started me on the new stuffs. But because I learning from home, I came across a lot of old tutorials and started from there without knowing they are sort of outdated stuffs. Anyway, I don't like quitting half-way and so did not quit mysqli for pdo when a lot of programmers advised me to dump mysqli for pdo. Thought, since I "wasted time" on mysqli then might aswell build a few sites with it before ditching it. Part time study. Full time working on projects for 3yrs now. projects are own "hobby sites" so to speak and not for clients. I am not the freelancer type or professional type. layman type. Never really have launched any sites. I finish one site/project then move onto another project for learning purpose. So I learn very little then moving onto building sites based on what little I learnt. When I learnt how to use the SELECT, INSERT. DELETE, UPDATE in sql, I jumped into learning to build my own membership site (reg, log-in, logout, etc. pages) to deal with mysql db. So far, built membership parts (login, logout, account homepage, pagination). All by copying codes from tutorials and forums from people like you and changing here and there according to my needs. And when I get stuck. I bug programmers like you. I do have a conscious and do not like plagiarism even while learning and so everytime I copy paste codes from tutorials or forums (where I get help), I retype every line and then delete the copy-pasted lines and leave my typed lines in the file. that way, I feel good I atleast made some effort to build the site rather than copy & paste. Then, I change the codes here and there to suit my purpose. Don't you like me ? ;). You probably chuckling inside reading this. Here's an example of how I copy-paste then re-write the lines. <?php //Code from: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_login_form ?> <!DOCTYPE html> <!DOCTYPE html> <html> <html> <head> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> <style> body {font-family: Arial, Helvetica, sans-serif;} body {font-family: Arial, Helvetica, sans-serif;} form {border: 3px solid #f1f1f1;} form {border: 3px solid #f1f1f1;} input[type=text], input[type=password] { input[type=text], input[type=password] { width: 100%; width: 100%; padding: 12px 20px; padding: 12px 20px; margin: 8px 0; margin: 8px 0; display: inline-block; display: inline-block; border: 1px solid #ccc; border: 1px solid #ccc; box-sizing: border-box; box-sizing: border-box; } } button { button { background-color: #4CAF50; background-color: #4CAF50; color: white; color: white; padding: 14px 20px; padding: 14px 20px; margin: 8px 0; margin: 8px 0; border: none; border: none; cursor: pointer; cursor: pointer; width: 100%; width: 100%; } } button:hover { button:hover { opacity: 0.8; opacity: 0.8; } } .cancelbtn { .cancelbtn { width: auto; width: auto; padding: 10px 18px; padding: 10px 18px; background-color: #f44336; background-color: #f44336; } } .imgcontainer { .imgcontainer { text-align: center; text-align: center; margin: 24px 0 12px 0; margin: 24px 0 12px 0; } } img.avatar { img.avatar { width: 40%; width: 40%; border-radius: 50%; border-radius: 50%; } } .container { .container { padding: 16px; padding: 16px; } } span.psw { span.psw { float: right; float: right; padding-top: 16px; padding-top; 16px; } } /* Change styles for span and cancel button on extra small screens */ /* Change styles for span and cancel button on extra small screens */ @media screen and (max-width: 300px) { @media screen and (max-width: 300px) { span.psw { span.psw { display: block; display: block; float: none; float: none; } } .cancelbtn { .cancelbtn { width: 100%; width: 100%; } } } } </style> </style> </head> </head> <body> <body> <h2>Login Form</h2> <h2>Login Form</h2> <form action="/action_page.php" method="post"> <form action="/action_page.php" method="post"> <div class="imgcontainer"> <div class="imgcontainer"> <img src="img_avatar2.png" alt="Avatar" class="avatar"> <img src="img_avatar2.png" alt="Avatar" class="avatar"> </div> </div> <div class="container"> <div class="container"> <label for="uname"><b>Username</b></label> <label for="uname"><b>Username</b></label> <input type="text" placeholder="Enter Username" name="uname" required> <input type="text" placeholder="Enter Username" name="uname" required> <label for="psw"><b>Password</b></label> <label for="psw"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="psw" required> <input type="password" placeholder="Enter Password" name="psw" required> <button type="submit">Login</button> <button type="submit">Login</button> <label> <label> <input type="checkbox" checked="checked" name="remember"> Remember me <input type="checkbox" checked="checked" name="remember"> Remember me </label> </label> </div> </div> <div class="container" style="background-color:#f1f1f1"> <div class="container" style="background-color:#f1f1f1"> <button type="button" class="cancelbtn">Cancel</button> <button type="submit" class="cancelbtn">Cancel</button> <span class="psw">Forgot <a href="#">password?</a></span> <span class="psw">Forgot <a href="#">password?</a></span> </div> </div> </form> </form> </body> </body> </html> </html> One thing I gain from this type of re-writings is that, typing the same thing over and over again sort of gets codes sink into my subconscious. Helps to memorise the codes. Ok. So now you know a little about me. As you can see, I always start on somebody else's skeleton, be it from a tutorial forum or a tutorial site or php manual. I have completed 3 websites, so to speak, in that way. 2 days ago I thought, I been doing this for 3yrs now. Let's test and see how well I can code without working on somebody else's skeleton. No copy-pasting from forums or tutorial sites or php manual. And so, look what I did. I coded all the following from my own memory. let me know how well I did. That repetition of lines re-writing has done me some good to memorise codes. I did make 2 mistakes. Note the comments in the code. You will notice "MY CODE ..." and then a correction "WHAT IT SHOULD BE ...". Compare the 2 and see how close or far away I was from the correction. And then give me score from 1-10 (where 10 is best) how well I did as a home study middle aged guy. Hard learning things at middle age. I think, if I had toild you I started learning a month ago then you'd give 9/10 but because it's been 3 yrs, you'll give 1/9 or 0. Just bear in mind it's not easy to learn things at middle age and remember them without forgetting. I learn fast but forget double fast. Lol! One thing though. My codes are not working. They do not INSERT data into db nor extract & display data from db. What is wrong ? TEST NUMBER 1: On this one, I first tried displaying data rows from mysql using mysqli_stmt_get_result(). That failed and so I tried with mysqli_stmt_bind_result() afterwards and so bear that in mind and don't ask me why I used both instead of one. Clicking the "search" button gives no response. Nothing happens on page. I did search for a ketywords that exist in each mysql tbl columns. <?php include('error_reporting.php'); require('conn.php'); //require('search_form.php'); ?> <form name = "search" method = "POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <label for="keywords">Keywords:*</label> <input type="text" name="keywords" id="keywords" placeholder="Input Keywords" required> <br> <label for="search_column">Search in ... ?</label> <select name="search_column" id="search_column"> <option value="page_url">Page Url</option> <option value="link_anchor_text">Link Anchor Text</option> <option value="page_description">Page Description</option> <option value="keyphrase">Keyphrase</option> <option value="keywords">Keywords</option> </select> <br> <label for="tos_agreement">Agree to TOS or not ? *</label> <select name="tos_agreement" id="tos_agreement" required> <option value="Yes">Yes</option> <option value="No">No</option> </select> <br> <input type="button" name="search_links" id="search_links" value="Search Links!"> <br> <input type="reset"> <br> </form> <?php if($_SERVER['REQUEST_METHOD'] === 'POST') { if(ISSET($_POST['search_links'])) { $_POST['page_url']; $_POST['link_anchor_text']; $_POST['page_description']; $_POST['keyphrase']; $_POST['keywords']; //I WROTE 2 QUERIES HERE AS I WASN'T SURE HOW IT SHOULD BE. FINALLY, STUCK TO THE LATTER. HOWEVER, ON TESTS NONE OF THEM WORK! //QUERY 1. $query = "SELECT FROM links (page_url,link_anchor_text,page_description,keyphrases,keywords) WHERE keywords = ?"; //QUERY 2... $query = "SELECT page_url,link_anchor_text,page_description,keyphrases,keywords FROM links WHERE page_url = ?, link_anchor_text = ?, page_description = ?, keyphrases = ?, keywords = ?"; $stmt = mysqli_stmt_init($conn); if(mysqli_stmt_prepare($stmt,$query)) { mysqli_stmt_bind_param($stmt,'sssss',$_POST['page_url'],$_POST['link_anchor_text'],$_POST['page_description'],$_POST['keyphrase'],$_POST['keywords']); //WRONG: FORGOT TO ADD "$result = " ... //mysqli_stmt_bind_result($stmt,$page_url,$link_anchor_text,$page_description,$keyphrase,$keywords); //CORRECTION: WHAT IT SHOULD BE ... $result = mysqli_stmt_bind_result($stmt,$page_url,$link_anchor_text,$page_description,$keyphrase,$keywords); //mysqli_stmt_execute($stmt);WRONG! THIS LINE SHOULDN'T EXIST UNLESS IT'S mysqli_stmt_get_result(). mysqli_stmt_fetch($stmt); //WASN'T SURE WHICH OF THE 3 FOLLOWING LINES ARE CORRECT REGARDING THE WHILE LOOP. FINALLY, STUCK TO THE 1ST LINE ... //1)... while(mysqli_stmt_fetch($stmt)) //2)... //while(mysqli_fetch_array($stmt,mysqli_assoc)) //3)... //while(mysqli_fetch($stmt)) { echo "url"; echo "<br>"; echo "anchor_text"; echo "<br>"; echo "description"; echo "<br>"; echo "keyphrases"; echo "<br>"; echo "keywords"; echo "<br>"; echo "|"; echo "<br>"; } mysqli_stmt_close($stmt);//CORRECTION: THIS SHOULD BE OUTSIDE THE "WHILE LOOP" mysqli_close($conn);//CORRECTION: THIS SHOULD BE OUTSIDE "IF" } else { echo "1. QUERY failed!"; } if(mysqli_stmt_prepare($stmt,$query)) { mysqli_stmt_bind_param($stmt,'sssss',$_POST['page_url'],$_POST['link_anchor_text'],$_POST['page_description'],$_POST['keyphrases'],$_POST['keywords']); mysqli_stmt_execute($stmt); //CORRECTION: FORGOT TO ADD "$result = " $result = mysqli_stmt_get_result($stmt); /* MY CODE WRONG! TRIED ECGHOING THE ARRAY "$row[]"! while($row = mysqli_fetch_array($result,mysqli_assoc)) { echo $row['page_url']; echo "<br>"; echo $row['link_anchor_text']; echo "<br>"; echo $row['page_description']; echo "<br>"; echo $row['keyphrases']; echo "<br>"; echo $row['keywords']; echo "<br>"; echo "|"; echo "<br>"; } */ //CORRECTION: HOW IT SHOULD BE: //$VARIABLE SHOULD BE ECHOED. NOT THE ARRAY $row[] while($row = mysqli_fetch_array($result,mysqli_assoc)) { $page_url = $row['page_url']; echo $page_url; echo "<br>"; $link_anchor_text = $row['link_anchor_text']; echo $link_anchor_text; echo "<br>"; $page_description = $row['page_description']; echo $page_description; echo "<br>"; $keyphrases = $row['keyphrases']; echo $keyphrases; echo "<br>"; $keywords = $row['keywords']; echo $keywords; echo "<br>"; echo "|"; echo "<br>"; } mysqli_stmt_close($stmt); mysqli_close($conn); } else { die("2. QUERY failed!"); } } } ?>
TEST NUMBER 2: On this one, clicking the "submit links" button gives no response atall!.
<?php include('error_reporting.php'); require('conn.php'); //equire('link_submission_form.php'); ?> <form name = "submit_link" method = "POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <label for="domain">Domain:</label> <input type="text" name="domain" id="domain" placeholder="Input Domain"> <br> <label for="domain_email">Domain Email:</label> <input type="email" name="domain_email" id="domain_email" placeholder="Input Domain Email"> <br> <label for="url">Url:</label> <input type="url" name="url" id="url" placeholder="Input Url"> <br> <label for="link_anchor_text">Link Anchor Text:</label> <input type="text" name="link_anchor_text" id="link_anchor_text" placeholder="Input Link Anchor Text"> <br> <textarea rows="10" cols="20">Page Description</textarea> <br> <label for="keywords">Keywords:</label> <input type="text" name="keywords" id="keywords" placeholder="Input Keywords related to Page"> <br> <label for="tos_agreement">Agree to TOS or not ?</label> <select name="tos_agreement" id="tos_agreement"> <option value="yes">Yes</option> <option value="no">No</option> </select> <br> <input type="button" name="submit_link" id="submit_link" value="Submit Link!"> <br> <input type="reset"> <br> </form> <?php if($_SERVER['REQUEST_METHOD'] === 'POST') { if(ISSET($_POST['submit_link'])) { $query = "INSERT into links (domain,domain_email,url,link_anchor_text,page_description,keywords) VALUES ?,?,?,?,?,?"; $stmt = mysqli_stmt_init($conn); if(mysqli_stmt_prepare($stmt,$query)) { mysqli_stmt_bind_param($stmt,'ssssss',$_POST['domain'],$_POST['domain_email'],$_POST['url'],$_POST['link_anchor_text'],$_POST['page_description'],$_POST['keywords']); mysqli_stmt_close($stmt); mysqli_close($conn); } else { die("INSERT failed!"); } } } ?>
What is wrong ? Why both codes don't work ? Edited July 14, 2020 by 2020 Alight, I'm trying to figure out the error string for an api http://www.haloreachapi.net/wiki/API_rate_limits The wiki says the limit is 300rpm I tried to run this in two tabs on my browser still won't give me the error string, how can it be done faster? P.s. Api key will be changed in the near future don't waste your time.. <?php $gamertag = "l RaH l"; $url = "http://www.bungie.net/api/reach/reachapijson.svc/game/metadata/30cRxVA9J73esG388CzmOXUVRo5VjYhSfI2qBaqcMzs="; $t_start = microtime(true); for($i = 0; $i < 301; $i++) { $file = file_get_contents($url); echo "Iteration ".($i + 1)."<br>\n"; } $exectime = microtime(true) - $t_start; echo "Execution time: " . round($exectime, 4) . "<br><br>\n\n"; $json = json_decode($file, 1); print_r($json); ?> function wsProcessClientMessage($clientID, $opcode, &$data, $dataLength) { global $wsClients; // check opcodes if ($opcode == WS_OPCODE_PING) { // received ping message return wsSendClientMessage($clientID, WS_OPCODE_PONG, $data); } elseif ($opcode == WS_OPCODE_PONG) { // received pong message (it's valid if the server did not send a ping request for this pong message) if ($wsClients[$clientID][4] !== false) { $wsClients[$clientID][4] = false; } } elseif ($opcode == WS_OPCODE_CLOSE) { // received close message if (substr($data, 1, 1) !== false) { $array = unpack('na', substr($data, 0, 2)); $status = $array['a']; } else { $status = false; } if ($wsClients[$clientID][2] == WS_READY_STATE_CLOSING) { // the server already sent a close frame to the client, this is the client's close frame reply // (no need to send another close frame to the client) $wsClients[$clientID][2] = WS_READY_STATE_CLOSED; } else { // the server has not already sent a close frame to the client, send one now wsSendClientClose($clientID, WS_STATUS_NORMAL_CLOSE); } wsRemoveClient($clientID); } elseif ($opcode == WS_OPCODE_TEXT || $opcode == WS_OPCODE_BINARY) { // received text or binary message if (function_exists('wsOnMessage')) wsOnMessage($clientID, $data, $dataLength, $opcode == WS_OPCODE_BINARY); } else { // unknown opcode return false; } return true; } Hi, I am trying to store the view rate of articles so that I can retrieve them later on by "the most popular". I have searched around but cannot find a straight answer. Can anyone point me towards the right direction? Edit: Never mind, I was over complicating the logic behind this. I built a address book for customers and i realize now im not sure the best way to allow the customer to edit/delete their addresses, but stopping them from pulling/editing other customers info. Even if i use post data only they could still view the page source and see the address ID being posted to the next page and change it, to see or edit someone elses data... Should i encrypt the ID? Is that even good enough? Im using PHP/MYSQL Help! I'm stuck! This is the feedback form file I made. Code: [Select] <html> <head><title>Bob's Auto Parts - Customer Feedback</title></head> <body> <h1>Customer Feedback</h1> <p>Please tell us what you think.</p> <form action="processfeedback.php" method="post"> <p>Your name:<br/> <input type="text" name="name" size="40" /></p> <p>Your email address:<br/> <input type="text" name="email" size="40" /></p> <p>Your feedback:<br/> <textarea name="feedback" rows="8" cols="40" wrap="virtual" /></textarea></p> <p><input type="submit" value="Send feedback" /></p> </form> </body> </html> And this is the process feedback file I made. Code: [Select] <?php //create short variable names $name = trim($_POST['name']); $email = trim($_POST['email']); $feedback = trim($_POST['feedback']); //set up some static information $toaddress = "wolocaw@localhost"; $subject = "Feedback from web site"; $mailcontent = "Customer name: ".$name."\n". "Customer email: ".$email."\n". "Customer comments:\n".$feedback."\n"; $fromaddress = "From: webserver@example.com"; //invoke mail() function to send mail mail($toaddress, $subject, $mailcontent, $fromaddress); ?> <html> <head> <title>Bob's Auto Parts - Feedback Submitted</title> </head> <body> <h1>Feedback submitted</h1> <p>Your feedback (shown below) has been sent.</p> <p><?php echo nl2br($mailcontent); ?> </p> </body> </html> After I fill out the form, it brings me to a page that says "Feedback submitted" at the top and "Your feedback (shown below) has been sent." below it. And that's it. nl2br($mailcontent) doesn't do anything. What am I doing wrong? I don't understand! Hi all, I want some help regarding my banking project. I have a customer registration form in my project.After successfully completion of the form users have to click on the "Open Account" button.Thereafter a customer id(Auto increment value) should be generated.It was stored in the database where other form details are also being stored. How can i call to this one by one customer id's?? Heshan, Hi Guys, Basically, I have a long php script to calculate the nearest branch dependant on there postcode hence why $to = $branchemail at the end. It will send it to HQ if anything goes wrong as a safeguard. Here is a small piece of my php code: if (strlen($branchemail) == 0){ // Default Address if anything goes wrong $to = "hq@example.com"; } else { // The address of the branch to send to $to = $branchemail; } What I can't seem to do is also send the customer filling in the php form a copy of the email sent. The variable for the customers email is $email I have tried this and it doesn't seem to work either... // The address of the branch to send to $to = $branchemail; $to .= $email; } At the bottom of the script, there is this code to physically send the email. This also always sends a copy to hq aswell. echo "Thank you for contacting us, we have received your message and we aim to respond your very shortly."; mail($to, $subject, $body, $mailheader); // THIS LINE TO CC Email mail("hq@example.com", $subject, $body, $mailheader); } else { echo "There has been an error code 1. Please try again."; So basically I just can't get it to send a copy to the customer filling it in ($email) Any idea's because my mind has gone blank. Cheers, S How can I do the following: 1. Upon successful login, generate a random 8-digit customer number and assign it to that customer and writes that data to mYsQl. 2. Screen then refreshes and reads, "Welcome Mr Smith". |