PHP - Inserting Custom Id As Pk.
Hi Everyone.
I'm trying to generate a non standard PK in the form of 000111-YU, where 0001 refers to the record number, the 11 refers to the year and the -YU is a set of random letters / numbers. The 0001 can increment throughout the year, but once 2012 occurs, the counter needs to be reset back to 0001. I need this number to be generated and inserted into the table, but I also need to have form fields inserted into the db. for eg. FirstName and LastName are names of textboxes in a form. this is what i have so far, but i keep receiving 'error, insert query failed.' <?php $db="db"; $link = mysql_connect('localhost', 'root', 'pw'); if (! $link) die(mysql_error()); mysql_select_db($db , $link) or die("Couldn't open $db: ".mysql_error()); $query = "INSERT INTO records (IDNumber, FirstName, LastName) SELECT * FROM ( SELECT # id CONCAT( # Sequential number, incremented, zero-padded LPAD((SUBSTR(COALESCE(MAX(IDNumber), '0'), 1, 4) + 1), 4, '0'), # Two-digit year DATE_FORMAT(CURRENT_DATE, '%y'), # Literal hyphen '-', # Two random letters (AA-ZZ) CHAR( FLOOR(65 + RAND() * 26), FLOOR(65 + RAND() * 26) ) ) FROM records WHERE IDNumber LIKE CONCAT('____', DATE_FORMAT(CURRENT_DATE, '%y'), '-__') ) "; mysql_query($query) or die('Error, insert query failed'); ?> Similar TutorialsHi, I have built a custom php program for a client which takes information submitted in a html form and calculates a persons bmi.
I have tested and it works fine, this is in one page (one file).
My problem is I have tried to insert it in to wordpress using both shortcodes and php tag plugins
(you can't insert php in to posts and pages as standard on wordpress)
and I can't get it to work.
The closest I've got is using a php tag plugin that uses shortcodes to replace <?php & ?> but when I submit, it just reloads the page and form rather than showing the result.
as I've said it works fine outside of wordpress. :-\
<h1>BMI Calculator</h1> <!--bmi form--> <?php if (!isset($_POST['submit'])){ ?> <form action="<?php echo $_SERVER['PHP_SHELF']; ?> "method="post"> <input name="weight" size="3"> Enter your weight in kilograms (KG). </br> </br> <input name="height" size="3"> Enter your height in metres, for example if you're 160cm tall you would type in "1.60". </br> </br> <input type="submit" name="submit" value="Calculate"> </form> <?php } else { $weight = $_POST ['weight']; $height = $_POST ['height']; $bmi_catagory = array("Underweight", "Normal", "Overweight", "Obese"); $bmi = ($weight/$height)/$height; if ($bmi <= 18.5) { echo '<h2>Your bmi is '.round($bmi).'</h2><p>You are '.$bmi_catagory[0] .' Click <a href=\'../bmichecker.php\'>HERE</a> to see how Hypnoslimtize can help you achieve a healthy weight.</p>'; } elseif (($bmi > 18.5) && ($bmi <=24.9)) { echo '<h2>Your bmi is '.round($bmi).'</h2><p>You are '.$bmi_catagory[1] .' Click <a href=\'../bmichecker.php\'>HERE</a> to see how Hypnoslimtize can help you stay healthy and avoid temptations.</p>'; } elseif (($bmi >= 25) && ($bmi <=29.9)) { echo '<h2>Your bmi is '.round($bmi).'</h2><p> You are '.$bmi_catagory[2] .' Click <a href=\'../bmichecker.php\'>HERE<a/> to see how Hypnoslimtize can Help you achieve a healthy body weight.</p>'; } elseif ($bmi >= 30) { echo '<h2>Your bmi is '.round($bmi).'</h2><p> You are '.$bmi_catagory[3] .' Click <a href=\'../bmichecker.php\'>HERE</a> to see how Hypnoslimtize can help you achieve a healthy body weight.</p>'; } else { echo 'Your bmi is '.round($bmi); } } ?> <!--bmi form end--> I'm sure it's not much, but I'm not understanding something with custom error handlers: I've created a custom error handler, which I initially set when my page loads : set_error_handler(array ( new ErrorHandler(), 'handleError' ));
It seems to catch all internal PHP errors, such as if I: var_dump($non_existing_var); right after the set_error_handler.... Now, I have an object that throws an exception after: set_error_handler(array ( new ErrorHandler(), 'handleError' )); $locale = new \CorbeauPerdu\i18n\Locale(...); // this should throw an exception ... I thought that with an error handler set, I could 'skip' the try/catch for it, but doing so, PHP spits out in its internal log: PHP Fatal error: Uncaught CorbeauPerdu\i18n\LocaleException: ....
My error handler doesn't catch it at all before, thus my page breaks!! If I want it to go through the error handler, I have to init my Locale with a try/catch and use trigger_error() like so: set_error_handler(array ( new ErrorHandler(), 'handleError' )); try { $locale = new \CorbeauPerdu\i18n\Locale(...); // this should throw an exception } catch(Exception $e) { trigger_error($e->getMessage(), E_USER_ERROR); } ... Is this normal ? I thought one of the goals of the error_handler was to catch anything that wasn't dealt with? Thanks for your answers! I am in the process of learning MySQL and PHP. I have a real-world application that I would like to develop for someone using MySQL and PHP, provided I can end up with the necessary user interface for the application. The user will be launching a web browser to start the application. The application will be developed for two purposes: to record employee information (name, contact info, category of worker such as: cook, dishwasher, server, host) to record the hours worked by each worker for each day and then generate a report that can be sent to the accountant by email or fax Since the interaction will take place in a web browser, what are the possibilities as far as having customization for the text fields (controllable size of text field, larger than the form element), having start and end times with the colon symbol inserted automatically, to name a few. When a text field is inserted via HTML, the rectangle is rather small. Can the default sizes of form elements be enlarged? hi i am new in here and php coding. i got the following code frm my friend for making a name, address, passout of student searching database. <?php // TAKE THE INFORMATION FROM FORM. $search = $_GET['search']; // IF THERE IS NOT A KEYWORD GIVE A MISTAKE. if (!$search) echo "You didn't enter a keyword."."$text Back to Search Again <a href=searchform.php>Search</a>"; else { echo "<td>You searched for: <strong>$search </strong></td>"; mysql_connect('sql servername','sql server username','password'); mysql_select_db('database name'); $id=@$_GET['id']; //QUERY IS THE CODE WHICH WILL MAKE THE SEARCH IN YOUR DATABASE. //I WROTE AN EXPLANATION ABOUT IT AFTER THE CODE. $query="SELECT * FROM searchform WHERE MATCH(Name, Address, Pass) AGAINST('%$search%' IN BOOLEAN MODE)"; $result1 = MySQL_query($query); if(!$result1) { echo MySQL_error()."<br>$query<br>"; } if(MySQL_num_rows($result1) > 0) { echo "<table width='480' align='center' border='1' cellspacing='0' cellpadding='0'>"; while($result2 = MySQL_fetch_array($result1)) { //A short description from category. $description = $result2['category']; $searchPosition = strpos($description, $search); $shortDescription = substr($description, $searchPosition, 150); // I added a link to results which will send the user to your display page. echo "<tr><td>Name</td><td>Address</td><td>Pass</td></tr>"; echo "<tr><td>{$result2['Name']}</td><td>{$result2['Address']}</td><td>{$result2['Pass']}</td></tr>"; } echo "</table>"; }else { echo "No Results were found.<br>"."$text Back to Search Again <a href=searchform.php>Search</a>"; }echo "<br>"; } ?> every thing is working fine as i wanted. my database structure is below |NAME||ADDRESS||YEAR| |ABC|abc|1980| |XYZ||xyz||1980| but there is a small problem of showing the output result. when i search with 1980 it show 4 column 1st column is showing NAME, ADDRESS, YEAR 2nd column is showing |ABC|abc|1980| again 3rd column is showing NAME, ADDRESS, YEAR 4th column is showing |XYZ||xyz||1980| how i solve to not showing every column the NAME, ADDRESS, YEAR (3rd column) When a user clicks on a topic they are transfered to its post, which is retrieved by the name of the topic as given by the url value. up to now i have just used urlencode. But its trickier when a user adds slashes and dots into the mix. for example the title of the post is testing/testing. The url will go to www.asimpleforum.co.uk/t/testing/testing. How would i get around this since url encode doesnt do the job? I could replace slashes and dots with their own unique symbol but that produces the problem when someone uses one of those symbols that i use to replace in their topic title. I know one site in particular that replaces all dots and slashes with a hyphen (-), but how would you know what to turn the hyphen into when you query the database for that topic? Anyone have any ideas? Hello. I am currently working on a new site (http://sa.cx) that is basically a free domain like this: (example.sa.cx). My main goal is to allow users to set the the full MX, CNAME, A and SOA records. Any ideas on how I could go about this using php? My initial thought would be via cURL. Is there a way to use PHP to edit html without having to store it in my DB? For example I would like someone to be able to edit a paragraph on the page, its wrapped in a <div class="editable"> now is there a way to have PHP detect that div and have an textarea to edit it directly without having to store anything in a DB? I hope that makes sense if it doesn't let me know! Thanks Hi. I was just wondering if it is possible to write custom mysql errors. I have hunted around for some but cant find any. Currently I write my errors like... or die (mysql_error()); How ever I see this as a problem! As Im not the best coder there are bound to be errors in my code. I dont want somebody who knows what they are doing to cause an error and then doing it (mysql_error()) will point them in the right direction to what I have missed. I would rather have my own error saying what line the issue is with. I have tried..... or die (mysql_error(My personal error here)) However this does not work. Please help. Thank you Hi guys, i have a ipn paypal setup where users can buy items from my custom made shop, however in original ipn code, the logged in users should have the same email with paypal to call on ipn which user has bought what, so I have decided to pass a custome variable as <input type="hidden" name="custom" value="<?php echo "$username";"> the hard part is in my ipn how im i going to recieve the username variable? what should i put in my ipn. In ipn code I have example code: $item_name = $_POST['item_name']; $item_number = $_POST['item_number']; $payment_status = $_POST['payment_status']; $payment_amount = $_POST['mc_gross']; $payment_currency = $_POST['mc_currency']; $txn_id = $_POST['txn_id']; $receiver_email = $_POST['receiver_email']; $payer_email = $_POST['payer_email']; but now, can u help me to recieve the username so i can match my mysql query which user has bought what? thanks in advance I'm gonna be perfectly honest, I have no idea what's wrong with this code, I'm not even entirely sure what it all means, I just need to make it work. -.- I get this error: Parse error: syntax error, unexpected '}' in Z:\www\cms\includes\functions.php on line 25 From this code: Code: [Select] <html> <body> <?php include('includes/dbvars.php'); function displayVideos($dbc){ mysqli_connect('DB_HOST', 'DB_USER', 'DB_PW', 'DB_NAME'); //Query $query = "SELECT * FROM videos"; //Execute $result = mysqli_query($dbc, $query) or die ("Error querying database."); While ($row = mysqli_fetch_assoc($result)) { echo '<h2>' . $row['Title'] . '</h2>'; echo '<b>Director</b>:' . $row['Director'] . '<br />'; echo '<b>Description</b>:<br />' . $row['Description']; echo '<hr>'; } mysqli_close($dbc) } ?> </body> </html> Any help very much appreciated Hi all I wonder if people can help me out here. It's a "bespoke" vs "framework" question, so not sure its belongs in here, but I didn't want to post it in the ZEND group, as it may have many more "pro ZEND fans" who read it, and I wanted a general thought. This is all based on the fact that I have a big project coming up and I want to know if I should be sticking with a custom job, or if something like ZEND is the way to go. Basically I have been developing PHP for about 2 years now and I have always thought a custom site written from scratch was the best way to go, not only does it allow you to have the minimal code needed to run the site, therefore reducing load, space and bandwidth, but it also allows you to know exactly how the system works, I guess the downside is that you have to spend more time doing the coding. But I have a few friends who use frameworks, ZEND has been coming up more and more, it's not really my ideal system to use as I prefer coding from scratch (not sure why), but they swear by it, and always tell me its great, its winning awards and none of them code from scratch, one of them even quoted that it "will become the standard for development" - is this true? Apart from being massively bulky and containing tons of files with scripts and functions that you might never ever use, what do people see as a downside to ZEND, If any? Is it best to code from scratch, and if so, why? Or does using something like ZEND much better? I guess if you always use ZEND, then you never really enhance your skill as a coder and never really learn anything new, plus I always think it's kind of cheeky using a pre-built system. Is there a good argument that would say using ZEND is not really a good idea? Or is the general feeling toward ZEND being a good thing? Surely if people know ZEND, they know how to play the security of the site to there advantage and therefore can break the security of other ZEND systems, or at least cause some hacks to a site. Any thoughts would be great Thanks everyone Hello, I am wondering how to create a counter that has 5 digits and counts the results from a db field (not just the returned results but the numeric SUM of the values in the field) for display. i.e. if the sum of the field = 347 the counter would read 00347 I have created images for the numbers 0-9 and named them 0.png, 1.png, 2.png etc Also, I may have to sum a value that is stored in the db as serialized data (part of an array). If so how can I do that?? Hi all
I have the following in my .htaccess file
RewriteRule ^([^/]+)/ /$1.php?q=$1 [L,QSA]
and this is great because any PHP page I create, such as 'about.php' can be rewritten as '/about/' - so that is all good.
the problem is, I also want to let users create their own custom URL's for their profiles in the root of the site, such as '/david-jones/' but because 'david-jones' is not actually a real PHP page (but rather a database entry), I cant use a rewrite rule as far as I can see.
Would the best solution be to piggy back the error 404 rewrite rule, so that if an actual PHP page isn't found, it takes them to the 404 error page which actually contains a script to lookup the users details, if the user details are not found, i'd show a "the page cannot be found" message.
Or is there a more elegant way to do this?
Thanks
Hi all,
alt="<?php echo the_title(); ?> keyword keyword"/>
So I need to include this: alt="<?php echo the_title(); ?> keyword keyword"/>
Or this: [show_post_categories show=”title”]
Into this, replacing the site_title in the alt= parts: // LOGO CODE FOR SORTING ALT TEXT <!-- Header logo --> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?><?php echo get_bloginfo( 'name' ) && get_bloginfo( 'description' ) ? ' - ' : ''; ?><?php bloginfo( 'description' ); ?>" rel="home"> <?php if(flatsome_option('site_logo')){ $logo_height = get_theme_mod('header_height',90); $logo_width = get_theme_mod('logo_width', 200); $site_title = esc_attr( get_bloginfo( 'name', 'display' ) ); if(get_theme_mod('site_logo_sticky')) echo '<img width="'.$logo_width.'" height="'.$logo_height.'" src="'.get_theme_mod('site_logo_sticky').'" class="header-logo-sticky" alt="'.$site_title.'"/>'; echo '<img width="'.$logo_width.'" height="'.$logo_height.'" src="'.flatsome_option('site_logo').'" class="header_logo header-logo" alt="'.$site_title.'"/>'; if(!get_theme_mod('site_logo_dark')) echo '<img width="'.$logo_width.'" height="'.$logo_height.'" src="'.flatsome_option('site_logo').'" class="header-logo-dark" alt="'.$site_title.'"/>'; if(get_theme_mod('site_logo_dark')) echo '<img width="'.$logo_width.'" height="'.$logo_height.'" src="'.get_theme_mod('site_logo_dark').'" class="header-logo-dark" alt="'.$site_title.'"/>'; } else { bloginfo( 'name' ); } ?> </a> <?php if(get_theme_mod('site_logo_slogan')){ echo '<p class="logo-tagline">'.get_bloginfo('description').'</p>'; } ?>
THIS IS THE WHOLE FUNCTIONS.PHP FILE IN MY CHILD THEME: <?php // Add custom Theme Functions here /** * Change text strings * * @link http://codex.wordpress.org/Plugin_API/Filter_Reference/gettext */ function custom_related_products_text( $translated_text, $text, $domain ) { switch ( $translated_text ) { case 'Related products' : $translated_text = __( 'More fire & security systems you may like', 'woocommerce' ); break; } return $translated_text; } add_filter( 'gettext', 'custom_related_products_text', 20, 3 ); /* USE SHORTCODES IN WIDGET TITLES AND PAGE TITLES !! */ add_filter('the_title', 'do_shortcode'); add_filter('widget_title', 'do_shortcode'); /* NOT SURE WHY I HAD THIS HERE??... <?php echo do_shortcode("[shortcode]"); ?> */ /* ADD ALT TAG TO GRAVATAR - BLOG-AUTHOR-IMAGE - IMAGES */ function crunchify_gravatar_alt($crunchifyGravatar) { if (have_comments()) { $alt = get_comment_author(); } else { $alt = get_the_author_meta('display_name'); } $crunchifyGravatar = str_replace('alt=\'\'', 'alt=\'Avatar for ' . $alt . '\' title=\'Gravatar for ' . $alt . '\'', $crunchifyGravatar); return $crunchifyGravatar; } add_filter('get_avatar', 'crunchify_gravatar_alt'); // LOGO CODE FOR SORTING ALT TEXT <!-- Header logo --> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?><?php echo get_bloginfo( 'name' ) && get_bloginfo( 'description' ) ? ' - ' : ''; ?><?php bloginfo( 'description' ); ?>" rel="home"> <?php if(flatsome_option('site_logo')){ $logo_height = get_theme_mod('header_height',90); $logo_width = get_theme_mod('logo_width', 200); $site_title = esc_attr( get_bloginfo( 'name', 'display' ) ); if(get_theme_mod('site_logo_sticky')) echo '<img width="'.$logo_width.'" height="'.$logo_height.'" src="'.get_theme_mod('site_logo_sticky').'" class="header-logo-sticky" alt="'.$site_title.'"/>'; echo '<img width="'.$logo_width.'" height="'.$logo_height.'" src="'.flatsome_option('site_logo').'" class="header_logo header-logo" alt="'.$site_title.'"/>'; if(!get_theme_mod('site_logo_dark')) echo '<img width="'.$logo_width.'" height="'.$logo_height.'" src="'.flatsome_option('site_logo').'" class="header-logo-dark" alt="'.$site_title.'"/>'; if(get_theme_mod('site_logo_dark')) echo '<img width="'.$logo_width.'" height="'.$logo_height.'" src="'.get_theme_mod('site_logo_dark').'" class="header-logo-dark" alt="'.$site_title.'"/>'; } else { bloginfo( 'name' ); } ?> </a> <?php if(get_theme_mod('site_logo_slogan')){ echo '<p class="logo-tagline">'.get_bloginfo('description').'</p>'; } ?>
I just can't get it to work, keeps throwing errors on save :( Hey, Basically the script runs fine except for the fact its just inserting one user instead of multiple users, anyone have a clue as to why? would be a huge hand, Cheers Code: [Select] <?php if (isset($_POST["submit"]) && $_POST["submit"] == "Recall Selected Informants") { //Force POST values to be INTs $addIDs_ary = array_map('intval', $_POST['chkInv']); //Remove any 'false' value $addIDs_ary = array_filter($addIDs_ary); //Check that there was at least one valid value if(count($addIDs_ary)) { //Create comma separated string of the IDs $addIDs_str = implode(',', $addIDs_ary); //Create and run one query to perform all the adds (of the user) $query = "INSERT INTO hitlist SET hit_id = '($addIDs_str)' AND player_id = '$playerID'"; $sql = "UPDATE players SET Informants = Informants - 1 WHERE id = '$playerID'"; mysql_query($sql) or die(mysql_error()); if(mysql_query($query)) { $selectedCount = count($addIDs_ary); $adddCount = mysql_affected_rows(); echo "{$adddCount} of {$selectedCount} Investigated player(s) were successfully added."; }else{ echo "There was a problem running the query.<br>" . mysql_error(); } }else{ echo "Invalid ID data passed."; } } hi i'm trying to insert this text just "we're pleased to announce etc........ect" but I can only insert "We" i believe its because single quotation mark. I've tried using addslashes, mysqli_real_escape_string and htmlspecialchars, strp_tags and applied it to my variable $s. But what ever i seem to try and insert still results in "we" being inserted. Cant see for the life of me why??? appreciate any help if (isset($_POST['submitted'])) { $errors = array(); if (empty($_POST['title'])) { $errors[] = '<p class="error">Either you haven\'t filled in the title or story for this news</p>'; } else { $t = mysqli_real_escape_string($dbc, $_POST['title']); } if (empty($_POST['story'])) { $errors[] = '<p class="error">Either you haven\'t filled in the title or story for this news</p>'; } else { $s = $_POST['story']; } echo $s; if(empty($errors)) { // No errors $q = "INSERT INTO news (title, story, date_added) values ('$t', '$s', NOW() )"; $r = mysqli_query($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc)); if (mysqli_affected_rows == !1) { // It didnt run ok $errors[] = '<p class="error">An error occured with your upload<a href="loggedin.php"> Admin</a></p>'; } else { echo 'Your news story has been added, visit <a href="news.php">News</a>'; } //if mysqli_affected rows } else { echo '<p class="error">The following errors occured<br />'; foreach ($errors as $msg) { echo " - $msg<br>"; } echo 'Please try again'; } // end of $errors } // End of submitted This is my code i'm using :-) as you an see i'm posting the variable $s which is ($_POST['story'] with no functions and it still only inserts "we" nothing more????? Code: [Select] elseif($_GET['rma']=="issue"){ session_start(); $rma_id=$_GET['id']; $_SESSION['rma_id']=$rma_id; $rma_issued=$_POST['rma_issued']; if($rma_issued=="y"){ $length = 2; $characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $string= microtime(true); for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } for ($p = 0; $p < $length; $p++) { $string2 .= $characters[mt_rand(0, strlen($characters))]; } $string="".$string2."".$string; $string=explode(".",$string); $string=$string[0].$string[1]; $rma_number=$string; date_default_timezone_set('US/Eastern'); $rma_date_issued = date("F j, Y, g:i A T"); $rma_month_issued = date("m"); $rma_year_issued = date("Y"); $sql2000000="UPDATE $tbl_name4 SET rma_number='$rma_number', rma_issued='$rma_issued', rma_date_issued='$rma_date_issued', rma_month_issued='$rma_month_issued', rma_year_issued='$rma_year_issued', returned='n' WHERE rma_id = $rma_id"; mysql_query($sql2000000); header("Location: ./acp_admincp.php?rma=issued"); } The above isn't inserting anything into the DB... not even the Date information. when i insert a new topic into the database its id is generated by the auto incrememnt field tid. but what i do next is insert the post for that new topic in the post table which has p_pid(post id) and p_tid(the topic id it is for). so how do i generate that p_tid when the topic has just been inserted. i used to do it by inserting the topic then running a query to pull the newest topic if from the database which would mean the post belonged to that topic. but what happens when people are posting several topics at the same time? |