PHP - Form Trouble
I'm not sure if this is a php issue or jquery issue. When I complete the form and hit submit it puts the successful message up like its supposed to but also with the fields still filled in the form which it shouldn't be doing and it doesn't actually post in the database so I'm not sure if its a php issue or jquery issue.
Code: [Select] <script type="text/javascript"> $(document).ready(function() { $('div.message-error').hide(); $('div.message-success').hide(); $("input.submit").click(function() { $('div.message-error').hide(); var templatename = $("input#templatename").val(); if (templatename == "") { $("div.message-error").show(); $("input#templatename").focus(); return false; } var headercode = $("textarea#headercode").val(); if (headercode == "") { $("div.message-error").show(); $("textarea#headercode").focus(); return false; } var footercode = $("textarea#footercode").val(); if (footercode == "") { $("div.message-error").show(); $("textarea#footercode").focus(); return false; } var dataString = 'templatename='+ templatename+ '&headercode=' + headercode + '&footercode=' + footercode; $.ajax({ type: "POST", url: "processes/template.php", data: dataString, success: function() { $("div.message-success").show(); return true; } }); return false; }); }); </script> <!-- Form --> <form action="#" name="templateform" > <fieldset> <legend>Add New Template</legend> <div class="field required"> <label for="templatename">Template Name</label> <input type="text" class="text" name="templatename" id="templatename" title="Template Name"/> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="headercode">Header Code</label> <textarea name="headercode" id="headercode" title="Header Code"></textarea> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="footercode">Footer Code</label> <textarea name="footercode" id="footercode" title="Footer Code"></textarea> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <input type="submit" class="submit" name="submittemplate" id="submittemplate" title="Submit Template" value="Submit Template"/> </fieldset> </form> <!-- /Form --> <!-- Messages --> <div class="message message-error"> <h6>Required field missing</h6> <p>Please fill in all required fields. </p> </div> <div class="message message-success"> <h6>Operation succesful</h6> <p>Template was added to the database.</p> </div> <!-- /Messages --> validation page <?php // Include the database page include ('inc/dbconfig.php'); if ((isset($_POST['templatename'])) && (strlen(trim($_POST['templatename'])) > 0)) { $templatename = stripslashes(strip_tags($_POST['templatename'])); } else {$templatename = 'No name entered';} if ((isset($_POST['headercode'])) && (strlen(trim($_POST['headercode'])) > 0)) { $headercode = stripslashes(strip_tags($_POST['headercode'])); } else {$headercode = 'No name entered';} if ((isset($_POST['footercode'])) && (strlen(trim($_POST['footercode'])) > 0)) { $footercode = stripslashes(strip_tags($_POST['footercode'])); } else {$footercode = 'No name entered';} $query = "INSERT INTO `templates` (templatename, header, footer, creator_id, datecreated) VALUES ('".$divisionname."','".$headercode."','".$footercode."' 1, NOW())"; mysql_query($query); ?> Similar TutorialsI'm not sure where the issue really lies after the form submits it DOES perform the error messages if there is one, however if the username and password are atleast filled in and the user clicks Log In it doesn't do anything after that. login.php <?php /** * @author Jeff Davidson * @copyright 2010 */ if (isset($_POST['submitted'])) { require_once ('inc/login_functions.php'); require_once ('inc/dbconfig.php'); list ($check, $data) = check_login($dbc, $_POST['username'], $_POST['password']); if ($check) { // OK! // Set the session data:. session_start(); $_SESSION['id'] = $data['id']; $_SESSION['firstname'] = $data['firstname']; // Redirect: $url = absolute_url ('loggedin.php'); header("Location: $url"); exit(); }else { // Unsuccessful! $errors = $data; } mysqli_close($dbc); } // End of the main submit conditional. include ('inc/login_page.php') ?> login_functions.php <?php /** * @author Jeff Davidson * @copyright 2010 */ // This page defines two functions used by the login/logout process. /* This function determines and returns an absolute URL. * It takes one argument: the page that concludes the URL. * The argument defaults to index.php. */ function absolute_url($page = 'index.php') { // Start defining the URL... // URL is http://plus the host name plus the current directory: $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); // Remove any trailing slashing: $url = rtrim($url, '/\\'); // Add the page $url .= '/' . $page; // Return the URL: return $url; } // End of absolute_url() function. /* This function validates the form data (the username and password). * If both are present, teh database is queried. * The function requires a database connection. * The function returns an array of information, including: * - a TRUE/FALSE variable indicating success * - an array of either errors or the database result */ function check_login($dbc, $username = '', $password = '') { $errors = array(); // Initialize error array. // Validate the username if (empty($username)) { $errors[] = 'You forgot to enter your username.'; } else { $u = mysqli_real_escape_string($dbc, trim($username)); } // Validate the password: if (empty($password)) { $errors[] = 'You forgot to enter your password.'; } else { $p = mysqli_real_escape_string($dbc, trim($password)); } if (empty($errors)) { // If everythings OK. // Retrieve the firstname and lastname for the username/password combination: $q = "SELECT id, firstname FROM users WHERE username='$u' AND password=SHA('$p')"; $r = @mysqli_query($dbc, $q); // Run teh query. // Check the result: if (mysqli_num_rows($r) == 1) { // Fetch the record: $row = mysqli_fetch_array($r, MYSQLI_ASSOC); // Return true and the record: return array(true, $row); }else { // Not a match! $errrors[] = 'The username and password entered do not match those on file.'; } } // End of empty ($errrors) IF. // Return false and the errors: return array(false, $errors); } //End of check_login() function. ?> login_page.php <?php /** * @author Jeff Davidson * @copyright 2010 */ // This page prints any errors associated with logging in and creates the login, including the form. // Prints any error messages, if they exists: if (!empty($errors)) { echo '<h1>Error!</h1> <p class="error">The following error(s) occured:<br />'; foreach ($errors as $msg) { echo " - $msg<br />\n"; } echo '</p><p>Please try again.</p>'; } // Display the form: ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="description" content="Caracole" /> <title>Titanium</title> <link HREF="favicon.ico" type="image/x-icon" rel="icon" /> <link HREF="favicon.ico" type="image/x-icon" rel="shortcut icon" /> <link rel="stylesheet" type="text/css" href="css/tripoli.simple.css" media="screen, projection, print" /> <link rel="stylesheet" type="text/css" href="css/base.css" media="screen, projection, print" /> <link rel="stylesheet" type="text/css" href="css/layout.css" media="screen, projection, print" /> <link rel="stylesheet" type="text/css" href="css/style.css" media="screen, projection, print" /> <link rel="stylesheet" type="text/css" href="css/theme.css" media="screen, projection, print" /> <link rel="stylesheet" type="text/css" href="css/icons.css" media="screen, projection, print" /> <script type="text/javascript" SRC="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> //<![CDATA[ document.write('<link rel="stylesheet" type="text/css" href="css/js/js.css" media="screen, projection, print" />'); //]]> $(document).ready(function(){ $(".close").click(function(){ $(this).parents(".message").hide("puff"); }); }); </script> <!--[if IE]> <link rel="stylesheet" type="text/css" href="css/ie/ie.css" media="screen, projection, print" /> <![endif]--> <!--[if lt IE 7]> <script src="js/DD_belatedPNG_0.0.7a-min.js" type="text/javascript"></script> <script> DD_belatedPNG.fix(' #header, h1, h1 a, .close, .field,.paginate .current, .icon, .required-icon'); </script> <link rel="stylesheet" href="css/ie/ie6.css" type="text/css" media="screen, projection"/> <![endif]--> </head> <body> <!-- Content --> <div id="login" class="content"> <div class="roundedBorders login-box"> <!-- Title --> <div id="title" class="b2"> <h2>Log In</h2> <!-- TitleActions --> <div id="titleActions"> <div class="actionBlock"> <a href="#">Forgot your password ?</a> </div> </div> <!-- /TitleActions --> </div> <!-- Title --> <!-- Inner Content --> <div id="innerContent"> <form action="login.php" method="post"> <div class="field"> <label for="username">Username</label> <input type="text" class="text" id="username" name="username" /> </div> <div class="field"> <label for="password">Password</label> <input type="password" class="text" id="password" name="password"/> </div> <div class="clearfix login-submit"> <span class="fleft"> <input type="checkbox" name="remember-me" id="remember-me" /> <label for="remember-me">Remember me</label> </span> <span class="fright"> <button class="button" type="submit" name="submit"><strong>Log In</strong></button> </span> </div> <input type="hidden" value="TRUE" name="submitted" /> </form> </div> <!-- /Inner Content --> <div class="bBottom"><div></div></div> </div> </div> </body> </html> loggedin.php <?php /** * @author Jeff Davidson * @copyright 2010 */ // The user is redirected here from login.php. session_start(); // Star the session. // If no session value is present, redirect the user: if (!isset($_SESSION['id'])) { require_once('inc/login_functions.php'); $url = absolute_url(); header("Location: $url"); exit(); } $page_title = 'Logged In!'; // Print a customized message: echo "<h1>Logged In!</h1> <p>You are now logged in, {$_SESSION['firstname']}!</p> <p><a href=\"logout.php\">Logout</a></p>"; ?> I thought I'd come back in and insert the file manager I have setup here. root/loggedin.php root/login.php root/inc/login_page.php root/inc/login_functions.php I'm trying to modify my existing comment form to only allow users to post comments. Right now anyone can visit the site and comment. Here is my code if($_POST['submit']){ if($_POST['$_SESSION['username']))==''){ $err = "You must login first"; }elseif($_POST['thecomment']==''){ $err = "You have to enter a comment."; }else{ $username = strip_tags($_POST['username']); $themessage = strip_tags($_POST['thecomment']); $ezdb->get_results("INSERT INTO user_comments (id,date_added, posted_by, message, image_id) VALUE ('','".time()."','".$name."','".$themessage."','".$imageid."')"); $err = "Thank you for your comment."; } } When a user is logged in, I still get the "you must log in error" Help please. This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=330011.0 Hi. My form involves a checkbox. Below is the code. The problem is that when I am not sure what to put on the php. I need for people to be able to check one box tow boxes or all three boxes. On the form side I have this: type="checkbox" name="formcheck[]" value="C". Not sure what to put on the php side and need some assistance Code: [Select] <label style="display: block; padding-left: 15px; text-indent: -15px; width:650px;"> <input style="width: 45px; height: 45px; padding: 0; margin:0; vertical-align: bottom; position: relative; top: -1px; *overflow: hidden;" type="checkbox" name="formcheck[]" value="A" /> Directory Listing </label> <label style="display: block; padding-left: 15px; text-indent: -15px;width:650px;"> <input style="width: 45px; height: 45px; padding: 0; margin:0; vertical-align: bottom; position: relative; top: -1px; *overflow: hidden;" type="checkbox" name="formcheck[]" value="B" /> Full page listing </label> <label style="display: block; padding-left: 15px; text-indent: -15px;width:650px;"> <input style="width: 45px; height: 45px; padding: 0; margin:0; vertical-align: bottom; position: relative; top: -1px; *overflow: hidden;" type="checkbox" name="formcheck[]" value="C" /> Receive a link to your website </label> Hi i'm new to PHP/web development but not new to coding. I have some php code that I grabed from a template where I am selecting data from a file and having it diplay on the screen in a form. My $query = "select * from file where" statement works and bring the data back to the screen. However, I want the data to be returned in a textarea instead of a text field that is not big enough to display the 3 paragraph that i need to display. Please see code below, thsi code will return the data but the text box only returns the data in a line, I need the data to be returned in a textarea, so I can update it. I have looked for the correct syntex with no luck, please correct me. $row = mysql_fetch_array($result, MYSQL_ASSOC); $recordid = $row['recordid']; $homepage = $row['homepage']; echo "<h2>Update About Us Information</h2>\n"; echo "<form enctype=\"multipart/form-data\" action=\"admin.php\" method=\"post\">\n"; echo "<table width=\"100%\" cellpadding=\"1\" border=\"1\">\n"; echo "<tr><td><h3>Record ID</h3></td><td>$recordid</td></tr>\n"; echo "<tr><td><h3>Homepage</h3></td><td><input type=\"text\" size=\"100\" name=\"homepage\" value=\"$homepage\" /></td></tr>\n"; echo "</table>\n"; echo "<input type=\"submit\" name=\"button\" value=\"Update\">\n"; echo "<input type=\"submit\" name=\"button\" value=\"Delete Product\">\n"; echo "</form>\n"; Working on a project for school and I am trying to code a form that feeds into a DB. I have been studying the syntax, reading and doing everything I can to get this to work. A little help, pointers, direction would be greatly appreciated. It may be my database structure so I included a image for anyone to see... and the files. Thanks in advance [attachment deleted by admin] Hello! Everything on this form emails the way it should except for the checkboxes. The email simply states "Array" instead of what services are checked off. I don't understand PHP that well so I used a contact form and tried to modify it to include the checkboxes. Didn't work out Please help. <?php // OPTIONS - PLEASE CONFIGURE THESE BEFORE USE! $yourEmail = "hello@mail"; // the email address you wish to receive these mails through $yourWebsite = ""; // the name of your website $thanksPage = ''; // URL to 'thanks for sending mail' page; leave empty to keep message on the same page $maxPoints = 4; // max points a person can hit before it refuses to submit - recommend 4 $requiredFields = "name,email,comments"; // names of the fields you'd like to be required as a minimum, separate each field with a comma // DO NOT EDIT BELOW HERE $error_msg = null; $result = null; $requiredFields = explode(",", $requiredFields); foreach($_POST["service"] as $value) { $service .= "$value\n"; } function clean($data) { $data = trim(stripslashes(strip_tags($data))); return $data; } function isBot() { $bots = array("Indy", "Blaiz", "Java", "libwww-perl", "Python", "OutfoxBot", "User-Agent", "PycURL", "AlphaServer", "T8Abot", "Syntryx", "WinHttp", "WebBandit", "nicebot", "Teoma", "alexa", "froogle", "inktomi", "looksmart", "URL_Spider_SQL", "Firefly", "NationalDirectory", "Ask Jeeves", "TECNOSEEK", "InfoSeek", "WebFindBot", "girafabot", "crawler", "www.galaxy.com", "Googlebot", "Scooter", "Slurp", "appie", "FAST", "WebBug", "Spade", "ZyBorg", "rabaz"); foreach ($bots as $bot) if (stripos($_SERVER['HTTP_USER_AGENT'], $bot) !== false) return true; if (empty($_SERVER['HTTP_USER_AGENT']) || $_SERVER['HTTP_USER_AGENT'] == " ") return true; return false; } if ($_SERVER['REQUEST_METHOD'] == "POST") { if (isBot() !== false) $error_msg .= "No bots please! UA reported as: ".$_SERVER['HTTP_USER_AGENT']; // lets check a few things - not enough to trigger an error on their own, but worth assigning a spam score.. // score quickly adds up therefore allowing genuine users with 'accidental' score through but cutting out real spam $points = (int)0; $badwords = array("adult", "beastial", "bestial", "blowjob", "clit", "cum", "cunilingus", "cunillingus", "cunnilingus", "cunt", "ejaculate", "fag", "felatio", "fellatio", "fuck", "fuk", "fuks", "gangbang", "gangbanged", "gangbangs", "hotsex", "hardcode", "jism", "jiz", "orgasim", "orgasims", "orgasm", "orgasms", "phonesex", "phuk", "phuq", "pussies", "pussy", "spunk", "xxx", "viagra", "phentermine", "tramadol", "adipex", "advai", "alprazolam", "ambien", "ambian", "amoxicillin", "antivert", "blackjack", "backgammon", "texas", "holdem", "poker", "carisoprodol", "ciara", "ciprofloxacin", "debt", "dating", "porn", "link=", "voyeur", "content-type", "bcc:", "cc:", "document.cookie", "onclick", "onload", "javascript"); foreach ($badwords as $word) if ( strpos(strtolower($_POST['comments']), $word) !== false || strpos(strtolower($_POST['name']), $word) !== false ) $points += 2; if (strpos($_POST['comments'], "http://") !== false || strpos($_POST['comments'], "www.") !== false) $points += 2; if (isset($_POST['nojs'])) $points += 1; if (preg_match("/(<.*>)/i", $_POST['comments'])) $points += 2; if (strlen($_POST['name']) < 3) $points += 1; if (strlen($_POST['comments']) < 15 || strlen($_POST['comments'] > 1500)) $points += 2; // end score assignments foreach($requiredFields as $field) { trim($_POST[$field]); if (!isset($_POST[$field]) || empty($_POST[$field])) $error_msg .= "Please fill in all the required fields and submit again.\r\n"; } if (!preg_match("/^[a-zA-Z-'\s]*$/", stripslashes($_POST['name']))) $error_msg .= "The name field must not contain special characters.\r\n"; if (!preg_match('/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\@([a-z0-9])(([a-z0-9-])*([a-z0-9]))+' . '(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i', strtolower($_POST['email']))) $error_msg .= "That is not a valid e-mail address.\r\n"; if (!empty($_POST['url']) && !preg_match('/^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(\d+))?\/?/i', $_POST['url'])) $error_msg .= "Invalid website url.\r\n"; if ($error_msg == NULL && $points <= $maxPoints) { $subject = "Automatic Form Email"; $message = "You received this e-mail message through your website: \n\n"; foreach ($_POST as $key => $val) { $message .= ucwords($key) . ": " . clean($val) . "\r\n"; } $message .= "\r\n"; $message .= 'IP: '.$_SERVER['REMOTE_ADDR']."\r\n"; $message .= 'Browser: '.$_SERVER['HTTP_USER_AGENT']."\r\n"; $message .= 'Points: '.$points; if (strstr($_SERVER['SERVER_SOFTWARE'], "Win")) { $headers = "From: $yourEmail\n"; $headers .= "Reply-To: {$_POST['email']}"; } else { $headers = "From: $yourWebsite <$yourEmail>\n"; $headers .= "Reply-To: {$_POST['email']}"; } if (mail($yourEmail,$subject,$message,$headers)) { if (!empty($thanksPage)) { header("Location: $thanksPage"); exit; } else { $result = 'Thank You! Your email was successfully sent.'; $disable = true; } } else { $error_msg = 'Your mail could not be sent this time. ['.$points.']'; } } else { if (empty($error_msg)) $error_msg = 'Your mail looks too much like spam, and could not be sent this time. ['.$points.']'; } } function get_data($var) { if (isset($_POST[$var])) echo htmlspecialchars($_POST[$var]); } ?> <!DOCTYPE html> <html lang="en"> <head> <title>Contact Us</title> <meta charset="utf-8"> <link rel="stylesheet" href="css/reset.css" type="text/css" media="all"> <link rel="stylesheet" href="css/style.css" type="text/css" media="all"> <script type="text/javascript" src="js/jquery-1.4.2.min.js" ></script> <script type="text/javascript" src="js/cufon-yui.js"></script> <script type="text/javascript" src="js/Humanst521_BT_400.font.js"></script> <script type="text/javascript" src="js/Humanst521_Lt_BT_400.font.js"></script> <script type="text/javascript" src="js/cufon-replace.js"></script> <script type="text/javascript" src="js/roundabout.js"></script> <script type="text/javascript" src="js/roundabout_shapes.js"></script> <script type="text/javascript" src="js/gallery_init.js"></script> <!--[if lt IE 7]> <link rel="stylesheet" href="css/ie/ie6.css" type="text/css" media="all"> <![endif]--> <!--[if lt IE 9]> <script type="text/javascript" src="js/html5.js"></script> <script type="text/javascript" src="js/IE9.js"></script> <![endif]--> </head> <body> <!-- header --> <header> <div class="container"> <h1><a href="index.html"></a></h1> <nav> <ul> <li><a href="index.html">Home</a></li> <li><a href="aboutpg/about.html">About</a></li> <li><a href="currentpg/current.html">Current</a></li> <li><a href="contact.php" class="current">Contact</a></li> </ul> </nav> </div> </header> <!-- #gallery --> <section id="gallery"> <div class="container"> <ul id="myRoundabout"> <li><img src="images/postcard.jpg"></li> </ul> </div> </section> <!-- /#gallery --> <div class="main-box"> <div class="container"> <div class="inside"> <div class="wrapper"> <!-- aside --> <aside> <h2>Contact <span></span></h2> <!-- .contacts --> <ul class="contacts"> <li><strong>Owner:</strong></li> <li><strong>Business:</strong></li> <li><strong>Address:</strong></li> <li><strong> </strong></li> <li><strong>Phone:</strong></li> <li><strong>Email:</strong> <script type="text/javascript"> /*<![CDATA[*/ /*********************************************** * Encrypt Email script- Please keep notice intact * Tool URL: http://www.dynamicdrive.com/emailriddler/ * **********************************************/ <!-- Encrypted version of: [at] *****.*** //--> var emailriddlerarray=[83,80,87,105,110,99,55,55,64,121,97,104,111,111,46,99,111,109] var encryptedemail_id20='' //variable to contain encrypted email for (var i=0; i<emailriddlerarray.length; i++) encryptedemail_id20+=String.fromCharCode(emailriddlerarray) document.write('<a href="mailto:'+encryptedemail_id20+'"></a>') /*]]>*/ </script></li> </ul> <!-- /.contacts --> <h3>Miscellaneous info:</h3> <p><a href="http://www.fireislandferries.com" target="_blank">Fire Island Ferries</a></p> <p><a href="http://www.googlemaps.com" target="_blank">Google Maps</a></p> <p><a href="http://www.fireislandnews.net" target="_blank">Fire Island News</a></p> <p><a href="http://www.fireislandtide.net" target="_blank">Fire Island Tide</a></p> </aside> <!-- content --> <section id="content"> <article> <h2><span>*All fields are required.</span></h2> <?php if ($error_msg != NULL) { echo '<p class="error">ERROR: '. nl2br($error_msg) . "</p>"; } if ($result != NULL) { echo '<p class="success">'. $result . "</p>"; } ?> <form action="<?php echo basename(__FILE__); ?>" method="post"> <noscript> <p><input type="hidden" name="nojs" id="nojs" /></p> </noscript> <label>Services Required (check off as many as required):</label> <br> <input type="checkbox" name="service[ ]" id="service_0" value="addition" align="right">Addition<br> <input type="checkbox" name="service[ ]" id="service_1" value="remodeling">Remodeling<br> <input type="checkbox" name="service[ ]" id="service_2" value="roof">Roof<br> <input type="checkbox" name="service[ ]" id="service_3" value="foundation">Foundation<br> <input type="checkbox" name="service[ ]" id="service_4" value="kitchen">Kitchen<br> <input type="checkbox" name="service[ ]" id="service_5" value="bath">Bath(s)<br> <input type="checkbox" name="service[ ]" id="service_6" value="tile">Tile Work<br> <input type="checkbox" name="service[ ]" id="service_7" value="window">Windows<br> <input type="checkbox" name="service[ ]" id="service_8" value="deck">Deck<br> <input type="checkbox" name="service[ ]" id="service_9" value="painting">Painting<br> <input type="checkbox" name="service[ ]" id="service_10" value="power washing">Power Washing<br> <input type="checkbox" name="service[ ]" id="service_11" value="opening closing">Spring Opening/Fall Closing <br><br> <br /> <p> <small>Name: </small><input type="text" name="name" id="name" value="<?php get_data("name"); ?>" size="22" placeholder="First Last"/> <label for="name"></label> </p> <p> <small>Phone: </small><input type="text" name="email" id="email" value="<?php get_data("phone"); ?>" size="22" placeholder="(123) 123-4567"/> <label for="phone"></label> </p> <p> <small>Email: </small><input type="text" name="email" id="email" value="<?php get_data("email"); ?>" size="22" placeholder="you@email.com"/> <label for="email"></label> </p> <p> <small>Message: </small><textarea name="comments" id="comments" placeholder="Please write a brief message here."><?php get_data("comments"); ?></textarea> <label for="comments" style="display:none;"></label> </p> <p> <input name="submit" type="submit" id="submit" value="Submit Form" <?php if (isset($disable) && $disable === true) echo ' disabled="disabled"'; ?> /> </p> </form> </div> </article> </section> </div> </div> </div> </div> <script type="text/javascript"> Cufon.now(); </script> </body> </html> Hey guys, I have made an admin page for a game Im working on to quickly allow me to update many aspects of the game. My form is sending the correct data because i can echo the $_post but for some reason it isnt updating my database. I just get a blank white page. Could anyone see what i have done wrong. Thanks Code: [Select] <?php require($DOCUMENT_ROOT . "/game/includes/connection.php"); require($DOCUMENT_ROOT . "/game/includes/settings.php"); ?> <?php $name = $_POST['admin_name']; $img = $_POST['admin_img']; $current_hp = $_POST['admin_current_hp']; $max_hp = $_POST['admin_max_hp']; $current_energy = $_POST['admin_current_energy']; $max_energy = $_POST['admin_max_energy']; $level = $_POST['admin_level']; $exp_total = $_POST['admin_exp_total']; $exp = $_POST['admin_exp']; $exp_level = $_POST['admin_exp_level']; $pos_x = $_POST['admin_pos_x']; $pos_y = $_POST['admin_pos_y']; $potion = $_POST['admin_potion']; $ether = $_POST['admin_ether']; $elixir = $_POST['admin_elixir']; $zenni = $_POST['admin_zenni']; $sector = $_POST['admin_sector']; $battle = $_POST['admin_battle']; ?> <?php $sql_1 = "UPDATE game_character SET name='$name', img='$img', current_hp='$current_hp', max_hp='$max_hp', current energy='$current_energy', max_energy='$max_energy', level='$level', exp_total='$exp_total', exp='$exp', exp_level='$exp_level', pos_x='$pos_x', pos_y='$pos_y', potion='$potion', ether='$ether', elixir='$elixir', zenni='$zenni' WHERE id=1"; $sql_2 = "UPDATE game_status SET sector='$sector', battle='$battle' WHERE id=1"; $statement_1 = $dbh->prepare($sql_1); $statement_2 = $dbh->prepare($sql_2); $statement_1->execute(); $statement_2->execute(); ?> <SCRIPT LANGUAGE="JavaScript"> redirTime = "1"; redirURL = "<?php echo $r_admin ?>"; function redirTimer() { self.setTimeout("self.location.href = redirURL;",redirTime); } </script> <BODY onLoad="redirTimer()"> Hi Guys, I'm struggling with a submit form via ajax. This is the code, but I've been looking for about 3 hours and cannot work out why it doesnt submit the form... Any ideas? <script type="application/javascript"> function addForm() { $.ajax({type:'POST', url: 'cart.php?ajax=1&a=add&domain=register', data:$('#add-form').serialize(), success: function(response) { $('#add-form').find('.form_result').html(response); }}); return false; } function transferForm() { $.ajax({type:'POST', url: 'cart.php?ajax=1&a=add&domain=transfer', data:$('#transfer-form').serialize(), success: function(response) { $('#transfer-form').find('.form_result').html(response); }}); return false; } </script>My code is mixed with smarty but the call is just a standard call {foreach from=$availabilityresults key=num item=result} {if $result.status eq "available"} <form method="post" id="add-form" onsubmit="return addForm();"> {else} <form method="post" id="transfer-form" onsubmit="return transferForm();"> {/if} <table width="700" border="0" cellspacing="5" cellpadding="0"> <input type="hidden" name="domain" value="{$result.domain}" /> <tr style="border-bottom: #333 1px solid;"> <td rowspan="2">{if $result.status eq "available"}<img src="templates/dj/yes.jpg" />{else}<img src="templates/dj/no.jpg" />{/if}</td> {if $result.status eq "available"}<td style="color:#339933;" />{$result.domain|replace:$domain:''}</td>{else}<td style="color:#cc0000;" />{$result.domain|replace:$domain:''}</td>{/if} <td rowspan="2">{$result.domain}</td> <td rowspan="2">{if $result.status eq "unavailable"}{else} <select name="domainsregperiod[{$result.domain}]"> {foreach key=period item=regoption from=$result.regoptions} <option value="{$period}">{$period} {$LANG.orderyears} @ {$regoption.register}</option> {/foreach} </select> {/if}</td> <td rowspan="2">{if $result.status eq "available"} <input type="image" src="templates/dj/add-basket.jpg" border="0" alt="Add to Basket" /><div class="form_result"> Added to Basket </div> {else} <input type="image" src="templates/dj/transfer.jpg" border="0" alt="Transfer to Us" /> {/if}</td> </tr> <tr> <td>{if $result.status eq "available"}Available{else}Taken{/if}</td> </tr> <tr><td colspan="8" style="height:1px; background-color:#999;"></td></tr> </table> </form> {/foreach} I have a form where people enter in values and I need these values displayed in the proper format. I need the output string to have a "<" at the beginning and a ">" at the end but whenever I put the code in to add the < in the beginning nothing shows up. Here is my code. I am able to get it to work with just adding the > at the end but it seems when I add "<" to the beginning this is where nothing shows up. Code: [Select] <?php $hairbald = trim($_POST['HairBald']); $eyes = trim($_POST['Eyes']); $test =$eyes.'.'.$hairbald; if(empty($test)) { $test = $test; } else $test = '<'.$test.'>'; ?> If the user selects blue eyes and bald head I need the output to be <blue.bald> (php is a weakness)
Here is the HTML portion for the form:
<form action="send_form_email.php" id="contacts-form" method="post"> Hi. So I've coded many a file upload form and never had any trouble. Until now. For some reason when I try to upload MP3 files, I'll hit submit and the page just reloads. Once it does so, the file upload field is once again blank. What's odd is that images and documents upload just fine. It's only audio tracks that cause the page to reload and clear. My php.ini max file upload size is at this point set to 100M, and the files I'm trying to upload are under 10M. Any ideas? Here's the form code, just to post it-- pretty basic. I'm at a loss here.... Any ideas would be appreciated. Thanks very much. <form action="test.php" enctype="multipart/form-data" method="POST"/> <input type = "file" name = "audio" /> <p><input type ="submit" name="submit" value="do it."/><p> </form> Hi Chaps, I have a PHP FTP App, where users can log in using a unique code and a password. Their unique code corresponds to an FTP folder, e.g. Quote \FTP_Root\Customer A & Co\ So when the user logs in, they can see their FTP directory and contents, in this case an Inbox and an Outbox. This works as the FTP folder contains both an Inbox and an Outbox. The problem I am having is when I try browsing within this directory (say the Inbox), ftp-chdir fails. I have a hyperlink that sends a 'dir' parameter to the same ftp.php page, and if set, will attempt to change to the given directory. So even though the URL Hyperlink reads: Quote ....server.co.uk/ftp.php?dir=/FTP_Root/Customer A & Co/Inbox When you click on this link, the page tries to load: Quote ....server.co.uk/ftp.php?dir=/FTP_Root/Customer A So my question is what do I need to change, the Hyperlink to read something like: Quote ....server.co.uk/ftp.php?dir=/FTP_Root/Customer%20A%20&%20Co/Inbox Do something to the ftp-chdir function, where I encode/decode/whatever to make sure it tries to change to the correct FTP directory? Or exclude all ampersand entirely? Building a website for work. I am struggling with the login for some reason. I`m using a lot of the same code as I did for my personal site and a few other websites I`ve programmed which has always worked. But for some reason, it isn`t working now. I`ve already told it to display to me the information that`s being processed and that is all correct (it even updates the database like it`s supposed to). It just won`t show the person being logged in, which defeats the purpose of logging in, yanno? Here are all the files in question. login.php <?php include "file_calls.php"; $title = "Business Name (Beta): Log In"; include "functions.php"; session_start(); echo "$title"; echo "<p>"; echo "Log into the Business Name website. Only authorized members of the Business Name Staff can log into the website."; echo "<p>"; include "login_form.php"; ?> login_form.php <?php echo "<form action='logging.php' method='post'>"; echo "E-Mail Address:"; echo "<br><input type='text' name='email' size=60 maxlength=100>"; echo "<p>"; echo "Password:"; echo "<br><input type='password' name='pass' size=60 maxlength=25>"; echo "<p>"; $buttonlabel = "Log In"; include "formbutton_format.php"; echo "</form>"; ?> logging.php <?php include "file_calls.php"; $title = "Business Name (Beta): Logging In"; include "functions.php"; session_start(); echo "$title"; echo "<p>"; echo "Logging into the Business Name website. Only authorized members of the Business Name Staff can log into the website."; echo "<p>"; $email = $_POST['email']; $pass = $_POST['pass']; $entry_date = strftime("%B\ %e\,\ %Y %I:%M:%S %p", time()); $res = mysql_query("SELECT id, memlev, pwd1, pwd2, email, name FROM user_data WHERE email='$email'"); $by = mysql_fetch_row($res); mysql_free_result($res); $log = $by[4]; $pas = $by[2]; $pas2 = $by[3]; if ($email && $pass) { if ($by[0]) { if ($by[1] == 2) { $passwd = crypt($_REQUEST['pass'],$by[5]); if ($pass == $pas2) { mysql_query("UPDATE user_data SET lastlogin='$entry_date' WHERE email='$email'"); mysql_close($con); header("Location: index.php"); } elseif ($passwd != $pas) { header("Location: nolog.php?logout=1&m=4"); } } elseif ($by[1] == 1) { header("Location: nolog.php?logout=1&m=2"); } elseif ($by[1] == 0) { header("Location: nolog.php?logout=1&m=3"); } } elseif (!$by[0]) { header("Location: nolog.php?logout=1&m=1"); } } elseif (!$email || !$pass) { echo "<b>Error:</b> Both username and password must be entered in order to log in."; echo "<p>"; include "login_form.php"; } ?>[/php index.php [php]<?php include "file_calls.php"; $title = "Business Name (Beta)"; include "functions.php"; session_start(); echo "$title"; echo "<p>"; echo "This website is currently under construction. Thank you for your patience."; echo "<p>"; if ($lev > 1) { echo "Hello, $loggeduser !"; } elseif ($lev < 2) { echo "Not logged in."; } echo "<p>"; echo "$lev"; echo "<br>$loggeduser<br>$email"; ?> auth.php <?php // Defines DEFINE('SESSION_MAGIC','sadhjasklsad2342'); // Initialization @session_start(); @ob_start(); /* Redirects to another page */ function Redirect($to) { @session_write_close(); @ob_end_clean(); @header("Location: $to"); } /* Deletes existing session */ function RemoveSession() { $_SESSION = array(); if (isset($_COOKIE[session_name()])) { @setcookie(session_name(), '', time()+(60*60*24*365), '/'); } } /* Checks if user is logged in */ function isLoggedIn() { return(isset($_SESSION['magic']) && ($_SESSION['magic']==SESSION_MAGIC)); } /* read message count */ function CountMessages($id) { if ($res=mysql_query("SELECT * FROM user_data WHERE email='$email'")) { $count=mysql_num_rows($res); mysql_free_result($res); return($count); } return 0; } /* Go login go! */ function Login($email,$pass) { global $nmsg, $rows; $ok=false; if ($res=mysql_query("SELECT id, email, name, pwd1, pwd2, memlev FROM user_data WHERE email='$email' AND pwd2='$pass'")) { if ($rows=mysql_fetch_row($res)) { $_SESSION['sess_name'] = $rows[2]; $_SESSION['pass'] = $pass; $_SESSION['gal'] = $rows[0]; $_SESSION['level2'] = $rows[5]; $_SESSION['email'] = $rows[1]; $_SESSION['magic'] = SESSION_MAGIC; $nmsg = CountMessages($rows[0]); $ok=true; } else { include('login_failed.php'); } mysql_free_result($res); } return($ok); } /* Terminates an existing session */ function Logout() { @RemoveSession(); @session_destroy(); } /* Escape array using mysql */ function Escape(&$arr) { if (Count($arr)>0) { foreach($arr as $k => $v) { if (is_array($v)) { Escape($arr[$k]); } else { if (function_exists('get_magic_quotes')) { if(!get_magic_quotes_gpc()) { $arr[$k] = stripslashes($v); } } $arr[$k] = mysql_real_escape_string($v); } } } } // ----------------------------------------------- // Main // ----------------------------------------------- Escape($_POST); Escape($_GET); Escape($_COOKIE); Escape($_REQUEST); Escape($_GLOBALS); Escape($_SERVER); ?> file_calls.php <?php include "info_con.php"; include "auth.php"; ?> functions.php <?php echo "<title>$title</title>"; $lev=isset($_SESSION['level2'])?$_SESSION['level2']:0; $logged=isset($_SESSION['gal'])?$_SESSION['gal']:0; $loggeduser=$_SESSION['sess_name']; $nmsg = 0; $rows = isset($_SESSION['rows'])?$_SESSION['rows']:array(); $email = isset($_SESSION['email'])?$_SESSION['email']:''; $pass = isset($_SESSION['pass'])?$_SESSION['pass']:''; function rand_chars($c, $l, $u = FALSE) { if (!$u) for ($s = '', $i = 0, $z = strlen($c)-1; $i < $l; $x = rand(0,$z), $s .= $c{$x}, $i++); else for ($i = 0, $z = strlen($c)-1, $s = $c{rand(0,$z)}, $i = 1; $i != $l; $x = rand(0,$z), $s .= $c{$x}, $s = ($s{$i} == $s{$i-1} ? substr($s,0,-1) : $s), $i=strlen($s)); return $s; } function ShowLoggedInBar() { global $email,$pass,$rows,$logid; $nmes=""; if($nmsg){ $nmes="($nmsg New)"; } echo "Hello, $loggeduser !"; } /* check if we are logging out */ if (isset($_REQUEST['logout'])) { Logout(); } /* check if already logged in */ if (isset($_SESSION['magic']) && ($_SESSION['magic']==SESSION_MAGIC)) { ShowLoggedInBar(); } else { /* not logged in, is it a form post? */ if (isset($_REQUEST['email']) && isset($_REQUEST['pass'])) { $email = $_REQUEST['email']; $pass = crypt($_REQUEST['pass'],$email); Login($email,$pass); } else { } } ?> Can anyone see why it works on everything but getting the person logged in? Hello everyone, I am new to this forum and PHP world. Doing my first project, a pretty complicated one to start with. I will be needing your help a lot to accomplish it. Here is the first one. 1. I have a certain field called 'country' 2. I have small flag icons for every country. WHAT DO I WANT TO DO? Example - If the country is U.S.A., the U.S. flag shows up and is a link to www.domain.com/usa If the country is Germany, the German flags shows up and is a link to www.domain.com/germany If the country is not set, no flag shows up. END. How do I execute this? This is what I am doing to get the image <img src="images/flags/<?php echo $row_rsPilots['country']; ?>.gif" alt="" name="Flag" width="20" height="20" id="Flag" /> How do make it a link to www.domain.com/'country' Thanks in advance This topic has been moved to CSS Help. http://www.phpfreaks.com/forums/index.php?topic=342058.0 i am not a coder by any means and my boss threw me under the bus to add an auto reply to this form. I've figured out that this is the code that the form uses to process - but now i have NO IDEA what to do. Can ANYONE help me with this? it's supposed to have instructions in the response and send a copy to us and the the submitter. THANKS SO MUCH IN ADVANCE!!! Here's the php form code: Code: [Select] <?php $EmailFrom = "Win One"; $EmailTo = "sales@capsonewire.com"; $Subject = "Registration"; $Name = Trim(stripslashes($_POST['Name'])); $Tel = Trim(stripslashes($_POST['Tel'])); $Email = Trim(stripslashes($_POST['Email'])); $Phone = Trim(stripslashes($_POST['Phone'])); $Message = Trim(stripslashes($_POST['Message'])); // validation $validationOK=true; if (!$validationOK) { print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">"; exit; } // prepare email body text $Body = ""; $Body .= "Name: "; $Body .= $Name; $Body .= "\n"; $Body .= "Email: "; $Body .= $Email; $Body .= "\n"; $Body .= "Phone: "; $Body .= $Phone; $Body .= "\n"; $Body .= "Message: "; $Body .= $Message; $Body .= "\n"; // send email $success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>"); // redirect to success page if ($success){ print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">"; } else{ print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">"; } ?> I wrote a simple sales tax function but it keeps come back with a sales tax of 0 the price is coming from a database. Code: [Select] function TotalSalesTax($price) { $salesTax = .07; $TotalSalesTax = $price * $salesTax; number_format($TotalSalesTax, 2); return $TotalSalesTax; } Code: [Select] <tr> <td></td> <td>Sales Tax: </td> <td><?php echo TotalSalesTax($price);?> </td> </tr> product page that the price comes from Code: [Select] <?php session_start(); if(!isset($_SESSION['quantity'])) { $_SESSION['quanity']=array(); //if there are no quantities selected, the array is empty if(is_array($_POST['quantity']))//if there are items in the cart { echo $quantity; header("location: checkOut.php"); } } require_once("functions.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <style type="text/css"> td { border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: #30C; border-right-color: #30C; border-bottom-color: #30C; border-left-color: #30C; } #productCatalog { width:400px; margin-right: auto; margin-left: auto; } </style> <link href="doggyTreats.css" rel="stylesheet" type="text/css" /> </head> <body> <?php logo(); navBar(); echo "<div id=\"productCatalog\">"; echo "<form action=\"checkOut.php\" method=\"post\" name=\"catalog\">"; DatabaseConnection(); $query = "SELECT * FROM treats"; $result_set = mysql_query($query) or die(mysql_error()); $i = 0; echo "<table>"; while ($row = mysql_fetch_array($result_set)) { echo"<tr><td width=\"2s00px\"><img src=\"{$row['product_pic']}\" /></td><td width=\"200px\">{$row['product_title']}.<br /><br />{$row['product_Description']}.<br /> Price: \${$row['price']}.<br /><br />Quantity <input name=\"quantity\" type=\"text\" size=\"2\" /></td></tr>"; } echo "<tr>"; echo "<td><input name=\"submit\" type=\"submit\" value=\"Proceed to Checkout\" />"; echo "</table>"; echo "</form>"; echo "</div>"; footer(); ?> </body> </html> I don't get why this fails. date() is meant to be a string, so why does it not concatenate correctly? Code: [Select] date_default_timezone_set('UTC'); $inputTime = date('c'); $inputTime = $inputTime . ' (UTC)'; // or $inputTime = date('c') . ' (UTC)'; Thanks. I am trying to put the tree of an XML file into an array. sample.xml Code: [Select] <?xml version='1.0' encoding='UTF-8'?> <getHistogramsResponse xmlns="http://www.ebay.com/marketplace/search/v1/services"> <ack>Success</ack> <version>1.7.0</version> <timestamp>2010-09-01T12:13:31.480Z</timestamp> <aspectHistogramContainer> <domainName>UK_CamerasPhoto_DigitalCameras_DigitalCameras_JN</domainName> <domainDisplayName>Digital Cameras</domainDisplayName> <aspect name="Brand"> <valueHistogram valueName="Canon"> <count>4323</count> </valueHistogram> <valueHistogram valueName="Sony"> <count>2210</count> </valueHistogram> </aspect> </aspectHistogramContainer> </getHistogramsResponse> $this->cXmlToArray->m_arr = GetXMLTree('sample.xml') if (isset($this->cXmlToArray->m_arr['getHistogramsResponse']['aspectHistogramContainer'][0])) { $this->m_arrResult = $this->cXmlToArray->m_arr['getHistogramsResponse']['aspectHistogramContainer']; } else if (count($this->cXmlToArray->m_arr['getHistogramsResponse']['aspectHistogramContainer']) > 0) { $this->m_arrResult[] = $this->cXmlToArray->m_arr['getHistogramsResponse']['aspectHistogramContainer']; } However my output is showing as: Array ( [0] => Array ( [domainName] => UK_CamerasPhoto_DigitalCameras_DigitalCameras_JN [domainDisplayName] => Digital Cameras [aspect] => Array ( [0] => Array ( [valueHistogram] => Array ( [0] => Array ( [count] => 4311 ) [1] => Array ( [count] => 2209 ) ) ) ) So how do I get it to return the attributes name and valueName? Any help will be greatly appreciated. |