How to debug a form that is not saving data? [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have made a signup page in PHP, I've made it ask for a name, username, email, password (and confirm), gender and country. I can make it all go through except the first and last name, which are not posting to my database.
I think it won't post to the database because the names are not going through. I have tried a lot and I'm now completely stuck. I've tried google, youtube etc and I can't find anything.
<?php
session_start();
include_once("php_includes/check_login_status.php");
if($user_ok == true){
header("location: profile.php?u=".$_SESSION["username"]);
exit();
}
?>
<?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
include_once("php_includes/db_connect.php");
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uname_check = mysqli_num_rows($query);
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#FFF;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
?>
<?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_connect.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES\
$f = $_POST['firstname'];
$l = $_POST['lastname'];
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($f = "" || $l = "" || $u == "" || $e == "" || $p == "" || $g == "" || $c == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else if (strlen($p) < 8) {
echo 'Your password must be 8 characters';
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
$p_md5 = md5($p);
$p_hash = hash('sha512', $p_md5);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (firstname, lastname, username, email, password, gender, country, ip, signup, lastlogin, notescheck)
VALUES('$f', '$l', '$u','$e','$p_hash','$g','$c,'$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
if(!$query) {
echo "DB1, FAIL<br>";
} else {
echo "DB1, Success<br>";
}
// Establish their row in the useroptions table
$sql = 'INSERT INTO useroptions (id, username, background)
VALUES ("$uid", "$u", "original")';
$query = mysqli_query($db_conx, $sql);
if(!$query) {
echo "DB2, FAIL<br>";
} else {
echo "DB2, Success<br>";
}
// Establish their row in the links table
$url = "www.elefind.x10.bz/profile.php?u=$u";
$sql = "INSERT INTO links (link_id, site_id, url, title, subtitle, description, fulltxt, indexdate, size, md5sum, visible, level)
VALUES('', '', '$url', '$u', '$f $l', '', now(), '', '', '', '')";
$query = mysqli_query($db_conx, $sql);
if(!$query) {
echo "DB3, FAIL<br>";
} else {
echo "DB2, Success<br>";
}
echo "Fname: ".$f."<br>";
echo "Lname: ".$l."<br>";
echo "Uname: ".$u."<br>";
echo "pwd: ".$p_hash."<br>";
echo "Gender: ".$g."<br>";
echo "Country: ".$c."<br>";
echo "ip: ".$ip."<br>";
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/")) {
mkdir("user/", 0755);
echo "User folder created.<br>";
}
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
echo "profile folder created.<br>";
}
// Email the user their activation link
$to = "$e";
$from = "noreply#elefind.x10.bz";
$subject = 'Elefind Account Activation';
$message = ' <!DOCTYPE html>';
$message .= ' <html>';
$message .= ' <head>';
$message .= ' <meta charset="UTF-8">';
$message .= ' <title>Elefind Message</title>';
$message .= ' </head>';
$message .= ' <body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;">';
$message .= ' <table style="background:#343642;padding:40px;border:1px solid #DDD;margin:0 auto;font-family:calibri;">';
$message .= ' <tr>';
$message .= ' <td>';
$message .= ' <table style="background:#505260;width:100%;border:1px solid #CCC;padding:0;margin:0;border-collapse:collapse;max-width:100%;width:550px;border-radius:10px;">';
$message .= ' <!-- Logo -->';
$message .= ' <tr>';
$message .= ' <td style="padding:10px 30px;text-align:center;margin:0">';
$message .= ' <p>';
$message .= ' <img src="http://www.elefind.x10.bz/img/logo.png" width="100">';
$message .= ' </p>';
$message .= ' </td>';
$message .= ' </tr>';
$message .= ' <!-- Welcome Salutation -->';
$message .= ' <tr>';
$message .= ' <td style="padding:10px 30px;margin:0;font-size:2.5em;color:#4A7BA5;text-align:center;">';
$message .= ' Welcome to Elefind!';
$message .= ' </td>';
$message .= ' </tr>';
$message .= ' <!-- User Msg -->';
$message .= ' <tr>';
$message .= ' <td style="padding:10px 30px;margin:0;text-align:left;color:FFF;">';
$message .= ' <p>Hey there '.$u.',</p>';
$message .= ' <p>To activate your profile please follow link on the below link,</p>';
$message .= ' </td>';
$message .= ' </tr>';
$message .= ' <!-- Link Button -->';
$message .= ' <tr>';
$message .= ' <td style="padding:10px 30px;text-align:center;">';
$message .= ' <a href="http://elefind.x10.bz/activation.php?id='.$uid.'&u='.$u.'&e='.$e.'&p='.$p_hash.'" title="Activate Profile">';
$message .= ' <img src="http://elefind.x10.bz/img/activate.png" width="300" height="auto">';
$message .= ' </img>';
$message .= ' </a>';
$message .= ' </td>';
$message .= ' </tr>';
$message .= ' <!-- Seperator -->';
$message .= ' <tr>';
$message .= ' <td style="padding:10px 30px;">';
$message .= ' </td>';
$message .= ' </tr>';
$message .= ' <!-- Footer Content -->';
$message .= ' <tr>';
$message .= ' <td style="padding:10px 30px;margin:0;background:#555;color:#CCC;border-top:1px solid #CCC;">';
$message .= ' <p>Once your account is active you can sign in with your email adress.</p>';
$message .= ' <p>Didn\'t request this? If you didn\'t request a to make an account with us, please let us know.</p>';
$message .= ' <p>This email is sent from an unmonitored address. Please do not reply.<!-- Please use links inline to get additional information or help.--></p>';
$message .= ' <!--<p>If you no longer wish to receive these emails, click here to Unsubscribe</p>-->';
$message .= ' </td>';
$message .= ' </tr>';
$message .= ' </table>';
$message .= ' <!-- Some more content -->';
$message .= ' <tr>';
$message .= ' <td style="padding:10px 30px;margin:0;font-size:10px;">';
$message .= ' <p> Click on the link above to activate your account, If the button does not work please use the following link,</br>';
$message .= ' <a href="http://elefind.x10.bz/activation.php?id='.$uid.'&u='.$u.'&e='.$e.'&p='.$p_hash.'">';
$message .= ' http://elefind.x10.bz/activation.php?id='.$uid.'&u='.$u.'&e='.$e.'&p='.$p_hash;
$message .= ' </a>';
$message .= ' </p>';
$message .= ' </td>';
$message .= ' </tr>';
$message .= ' </td>';
$message .= ' </tr>';
$message .= ' </table>';
$message .= ' </body>';
$message .= ' </html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "ACCOUNT_CREATED_SUCCESSFULLY";
exit();
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<head name="Default">
<link rel="icon" href="favicon.ico" type="image/x-icon">
<meta charset="UTF-8">
<title>Sign Up</title>
</head>
<head name="CSS">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/pages/signup.css">
<link rel="stylesheet" href="css/header.css">
<link rel="stylesheet" href="css/footer.css">
<link rel="stylesheet" href="css/fonts.css">
</head>
<head name="JS">
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="js/pages/signup.js"></script>
<script src="js/header.js"></script>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
$('.send').click(function(e){
$(".send").addClass("sending");
})
function restrict(elem){
var tf = document.getElementById(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[' "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
} else if(elem == "name"){
rx = /[^a-z]/gi;
} else if(elem == "name"){
rx = /[^a-z]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
document.getElementById(x).innerHTML = "";
}
function checkusername(){
var u = document.getElementById("username").value;
if(u != ""){
document.getElementById("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
document.getElementById("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
function signup(){
var fn = document.getElementById("firstname").value;
var ln = document.getElementById("lastname").value;
var u = document.getElementById("username").value;
var e = document.getElementById("email").value;
var p1 = document.getElementById("pass1").value;
var p2 = document.getElementById("pass2").value;
var c = document.getElementById("country").value;
var g = document.getElementById("gender").value;
var status = document.getElementById("status");
if(fn == "" || ln == ""|| u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == ""){
status.innerHTML = "Some of the form data is missing, Please fill it all out.<br>first name: "+fn+"<br>Last name: "+ln;
$(".send").removeClass("sending");
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
$(".send").removeClass("sending");
} else {
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "ACCOUNT_CREATED_SUCCESSFULLY"){
status.innerHTML = ajax.responseText;
$(".send").removeClass("sending");
} else {
window.scrollTo(0,0);
$(".send").removeClass("sending");
document.getElementById("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account. <br><br>fname: "+fn+"<br>lname: "+ln+"<br> username: "+u+"<br>email: "+e+"<br>password: "+p1+ "<br><br>Correct?";
}
}
}
ajax.send("fn="+fn+"&ln="+ln+"&u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g);
}
}
</script>
</head>
</head>
<body>
<?php include_once("header.php"); ?>
<div class="content">
<div class="cont">
<form name="signupform" id="signupform" action="signup()">
<div class="demo">
<div class="signup">
<div class="signup__check"></div>
<div class="signup__form">
<div class="signup__row">
<input type="text" placeholder="First name" class="signup__input name" id="firstname" name="firstname" onfocus="emptyElement('status')" onkeyup="restrict('name')" maxlength="32">
<br>
</div>
<div class="signup__row">
<input type="text" placeholder="Last name" class="signup__input name" id="lastname" name="lastname" onfocus="emptyElement('status')" onkeyup="restrict('name')" maxlength="32">
<br>
</div>
<div class="signup__row">
<input type="text" placeholder="Username" class="signup__input name" id="username" onfocus="emptyElement('status')" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<br>
<span id="unamestatus"></span>
</div>
<div class="signup__row">
<input type="text" placeholder="Email" class="signup__input name" id="email" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
</div>
<div class="signup__row">
<input type="password" placeholder="Password" class="signup__input pass" id="pass1" onfocus="emptyElement('status')" maxlength="16">
</div>
<div class="signup__row">
<input type="password" placeholder="Confirm password" class="signup__input pass" id="pass2" onfocus="emptyElement('status')" maxlength="16">
</div>
<div class="signup__row">
<select id="gender" onfocus="emptyElement('status')" placeholder="Gender" class="signup__input">
<option value="">Please select a gender</option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
</div>
<div class="signup__row">
<select id="country" onfocus="emptyElement('status')" placeholder="Country" class="signup__input">
<?php include_once("inc/countries.php"); ?>
</select>
</div>
<div>
<p class="signup__terms"> By creating an account you accept the terms of service </p>
</div>
<p id="status"></p>
<button id="signupbtn" onclick="signup()" class="send"name="Submit">Sign up</button>
</div>
</div>
</div>
</form>
</div>
</div>
<?php include_once("footer.php"); ?>
</body>
</html>

In your code besides what was mentioned in the comments you have an if statement that is assigning variables.
if($f = "" || $l = "" || $u == "" || $e == "" || $p == "" || $g == "" || $c == ""){}
Notice the = and not == after $f and $l, it should be:
if($f == "" || $l == "" || $u == "" || $e == "" || $p == "" || $g == "" || $c == ""){}
This way you aren't replacing the original contents and are now checking the contents.
And for future an empty() check will check for "" or even unset POST variables, allowing you to check missing POST values and empty strings in 1 go.

trap for the weary who have gazed at the screen for way, way tool long
if($f = "" || $l = "" || $u == "" || $e == "" || $p == "" || $g == "" || $c == ""){
In the line above you use a single = for $f and $l which gives them new values, in this case "".
Change it to
if($f == "" || $l == "" || $u == "" || $e == "" || $p == "" || $g == "" || $c == ""){
and you'll be back in business!

Related

PHP Focus on input

I am trying to create a PHP validation FORM.
Validation errors are displaying correctly for me every time. My only problems is that I am not able to set the focus on the input with error if an error came.
For example, I am using $rut_error, $first_name_error, $last_name_error, $email_error, $address_error and I want to set focus on the corresponding input if any error came.
I tried using javascript but I am not cleared where should I put that code, Could anyone guide me how to solve it? Can I fix this only with PHP? Please help.
I tried entering here but no success:
//First name Validation
if (empty($_POST["first_name"]) and $rut_error == '')
{
$first_name_error = "First name is required";
echo "<script>document.registration.first_name.focus();</script>";
}
My code is below:
addStudent.php
<html>
<head>
<title>Add Client</title>
</head>
<body>
Show Client
<?php include('form_processStudent.php'); ?>
<div id="divAgenda">
<form id="contact" action="<?= htmlspecialchars($_SERVER["PHP_SELF"]) ?>" method="post" name = "registration">
<fieldset>
<span class="error"><?= $rut_error ?></span><br>
<input placeholder="Rut..." id="rut" type="text" name="rut" value="<?= $rut ?>" tabindex="1" size="8" maxlength="8"> - <input type="text" name="dv" value="<?= $dv ?>" size="1" tabindex="2" maxlength="1"> Ejemplo: 12345678-1<br>
</fieldset>
<fieldset>
<span class="error"><?= $first_name_error ?></span><br>
<input placeholder="Primer Nombre..." id="first_name" type="text" id="first_name" name="first_name" value="<?= $first_name ?>" maxlength="50" tabindex="3"><br>
</fieldset>
<fieldset>
<span class="error"><?= $last_name_error ?></span><br>
<input placeholder="Segundo Nombre..." id="last_name" type="text" id="last_name" name="last_name" value="<?= $last_name ?>" maxlength="50" tabindex="4"><br>
</fieldset>
<fieldset>
<span class="error"><?= $email_error ?></span><br>
<input placeholder="Correo Electrónico..." id="email" type="text" name="email" value="<?= $email ?>" maxlength="100" tabindex="5"><br>
</fieldset>
<fieldset>
<span class="error"><?= $address_error ?></span><br>
<input placeholder="Dirección..." id="address" type="text" name="address" value="<?= $address ?>" maxlength="200" tabindex="5"><br>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Enviar</button>
</fieldset>
</form>
</body>
</html>
form_processStudent.php
<?php
// define variables and set to empty values
echo"<script>
document.registration.last_name.focus();
return false;
</script>";
$rut_error = $first_name_error = $last_name_error = $email_error = $address_error = "";
$rut = $dv = $first_name = $last_name = $email = $address = "";
if(isset($_POST['submit']))
{
//RUT Validation
$rut = test_input($_POST["rut"]);
$dv = ($_POST["dv"]);
if ( empty($_POST["rut"]))
{
$rut_error = "RUT is required";
}
else if ( $dv=='' )
{
$rut_error = "Verification digit is required";
}
else if (!is_numeric($rut))
{
$rut_error = "Entered RUT is not numeric";
}
else if (!((strlen($rut) == 7) or (strlen($rut) == 8)))
{
$rut_error = "Number of digits of RUT not valid";
}
else
{
$x = 2; $s = 0; $dv2 = 0;
for($i = (strlen($rut) - 1); $i >= 0; $i--)
{
if($x > 7)
$x = 2;
$s += ($rut[$i] * $x);
$x++;
}
$dv2=11-($s % 11);
if($dv2 == 10)
$dv2 = 'K';
if($dv2 == 11)
$dv2 = '0';
if($dv2 == $dv)
{
//echo "<br>". "rut={" . $rut . "}";
//echo "<br>". "dv ={" . $dv . "}";
}
else
$rut_error = "invalid RUT";
}
//First name Validation
if (empty($_POST["first_name"]) and $rut_error == '')
{
$first_name_error = "First name is required";
echo "<script>document.registration.first_name.focus();</script>";
}
else
{
if ($rut_error == '')
{
$first_name = test_input($_POST["first_name"]);
//echo "<br>". "first_name={" . $first_name . "}";
}
}
//Last name Validation
if (empty($_POST["last_name"]) and $rut_error == '' and $first_name_error == '')
{
$last_name_error = "Second name is required";
echo "<script>function validateform()
{
document.registration.last_name.focus();
return false;
}
</script>";
}
else
{
if ($rut_error == '' and $first_name_error == '')
{
$last_name = test_input($_POST["last_name"]);
//echo "<br>". "last_name={" . $last_name . "}";
}
}
//Email Validation
if (empty($_POST["email"]) and $rut_error == '' and $first_name_error == '' and $last_name_error == '')
{
$email_error = "Email is required";
}
else
{
if ($rut_error == '' and $first_name_error == '' and $last_name_error == '')
{
$email = test_input($_POST["email"]);
//echo "<br>". "email={" . $email . "}";
// check if e-mail address is well-formed
if ((!filter_var($email, FILTER_VALIDATE_EMAIL)) and $rut_error == '' and $first_name_error == '' and $last_name_error == '')
{
$email_error = "Invalid email";
}
}
}
//Adress Validation
if (empty($_POST["address"]) and $rut_error == '' and $first_name_error == '' and $last_name_error == '' and $email_error == '')
{
$address_error = "Address is required";
}
else
{
if ($rut_error == '' and $first_name_error == '' and $last_name_error == '' and $email_error == '')
{
$address = test_input($_POST["address"]);
//echo "<br>". "address={" . $address . "}";
}
}
if ($rut_error == '' and $first_name_error == '' and $last_name_error == '' and $email_error == '' and $address_error == '')
{
//echo "<br>". "Dentro de IF";echo "<br>";
require_once('mysqli_connect.php');
$query = "INSERT INTO students (rut, dv, first_name, last_name, email, address) VALUES (?,?,?,?,?,?)";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, "ssssss", $rut, $dv, $first_name, $last_name, $email, $address);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
echo 'affected_rows=<' . $affected_rows . '>';
if($affected_rows == 1)
{
$rut = $dv = $first_name = $last_name = $email = $address = '';
echo "<br>"."Client Entered";
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}
else
{
echo 'Error Occurred<br />';
echo mysqli_error();
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
getStudentInfo.php
Add Client
<?php
// Get a connection for the database
require_once('mysqli_connect.php');
// Create a query for the database
$query = "SELECT serie, rut, dv, first_name, last_name, email, address FROM students ORDER BY serie desc";
// Get a response from the database by sending the connection
// and the query
$response = #mysqli_query($dbc, $query);
// If the query executed properly proceed
if($response)
{
echo '<table align="left" cellspacing="5" cellpadding="8">
<tr><td align="left"><b>Serie </b></td>
<td align="left"><b>Rut </b></td>
<td align="left"><b>Dígito Verificador </b></td>
<td align="left"><b>Primer Nombre </b></td>
<td align="left"><b>Segundo Nombre </b></td>
<td align="left"><b>Email </b></td>
<td align="left"><b>Dirección </b></td>
</tr>';
// mysqli_fetch_array will return a row of data from the query
// until no further data is available
while($row = mysqli_fetch_array($response))
{
echo '<tr><td align="left">' . $row['serie'] . '</td>
<td align="left">' . $row['rut'] . '</td>
<td align="left">' . $row['dv'] . '</dv>
<td align="left">' . $row['first_name'] . '</td>
<td align="left">' . $row['last_name'] . '</td>
<td align="left">' . $row['email'] . '</td>
<td align="left">' . $row['address'] . '</td>'
;
echo '</tr>';
}
echo '</table>';
}
else
{
echo "Couldn't issue database query<br />";
echo mysqli_error($dbc);
}
// Close connection to the database
mysqli_close($dbc);
?>
mysqli_connect.php
<?php
// Defined as constants so that they can't be changed
DEFINE ('DB_USER', 'studentweb');
DEFINE ('DB_PASSWORD', '123');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'dbTest');
// $dbc will contain a resource link to the database
// # keeps the error from showing in the browser
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die('Could not connect to MySQL: ' . mysqli_connect_error());
//echo "Connected...\n\n";
?>
You can do it via javascript.
You put a script that would work once the page is fully loaded.
The script will checkout the content of each <span class="error">. If some non empty one is found, it shall put the focus on it.
In your html:
<body>
...
<script type="text/javascript">
window.onload = function(){
var errors = document.querySelectorAll('.error');
for(var i = 0, l = errors.length; i < l; i++){
var error = errors[i],
shouldForcus = error.textContent.trim().length !== 0;
if(shouldFocus){
var input = error.parentNode.querySelector('input');
input.focus();
break;
}
}
}
</script>
</body>

sign up form Code not working

Hello Guys this is sign up form. Please read this code and try to answer
I have two problems with this code
1) I am getting a warning
Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\signup.php:252) in C:\xampp\htdocs\signup.php on line 295
2) When I click on Create account after filling form the button does nothing
i.e. it does not inserting values in table.
<?php
session_start();
// If user is logged in, header them away
if(isset($_SESSION["username"])){
header("location: message.php?msg=NO to that weenis");
exit();
}
?><?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
include_once("includes/db_connnection.php");
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uname_check = mysqli_num_rows($query);
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
?><?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("includes/db_connection.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$n = preg_replace('#[^a-z ]#i', '', $_POST['n']);
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$s = preg_replace('#[^a-z ]#i', '', $_POST['s']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($n == "" || $u == "" || $e == "" || $n == "" || $p == "" || $g == "" || $s == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
$p_hash = md5($p);
//$cryptpass = hash('sha1',$p);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (name, username, email, password, gender, stream, ip, signup, lastlogin, notescheck)
VALUES('$n','$u','$e', '$p_hash','$g','$s','$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Establish their row in the useroptions table
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
// Email the user their activation link
$to = "$e";
$from = "example#gmail.com";
$subject = 'yoursitename Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>yoursitename Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;"><img src="http://www.yoursitename.com/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;">yoursitename Account Activation</div><div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* E-mail Address: <b>'.$e.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
#signupform{
margin-top:24px;
}
#signupform > div {
margin-top: 12px;
}
#signupform > input,select {
width: 200px;
padding: 3px;
background: #F3F9DD;
}
#signupbtn {
font-size:18px;
padding: 12px;
}
#terms {
border:#CCC 1px solid;
background: #F5F5F5;
padding: 12px;
}
</style>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[' "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var n = _("name").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var s = _("stream").value;
var g = _("gender").value;
var status = _("status");
if(n == "" || u == "" || e == "" || n == "" || p1 == "" || p2 == "" || s == "" || g == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else if( _("terms").style.display == "none"){
status.innerHTML = "Please view the terms of use";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&n="+n+"&e="+e+"&n="+n+"&p="+p1+"&s="+s+"&g="+g);
}
}
function openTerms(){
_("terms").style.display = "block";
emptyElement("status");
}
/* function addEvents(){
_("elemID").addEventListener("click", func, false);
}
window.onload = addEvents; */
</script>
</head>
<body>
<div id="pageMiddle">
<h3>Sign Up Here</h3>
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Name:</div>
<input id="name" type="text" onfocus="emptyElement('status')">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="88">
<div>Confirm Password:</div>
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="100">
<div>Gender:</div>
<select id="gender" onfocus="emptyElement('status')">
<option value=""></option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
<div>Stream:</div>
<select id="stream" onfocus="emptyElement('status')">
<option disabled selected value>--select your option--</option>
<option value="Arts">India</option>
<option value="Biology">USA</option>
<option value="Maths">Russia</option>
</select>
<div>
<a href="#" onclick="return false" onmousedown="openTerms()">
View the Terms Of Use
</a>
</div>
<div id="terms" style="display:none;">
<h3>Web Intersect Terms Of Use</h3>
<p>1. Play nice here.</p>
<p>2. Take a bath before you visit.</p>
<p>3. Brush your teeth before bed.</p>
</div>
<br /><br />
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
</div>
</body>
</html>
<?php
if (isset($_GET['id']) && isset($_GET['u']) && isset($_GET['e']) && isset($_GET['p'])) {
// Connect to database and sanitize incoming $_GET variables
include_once("includes/db_connection.php");
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
$e = mysqli_real_escape_string($db_conx, $_GET['e']);
$p = mysqli_real_escape_string($db_conx, $_GET['p']);
// Evaluate the lengths of the incoming $_GET variable
if($id == "" || strlen($u) < 3 || strlen($e) < 5 || strlen($p) != 74){
// Log this issue into a text file and email details to yourself
header("location: message.php?msg=activation_string_length_issues");
exit();
}
// Check their credentials against the database
$sql = "SELECT * FROM users WHERE id='$id' AND username='$u' AND email='$e' AND password='$p' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
// Evaluate for a match in the system (0 = no match, 1 = match)
if($numrows == 0){
// Log this potential hack attempt to text file and email details to yourself
header("location: message.php?msg=Your credentials are not matching anything in our system");
exit();
}
// Match was found, you can activate them
$sql = "UPDATE users SET activated='1' WHERE id='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
// Optional double check to see if activated in fact now = 1
$sql = "SELECT * FROM users WHERE id='$id' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
// Evaluate the double check
if($numrows == 0){
// Log this issue of no switch of activation field to 1
header("location: message.php?msg=activation_failure");
exit();
} else if($numrows == 1) {
// Great everything went fine with activation!
header("location: message.php?msg=activation_success");
exit();
}
} else {
// Log this issue of missing initial $_GET variables
header("location: message.php?msg=missing_GET_variables");
exit();
}
?>
ajax.js file
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
main.js file
function _(x){
return document.getElementById(x);
}
function toggleElement(x){
var x = _(x);
if(x.style.display == 'block'){
x.style.display = 'none';
}else{
x.style.display = 'block';
}
}

Need help to troubleshoot php (Warning: Missing argument 11 ...)

I have had to modify some php code to suit my needs and my forms page is now spitting out this
"Warning: Missing argument 11 for cash_payment(), called in
/.../wp-content/plugins/inkappointmentpro/ink-admin/apt-form.php
on line 66 and defined in
/.../wp-content/plugins/inkappointmentpro/ink-admin/appointments-form/getway/paypal-page.php
on line 26"
when submitting the form.
Here are the two files in question. Can someone please help? I'm not a programmer, just a guy who manages to fuddle his way through this stuff usually.
paypal-page.php
<?php
/**
* Paypal Transaction
* # gateway_sandbox
* */
function gateway_sandbox() {
if (isset($_POST['submit'])) {
$db_obj = new Apt_DB();
if (file_exists($db_obj->dir . "ink-admin/appointments-form/getway/paypal/paypal_sandbox.php")) {
include_once($db_obj->dir . "ink-admin/appointments-form/getway/paypal/paypal_sandbox.php");
}
}
}
/**
* Paypal Transaction
* # gateway_paypal
* */
function gateway_paypal() {
if (isset($_POST['submit'])) {
$db_obj = new Apt_DB();
if (file_exists($db_obj->dir . "ink-admin/appointments-form/getway/paypal/paypal_response.php")) {
include_once($db_obj->dir . "ink-admin/appointments-form/getway/paypal/paypal_response.php");
}
}
}
function cash_payment($sr_apt_id, $sr_apt_time, $sr_apt_date, $sr_apt_persion_name, $sr_apt_email, $sr_apt_phone, $sr_msg, $sr_apt_message, $sr_apt_ugs, $sr_apt_lawnarea, $sr_data_rand) {
global $wpdb;
$db_obj = new Apt_DB();
$apt_service = $db_obj->tbl_service;
$appointment_data = $db_obj->tbl_appointment_data;
$sql_srdata = $wpdb->get_row("SELECT * FROM $apt_service Where service_id='$sr_apt_id'", ARRAY_N);
$cr_code = get_option('apt_currency_code');
$price = $sql_srdata[2] . '&nbsp' . $cr_code . '&nbsp- Pay Cash Later';
$priceshow = $sql_srdata[2] . '' . $cr_code;
$apt_txn_booking_date = date("F j, Y, g:i A");
$apt = new AptService();
if (isset($_POST['submit'])) {
$sql_val = $wpdb->get_row("SELECT * FROM $appointment_data Where apt_data_rand='$sr_data_rand'");
if (!$sql_val) {
$apt->insert_data_frontend($sr_apt_id, $sr_apt_date, $sr_apt_persion_name, $sql_srdata[1], $sr_apt_time, $price, $sr_apt_email, $sr_apt_phone, $sr_msg, $sr_apt_message, $sr_apt_ugs, $sr_apt_lawnarea, $sr_data_rand, $apt_txn_booking_date, 'cash');
echo '<p>Your appointment request has be submitted successfully. We will email or phone you with confirmation.</br>Thank you for choosing Saskatoon ProLawn.</p>';
/**
* Send transaction notification to admin or client
*/
$transaction_details = '';
$personname = $sr_apt_persion_name;
$servicename = $sql_srdata[1];
$aptime = $sr_apt_time;
$aptdate = $sr_apt_date;
$aptmessage = $sr_apt_message;
$aptugs = $sr_apt_ugs;
$aptlawnarea =$sr_apt_lawnarea;
$aptemail = $sr_apt_email;
$url = site_url();
$adminurl = str_replace('http://', '', $url);
$transaction_details .= "Hello $personname,\r";
$transaction_details .= "\r";
$transaction_details .= "Your appointment request has been received, below are the details of your request. \r \r";
$transaction_details .= "Service Name: $servicename \r";
$transaction_details .= "Appointment Date: $aptdate\r";
$transaction_details .= "Appointment Time: $aptime\r";
$transaction_details .= "Contact Phone: $aptphone\r";
$transaction_details .= "Address: $aptmessage\r";
$transaction_details .= "Underground Sprinklers Present: $aptugs\r";
$transaction_details .= "Lawn Area to be Done: $aptlawnarea\r \r";
$transaction_details .= "Thanks for choosing Saskatoon ProLawn.\r";
$transaction_details .= "When I confirm the date and time, I will send another email or contact you at the phone number provided. Please add us \r \r";
$transaction_details .= "Warm Regards,\r";
$transaction_details .= "Shane\r \r";
$transaction_details .= "$adminurl\r";
$subject = __("Your Appointment Request Has Been Received", 'appointment');
$filecontent = $transaction_details;
$admin_email = get_option('admin_email');
$headers = 'From: ' . $admin_email . ' <' . $aptemail . '>' . "\r\n" . 'Reply-To: ' . $admin_email;
$header = 'From: ' . $aptemail . ' <' . $admin_email . '>' . "\r\n" . 'Reply-To: ' . $aptemail;
//mail($to_admin, $subject, $filecontent, $headers);
wp_mail($aptemail, $subject, $filecontent, $headers); //email to user
wp_mail($admin_email, $subject, $filecontent, $header); //email to admin
} //refresh value if end
} //submit data if end
}
//function end
apt-form.php
<?php
add_shortcode('ink-appointments-form', 'ink_appoitment');
function ink_appoitment() {
?>
<script>
jQuery.noConflict();
jQuery(function () {
jQuery("#aptcal").datepicker();
jQuery("#aptcal").datepicker("option", "minDate", 0);
});
</script>
<?php
$db_obj = new Apt_DB();
global $wpdb;
$cpt_true = false;
$apt_service = $db_obj->tbl_service;
$check_apt = isset($_POST['chk_apt']) ? $_POST['chk_apt'] : null;
$cpt_apt = isset($_POST['apt_cpt']) ? $_POST['apt_cpt'] : null;
if ($check_apt != $cpt_apt) {
$cpt_true = true;
}
$msg = '';
$captcha_details = '';
$is_captcha_on = get_option('cpt_enable');
if ($_SERVER["REQUEST_METHOD"] == "POST" && $is_captcha_on == 'on') {
$recaptcha = $_POST['g-recaptcha-response'];
if (!empty($recaptcha)) {
$secret = get_option('apt_recaptcha_private');
$secret = empty($secret) ? 'Google secret key' : $secret;
$captcha_data = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $_POST['g-recaptcha-response']);
$response = json_decode($captcha_data, TRUE);
if ($response['success']) {
$captcha_details = true;
} else {
$captcha_details = false;
$error = array_search("invalid-input-secret", $response['error-codes']);
if ($error == 0) {
$msg = "Please enter correct reCAPTCHA key.";
} else {
$msg = "Please re-enter your reCAPTCHA.";
}
}
} else {
$captcha_details = false;
$msg = "Please re-enter your reCAPTCHA.";
}
}
$blank_data = "";
if ((isset($_POST['submit']) && $is_captcha_on != 'on' && $cpt_true == false ) || (isset($_POST['submit']) && $captcha_details == true)) {
$_POST['time'];
if (($_POST['time'] == 'notavi') || ($_POST['service_select'] == 'notavi')) {
echo "<p>Please Insert All data.</p>";
$blank_data = true;
} else {
$blank_data = false;
echo $badUrl = (isset($_POST['sr_price'])) ? $_POST['sr_price'] : null;
if (get_option('apt_paypal') == "sandbox") {
gateway_sandbox();
} elseif (get_option('apt_paypal') == "paypal") {
gateway_paypal();
} elseif (get_option('apt_paypal') == "cash") {
$datechange = $_POST['aptcal'];
$dateformat = explode('/', $datechange);
$newaptdate = $dateformat[1] . '/' . $dateformat[0] . '/' . $dateformat[2];
cash_payment($_POST['service_select'], $_POST['time'], $newaptdate, $_POST['fname'], $_POST['aptemail'], $_POST['aptphone'], $_POST['aptmessage'], $_POST['aptugs'], $_POST['aptlawnarea'], $_POST['random']);
}
}
}
if (isset($_GET['paypal-trans'])) {
ink_apt_trans_display();
} else {
$ruri = $_SERVER['REQUEST_URI'];
$sname = $_SERVER['SERVER_NAME'];
$fullpath = 'http://' . $sname . $ruri;
update_option('return_apt_url', $fullpath);
$br = new AptService();
$iechk = $br->ink_browser();
if ((!isset($_POST['submit'])) || ($check_apt != $cpt_apt) || ($captcha_details == false) || ($blank_data == true)) {
?>
<div class="ink-container">
<div class="inkappointment_wrapper">
<div class="inkappointment_form_top">
</div>
<div class="inkappointment_form_wrapper">
<form method="post" action="" id="ink-form" name="ink-form" class="ink-form" >
<header id="ink-header" class="ink-info">
</header>
<ul class="inkappform">
<li class="textheading"><h2><span class="msg_text"><?php echo get_option('apt_form_head'); ?></span></h2></li>
<li class="textfname"><input type="text" name="fname" id="fname" class="inktext inklarge inkrequired" placeholder="Name" maxlength="100" />
<label id="apt_error"> </label>
</li>
<li class="textaptemail"><input type="email" name="aptemail" id="aptemail" class="inktext inklarge inkrequired" placeholder="Email" maxlength="100" /></li>
<li class="textaptphone"><input type="text" name="aptphone" id="aptphone" class="inktext inklarge" placeholder="Contact Number" maxlength="12” /></li>
<li class="textfixdate"><span class="fix_date"><?php echo get_option('apt_fix_date'); ?></span></li>
<li class="select_item"><select id="service_select" name="service_select" class="inktext inklarge inkrequired" >
<option value="noavi">Select Service</option>
<?php
$showts = $wpdb->get_results("SELECT * FROM $apt_service ", ARRAY_A);
foreach ($showts as $timerow) {
?>
<option value="<?php echo $timerow['service_id']; ?>"><?php echo $timerow['service_name']; ?></option>
<?php } ?> </select></li>
<li class="textaptcal"><input type="text" name="aptcal" id="aptcal" class="dateField inktext inklarge" placeholder="Select Date" /></li>
<li class="select_item"><select id="time" name="time" class="inktext inklarge inkrequired">
<option value="notavi">Select Time</option> </select></li>
<li class="textfixdate"><span class="fix_date">Do you have underground Sprinklers?</span></li>
<li class="textfixdate"><span class="fix_date"><input type="radio" name="aptugs" id="aptugs" value="yes" checked>Yes <input type="radio" name="aptugs" id="aptugs"” value="no">No</span></li>
<li class="textfixdate"><span class="fix_date">Area Required</span></li>
<li class="textfixdate"><span class="fix_date"><input type="radio" name="aptlawnarea" id="aptlawnarea" value="frontback" checked>Front+Back <br> <input type="radio" name="aptlawnarea" id="aptlawnarea" value="front">Front Only <br> <input type="radio" name="aptlawnarea" id="aptlawnarea" value=“back”>Back Only</span></li>
<li class="textfixdate"><span class="fix_date"><?php echo get_option('apt_custom_msg'); ?></span></li>
<li class="textaptmessage"><textarea name="aptmessage" id="aptmessage" class="inktext inklarge inkrequired" maxlength="255" rows="3" cols="50" placeholder="Address (required)" ></textarea></li>
<?php if ($is_captcha_on === 'on') { ?><li>
<div class="g-recaptcha-div"><div class="g-recaptcha" data-sitekey="<?php
if (get_option('apt_recaptcha_public')) {
echo get_option('apt_recaptcha_public');
} else {
echo 'Google Public Key';
}
?>"></div>
</div>
<span class='msg'><?php echo $msg; ?></span>
</li>
<?php } ?>
<li class="submit_bg">
<input type="hidden" name="random" id="random" value="<?php echo rand(); ?>"/>
<input type="submit" name="submit" id="submit" class='ink-submit inkrequired' value="Book Appointment"/> </li>
</ul>
</form>
</div>
<div class="inkappointment_form_bottom">
</div>
</div>
</div>
<?php
} //submit not set
}
}
you have missing one parameter for the following function: cash_payment()
Function Definition having 11 parameters:
function cash_payment($sr_apt_id, $sr_apt_time, $sr_apt_date, $sr_apt_persion_name, $sr_apt_email, $sr_apt_phone, $sr_msg, $sr_apt_message, $sr_apt_ugs, $sr_apt_lawnarea, $sr_data_rand) {}
Function calling 10 parameters:
cash_payment($_POST['service_select'], $_POST['time'], $newaptdate, $_POST['fname'], $_POST['aptemail'], $_POST['aptphone'], $_POST['aptmessage'], $_POST['aptugs'], $_POST['aptlawnarea'], $_POST['random']);
If you don't have any 11th parameters of any values against parameters than pass the empty string but no of parameters in definition is always equal to no of parameters of calling a function.
I think this error comes due to missing argument in cash_payment function, please check all fields of this function.
cash_payment($_POST['service_select'], $_POST['time'], $newaptdate, $_POST['fname'], $_POST['aptemail'], $_POST['aptphone'], $_POST['aptmessage'], $_POST['aptugs'], $_POST['aptlawnarea'], $_POST['random']);
}
Please try to echo all fields and check if you found any of null value.

Mysqli and PDO combined with Javascript and Ajax... possible?

Simple question from a noob programer. Thinking of several different styles and features to a project i have for a social website. question is this...
can you combine mysqli and PDO style programs?
having difficulty inserting data into database with php, ajax and javascript modules. it says "success" but doesnt insert the info with mysqli. i HAVE used PDO successfully. but my code looks right... it has the same syntax as the tutorial i am looking at with mysqli. this is the code...
<!-- ********************************** -->
<!-- *********** signup.php *********** -->
<!-- ********************************** -->
<?php
session_start();
// If user is logged in, header them away
if(isset($_SESSION["username"])){
header("location: message.php?msg=NO to that weenis");
exit();
}
?><?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
include_once("php_includes/db_conx.php");
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uname_check = mysqli_num_rows($query);
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
?><?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $e == "" || $p == "" || $g == "" || $c == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
$cryptpass = crypt($p);
include_once ("php_includes/randStrGen.php");
$p_hash = randStrGen(20)."$cryptpass".randStrGen(20);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (username, email, password, gender, country, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p_hash','$g','$c','$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Establish their row in the useroptions table
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
// Email the user their activation link
$to = "$e";
$from = "auto_responder#yoursitename.com";
$subject = 'yoursitename Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>yoursitename Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;"><img src="http://www.yoursitename.com/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;">yoursitename Account Activation</div><div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* E-mail Address: <b>'.$e.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="css/style.css">
<style type="text/css">
</style>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[' "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else if( _("terms").style.display == "none"){
status.innerHTML = "Please view the terms of use";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g);
}
}
function openTerms(){
_("terms").style.display = "block";
emptyElement("status");
}
/* function addEvents(){
_("elemID").addEventListener("click", func, false);
}
window.onload = addEvents; */
</script>
</head>
<body>
<?php include_once("includes/template_header.php"); ?>
<div id="pageMiddle">
<h3>Sign Up Here</h3>
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Confirm Password:</div>
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Gender:</div>
<select id="gender" onfocus="emptyElement('status')">
<option value=""></option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
<div>Country:</div>
<select id="country" onfocus="emptyElement('status')">
<?php include_once("includes/template_country_list.php"); ?>
</select>
<div>
<a href="#" onclick="return false" onmousedown="openTerms()">
View the Terms Of Use
</a>
</div>
<div id="terms" style="display:none;">
<h3>Web Intersect Terms Of Use</h3>
<p>1. Play nice here.</p>
<p>2. Take a bath before you visit.</p>
<p>3. Brush your teeth before bed.</p>
</div>
<br /><br />
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
</div>
<?php include_once("includes/template_bottom.php"); ?>
</body>
</html>
<!-- ********************************** -->
<!-- *********** activation.php ******* -->
<!-- ********************************** -->
<?php
if (isset($_GET['id']) && isset($_GET['u']) && isset($_GET['e']) && isset($_GET['p'])) {
// Connect to database and sanitize incoming $_GET variables
include_once("php_includes/db_conx.php");
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
$e = mysqli_real_escape_string($db_conx, $_GET['e']);
$p = mysqli_real_escape_string($db_conx, $_GET['p']);
// Evaluate the lengths of the incoming $_GET variable
if($id == "" || strlen($u) < 3 || strlen($e) < 5 ){
// Log this issue into a text file and email details to yourself
header("location: message.php?msg=activation_string_length_issues");
exit();
}
// Check their credentials against the database
$sql = "SELECT * FROM users WHERE id='$id' AND username='$u' AND email='$e' AND password='$p' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
// Evaluate for a match in the system (0 = no match, 1 = match)
if($numrows == 0){
// Log this potential hack attempt to text file and email details to yourself
header("location: message.php?msg=Your credentials are not matching anything in our system");
exit();
}
// Match was found, you can activate them
$sql = "UPDATE users SET activated='1' WHERE id='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
// Optional double check to see if activated in fact now = 1
$sql = "SELECT * FROM users WHERE id='$id' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
// Evaluate the double check
if($numrows == 0){
// Log this issue of no switch of activation field to 1
header("location: message.php?msg=activation_failure");
exit();
} else if($numrows == 1) {
// Great everything went fine with activation!
header("location: message.php?msg=activation_success");
exit();
}
else {
// Log this issue of missing initial $_GET variables
header("location: message.php?msg=missing_GET_variables");
exit();
}}
?>
<!-- ********************************** -->
<!-- *********** message.php ********** -->
<!-- ********************************** -->
<?php
$message = "";
$msg = preg_replace('#[^a-z 0-9.:_()]#i', '', $_GET['msg']);
if($msg == "activation_failure"){
$message = '<h2>Activation Error</h2> Sorry there seems to have been an issue activating your account at this time. We have already notified ourselves of this issue and we will contact you via email when we have identified the issue.';
} else if($msg == "activation_success"){
$message = '<h2>Activation Success</h2> Your account is now activated. Click here to log in';
} else {
$message = $msg;
}
?>
<div><?php echo $message; ?></div>
<!-- ********************************** -->
<!-- ********* randStrGen.php ********* -->
<!-- ********************************** -->
<?php
function randStrGen($len){
$result = "";
$chars = "abcdefghijklmnopqrstuvwxyz0123456789$$$$$$$1111111";
$charArray = str_split($chars);
for($i = 0; $i < $len; $i++){
$randItem = array_rand($charArray);
$result .= "".$charArray[$randItem];
}
return $result;
}
?>
is it possible to rewrite so different modules interact?

Ajax/PHP contact form not able to send mail

The funny thing is it did work for one evening. I contacted my host, and they are saying there's no reason it should not be working. I have also attempted to test it in Firebug, but it seemed to be sending. And I specifically put the email address (hosted in my domain) on my email safe list, so that is not the culprit either.
Would anyone here take a look at it for me? I'd be so grateful.
In the header I have:
<script type="text/javascript">
$(document).ready(function () {
var options = {
target: '#alert'
};
$('#contactForm').ajaxForm(options);
});
$.fn.clearForm = function () {
return this.each(function () {
var type = this.type,
tag = this.tagName.toLowerCase();
if (tag == 'form')
return $(':input', this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
</script>
Here is the actual form:
<form id="contactForm" method="post" action="sendmail.php">
<fieldset>
<p>Email Me</p>
<div id="fieldset_container">
<label for="name">Your Name:</label>
<input type="text" name="name" id="name" /><br /><br />
<label for="email">Email:</label>
<input type="text" name="email" id="email" /><br /><br />
<span style="display:none;">
<label for="last">Honeypot:</label>
<input type="text" name="last" value="" id="last" />
</span><br /><br />
<label for="message">Comments & Inquiries:</label>
<textarea name="message" id="message" cols="" rows=""></textarea><br/>
</div>
<div id="submit_button">
<input type="submit" name="submit" id="submit" value="Send It" />
</div>
</fieldset>
</form>
<div class="message"><div id="alert"></div></div>
Here is the code from my validating page, sendmail.php:
<?php
// Who you want to recieve the emails from the form. (Hint: generally you.)
$sendto = 'my#emailaddress.com';
// The subject you'll see in your inbox
$subject = 'SH Contact Form';
// Message for the user when he/she doesn't fill in the form correctly.
$errormessage = 'There seems to have been a problem. May I suggest...';
// Message for the user when he/she fills in the form correctly.
$thanks = "Thanks for the email!";
// Message for the bot when it fills in in at all.
$honeypot = "You filled in the honeypot! If you're human, try again!";
// Various messages displayed when the fields are empty.
$emptyname = 'Entering your name?';
$emptyemail = 'Entering your email address?';
$emptymessage = 'Entering a message?';
// Various messages displayed when the fields are incorrectly formatted.
$alertname = 'Entering your name using only the standard alphabet?';
$alertemail = 'Entering your email in this format: <i>name#example.com</i>?';
$alertmessage = "Making sure you aren't using any parenthesis or other escaping characters in the message? Most URLS are fine though!";
//Setting used variables.
$alert = '';
$pass = 0;
// Sanitizing the data, kind of done via error messages first. Twice is better! ;-)
function clean_var($variable) {
$variable = strip_tags(stripslashes(trim(rtrim($variable))));
return $variable;
}
//The first if for honeypot.
if ( empty($_REQUEST['last']) ) {
// A bunch of if's for all the fields and the error messages.
if ( empty($_REQUEST['name']) ) {
$pass = 1;
$alert .= "<li>" . $emptyname . "</li>";
} elseif ( ereg( "[][{}()*+?.\\^$|]", $_REQUEST['name'] ) ) {
$pass = 1;
$alert .= "<li>" . $alertname . "</li>";
}
if ( empty($_REQUEST['email']) ) {
$pass = 1;
$alert .= "<li>" . $emptyemail . "</li>";
} elseif ( !eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*#[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $_REQUEST['email']) ) {
$pass = 1;
$alert .= "<li>" . $alertemail . "</li>";
}
if ( empty($_REQUEST['message']) ) {
$pass = 1;
$alert .= "<li>" . $emptymessage . "</li>";
} elseif ( ereg( "[][{}()*+?\\^$|]", $_REQUEST['message'] ) ) {
$pass = 1;
$alert .= "<li>" . $alertmessage . "</li>";
}
//If the user err'd, print the error messages.
if ( $pass==1 ) {
//This first line is for ajax/javascript, comment it or delete it if this isn't your cup o' tea.
echo "<script>$(\".message\").hide(\"slow\").show(\"slow\"); </script>";
echo "<b>" . $errormessage . "</b>";
echo "<ul>";
echo $alert;
echo "</ul>";
// If the user didn't err and there is in fact a message, time to email it.
} elseif (isset($_REQUEST['message'])) {
//Construct the message.
$message = "From: " . clean_var($_REQUEST['name']) . "\n";
$message .= "Email: " . clean_var($_REQUEST['email']) . "\n";
$message .= "Message: \n" . clean_var($_REQUEST['message']);
$header = 'From:'. clean_var($_REQUEST['email']);
//Mail the message - for production
mail($sendto, $subject, $message, $header, "-fstephanie#stephaniehenderson.com");
//This is for javascript,
echo "<script>$(\".message\").hide(\"slow\").show(\"slow\").animate({opacity: 1.0}, 4000).hide(\"slow\"); $(':input').clearForm() </script>";
echo $thanks;
die();
//Echo the email message - for development
echo "<br/><br/>" . $message;
}
//If honeypot is filled, trigger the message that bot likely won't see.
} else {
echo "<script>$(\".message\").hide(\"slow\").show(\"slow\"); </script>";
echo $honeypot;
}
?>
If the message is echoing then it's not a problem with your javascript or html. I would suggest making a fresh PHP file with only the 1 line that attempts to send mail:
mail('youremailaddress#example.com', 'My Subject', 'This is a message');
Hardcode everything. If that works, then you know that it's probably not a problem with your host, and you need to examine that line and the variables to are passing to mail()

Categories