Jump to content

Data is not inserted to database after submit


Go to solution Solved by osherdo,

Recommended Posts

Hello everyone.

 

It seems like my code is not working properly. 

 

i have tried both mysqli and PDO to insert data into database,but it only takes me back to same page again,without doing nothing in the database (been checking this a few times to be sure).

 

both php and html code are on the same page.

 

Could anyone point me to the missing link in my code?

 

here's my code (HTML & PHP) :

<form action="" id="SignUpForm" autocomplete="on" style="display:none" method="post"> <!-- Form is Hidden until the user is clicking the "Sign Up" button. -->
<input type="hidden" name="Language" value="English">
Fill up the following fields:<br><br>
First name:<input type="text" name="fname" required><br><br>
Last name: <input type="text" name="lname" required><br><br>
Age: <input type="number" name="UserAge" min="1" max="120" required><br><br>
Gender: <input type="radio" name="Gender" value="male">Male<br>
<input type="radio" name="Gender" value="Female">Female<br>
E-mail Address: <input type="email" name="email" autocomplete="off" required><br><br>
Pick your new password: <input type="password"  maxlength=”40” name="Password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"> Add password strength checker here.<br><br> <!-- Uses regular expression. -->
Confirm Password:  <input type="password" maxlength=”40” name="ConfirmPassword" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"><br><br> <!-- A better way is to use onblur to check user's type match. -->
 <hr>
 <script>
 (function(){
        $("#submit").click(function(){
        $(".error").hide(); //Bind an event handler to the "error" JavaScript event.
        var hasError = false;
        var passwordVal = $("#Password").val();
        var checkVal = $("#ConfirmPassword").val();
        if (passwordVal == '') {
            $("#Password").after('<span class="error">Please enter a password.</span>');
            hasError = true;
        } else if (checkVal == '') {
            $("#ConfirmPassword").after('<span class="error">Please re-enter your password.</span>');
            hasError = true;
        } else if (passwordVal != checkVal ) {
            $("#ConfirmPassword").after('<span class="error">Passwords do not match.</span>');
            hasError = true;
        }
        if(hasError == true) {return false;}
    });
});
 </script>
 
<script>
//The validationMessage property of a DOM node contains the message the browser displays to the user when a node's validity is checked and fails.
document.getElementById("name").validationMessage;
document.getElementById("lname").validationMessage;
document.getElementById("UserAge").validationMessage;
document.getElementById("Gender").validationMessage;
document.getElementById("email").validationMessage;
document.getElementById("Password").validationMessage;
document.getElementById("ConfirmPassword").validationMessage;
</script>

Now let's go through your prefered food. Check the appropriate boxed beyond.<br><br>
This will help us to better understand your food discipline:<br>

<p style="text-align:center"><b> Meat And Poultry:</b></p>
<div id="MeatCheckBox">
<input type="checkbox" name="FoodTypes[]" value="Hamburger">Hamburger<br>
<input type="checkbox" name="FoodTypes[]" value="Steak">Steak<br>
<input type="checkbox" name="FoodTypes[]" value="GroundBeef">Ground Beef<br>
<input type="checkbox" name="FoodTypes[]" value="Bacon">Bacon<br>
<input type="checkbox" name="FoodTypes[]" value="Beef">Beef<br>
<input type="checkbox" name="FoodTypes[]" value="Salami">Salami<br>
<input type="checkbox" name="FoodTypes[]" value="Chicken">Chicken (In all its forms)<br>
<input type="checkbox" name="FoodTypes[]" value="NoMeat">I don't eat meat at all (Vegeterian/Vegan)<br>

</div>
 <p style="text-align:center"><b> Fish And Seafood:</b></p>
 <div id="FishAndSeaFood">
 <input type="checkbox" name="FoodTypes[]" value="Fish">Fish<br>
 <input type="checkbox" name="FoodTypes[]" value="Sushi">Sushi<br>
  <input type="checkbox" name="FoodTypes[]" value="CannedFish">Canned Fish<br>
  <input type="checkbox" name="FoodTypes[]" value="Oysters">Seafood<br>
    <input type="checkbox" name="FoodTypes[]" value="SmokedSalmon">Smoked Salmon<br>
  </div>
 
 <div id="Vegetables">
 <p style="text-align:center"><b> Do you eat vegtables?</b></p><br>
 <input type="radio" name="YesOrNo" value="Yes">Yes <!-- Give both options the same name,Because they are related. -->
<input type="radio" name="YesOrNo" value="No">No<br>
 </div>
 <hr>
 

<p>Do you workout as part of your lifestyle?</p><br>
<input type="radio" name='workout_options' value='valuable' data-id="DoWorkout" class="workout_options" /> I do workout occasionally
<input type="radio" name='workout_options' value='valuable' data-id="DoNotWorkout" class="workout_options" /> I am not working out<br><br><br>
<section>
    <div id=DoWorkout class="workout_options"><p>We see you're not having any exercise at the moment.<br><br>Did you know that doing some kind of activity like running or cardio 3 times a week improve your life quality?<br><br>We'll help you go straight from zero to hero!</p></div>
    <div id=DoNotWorkout class="workout_options">What type of workout you're working on at the moment? Please choose from the options beyond:<br><br><br>
    
    <input type="checkbox" name="Cardio" value="Cardio" data-id="Cardio"/>Cardio/Aerobics<br><br> 
    <input type="checkbox" name=" Weight_Lifting" value=" Weight_Lifting" data-id="Weight_Lifting"/>Weight Lifting/ Anaerobics</div><br>
</section>

<input type="submit" value="Sign Up!" id="submit">

</div>
</form>

PHP/PDO:

<?php
// connnecting to MYSQL with PDO.

// Connection data (server_address, database, username, password)
$hostdb = 'localhost';
$namedb = 'caf_users';
$userdb = 'root';
$passdb = 'mypassword';

if (isset($_POST['SignUpButton'])) {

$yesOrNo=$_POST["YesOrNo"];
$firstName=$_POST["fname"];
$lastName=$_POST["lname"];
$userGender=$_POST["Gender"];
$emailAddress=$_POST["email"];
//check if user entered the exact password twice.
if ($_POST["password"] === $_POST["confirm_password"]) {
	$password=$_POST["password"];
	$hash = password_hash($passwod, PASSWORD_DEFAULT);}
	// The first parameter is the password string that needs to be hashed,
	//and the second parameter specifies the algorithm that should be used for generating the hash.
	//encrypted by bcrypt algorithm.
	else {
		echo "Passwords are mismatched. Please try again.";
	};
	$userAge=$_POST["UserAge"];
// Display message if successfully connect, otherwise retains and outputs the potential error
try {
	$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb); //Initiate connection witht the PDO object instance.
	$conn->exec("SET CHARACTER SET utf8");  // Sets encoding UTF-8
	echo 'Connected to database';

	// Define an insert query
	$sql = "INSERT INTO `users` ('Workout','first_name','last_name','gender','Email_Address','Password','User_Age')
	VALUES
	($YesOrno,$fname,$lname,$Gender,$email,$password,$UserAge)";
	$count = $conn->exec($sql);

	$conn = null;        // Disconnect
	if($count !== false) echo 'Number of rows added: '. $count;
}
catch(PDOException $e) {
	echo $e->getMessage();
}
}
	?>

Thank you in advance,

 

Osher.

your form does not have a form element with the name SignUpButton, so your php code if (isset($_POST['SignUpButton'])) { will never be true.

 

it is recommend that you detect a form field that will always be present in the submitted form data (submit buttons cannot be guaranteed to be present, if you use the enter-key to submit the form (IE and Opera browsers) or use javascript to submit the form.) either test for a non-disabled text/password/textarea field or add a hidden field.

  • Like 1

Everything needs to match up, from the form element names for your $_POST array to the variable names you declare and assign to that $_POST['name'].


 


You declare variables of $lastname, $firstname and then use $lname and $fname to put them in the database. Check everything and echo the values to the screen before you try to insert them into the database to make sure they all match up.


Sorry, here's a better one:

<html> 
<head>
<meta charset="UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script> <!-- Load Jquery -->

<script>
$(document).ready(function(){ //Specify a function to execute when the DOM is fully loaded.
  $("button").click(function(){ // הפעלת פקודה על הכפתור.
    $("#SignUpButton").remove(); // Remove the SignUpButton onclick.
  });
});
</script>
<!-- below is the tag that allows reading the css settings from an external .css file. -->
<link rel="stylesheet" type="text/css" href="CSSFILE.css">
</head>
<title> Welcome to Click-And-Fit website.Soon you'll be in better shape!</title>
<body>

<img src="Demo_Photo.jpg" class="Demo_Photo" alt="CAF Demo Image" height=350 width="300">

<img src="Click_and_Fit!.jpg" class="Logo" alt="Click And Fit logo" height="200" width="200">

<p style="text-align:center">Welcome to Click-And-Fit!<br><br>Would you like to make a change in your life?
<br><br><FONT COLOR="#551A8B" ><b>Click-And-Fit</b></FONT><br><br>
Let's make this change happen by sign up to our website with the following form beyond.<br><br>
You need to provide some of your daily lifestyle habits. (e.g.:Like if you're a smoker)</p> <br><br><br>


<div class="container">
    <a href="" class="button"><strong>Already have an account?</strong></a>
</div>

<div align="center">
<form action="" id="SignUpForm" autocomplete="on" style="display:none" method="post"> <!-- Form is Hidden until the user is clicking the "Sign Up" button. -->
<input type="hidden" name="Language" value="English">
Fill up the following fields:<br><br>
First name:<input type="text" name="fname" required><br><br>
Last name: <input type="text" name="lname" required><br><br>
Age: <input type="number" name="UserAge" min="1" max="120" required><br><br>
Gender: <input type="radio" name="Gender" value="male">Male<br>
<input type="radio" name="Gender" value="Female">Female<br>
E-mail Address: <input type="email" name="email" autocomplete="off" required><br><br>
Pick your new password: <input type="password"  maxlength=”40” name="Password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"> Add password strength checker here.<br><br> <!-- Uses regular expression. -->
Confirm Password:  <input type="password" maxlength=”40” name="ConfirmPassword" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"><br><br> <!-- A better way is to use onblur to check user's type match. -->
 <hr>
 <script>
 (function(){
        $("#submit").click(function(){
        $(".error").hide(); //Bind an event handler to the "error" JavaScript event.
        var hasError = false;
        var passwordVal = $("#Password").val();
        var checkVal = $("#ConfirmPassword").val();
        if (passwordVal == '') {
            $("#Password").after('<span class="error">Please enter a password.</span>');
            hasError = true;
        } else if (checkVal == '') {
            $("#ConfirmPassword").after('<span class="error">Please re-enter your password.</span>');
            hasError = true;
        } else if (passwordVal != checkVal ) {
            $("#ConfirmPassword").after('<span class="error">Passwords do not match.</span>');
            hasError = true;
        }
        if(hasError == true) {return false;}
    });
});
 </script>
 
<script>
//The validationMessage property of a DOM node contains the message the browser displays to the user when a node's validity is checked and fails.
document.getElementById("name").validationMessage;
document.getElementById("lname").validationMessage;
document.getElementById("UserAge").validationMessage;
document.getElementById("Gender").validationMessage;
document.getElementById("email").validationMessage;
document.getElementById("Password").validationMessage;
document.getElementById("ConfirmPassword").validationMessage;
</script>

Now let's go through your prefered food. Check the appropriate boxed beyond.<br><br>
This will help us to better understand your food discipline:<br>

<p style="text-align:center"><b> Meat And Poultry:</b></p>
<div id="MeatCheckBox">
<input type="checkbox" name="FoodTypes[]" value="Hamburger">Hamburger<br>
<input type="checkbox" name="FoodTypes[]" value="Steak">Steak<br>
<input type="checkbox" name="FoodTypes[]" value="GroundBeef">Ground Beef<br>
<input type="checkbox" name="FoodTypes[]" value="Bacon">Bacon<br>
<input type="checkbox" name="FoodTypes[]" value="Beef">Beef<br>
<input type="checkbox" name="FoodTypes[]" value="Salami">Salami<br>
<input type="checkbox" name="FoodTypes[]" value="Chicken">Chicken (In all its forms)<br>
<input type="checkbox" name="FoodTypes[]" value="NoMeat">I don't eat meat at all (Vegeterian/Vegan)<br>

</div>
 <p style="text-align:center"><b> Fish And Seafood:</b></p>
 <div id="FishAndSeaFood">
 <input type="checkbox" name="FoodTypes[]" value="Fish">Fish<br>
 <input type="checkbox" name="FoodTypes[]" value="Sushi">Sushi<br>
  <input type="checkbox" name="FoodTypes[]" value="CannedFish">Canned Fish<br>
  <input type="checkbox" name="FoodTypes[]" value="Oysters">Seafood<br>
    <input type="checkbox" name="FoodTypes[]" value="SmokedSalmon">Smoked Salmon<br>
  </div>
 
 <div id="Vegetables">
 <p style="text-align:center"><b> Do you eat vegtables?</b></p><br>
 <input type="radio" name="YesOrNo" value="Yes">Yes <!-- Give both options the same name,Because they are related. -->
<input type="radio" name="YesOrNo" value="No">No<br>
 </div>
 <hr>
 

<p>Do you workout as part of your lifestyle?</p><br>
<input type="radio" name='workout_options' value='valuable' data-id="DoWorkout" class="workout_options" /> I do workout occasionally
<input type="radio" name='workout_options' value='valuable' data-id="DoNotWorkout" class="workout_options" /> I am not working out<br><br><br>
<section>
    <div id=DoWorkout class="workout_options"><p>We see you're not having any exercise at the moment.<br><br>Did you know that doing some kind of activity like running or cardio 3 times a week improve your life quality?<br><br>We'll help you go straight from zero to hero!</p></div>
    <div id=DoNotWorkout class="workout_options">What type of workout you're working on at the moment? Please choose from the options beyond:<br><br><br>
    
    <input type="checkbox" name="Cardio" value="Cardio" data-id="Cardio"/>Cardio/Aerobics<br><br> 
    <input type="checkbox" name=" Weight_Lifting" value=" Weight_Lifting" data-id="Weight_Lifting"/>Weight Lifting/ Anaerobics</div><br>
</section>

<input type="submit" value="Sign Up!" id="submit">

</div>
</form>

<p style="text-align:center;"><a href="#" id="Learn_More"> Learn more about Click-And-Fit</a></p>

<div id="clickme">
<p align="center"><button type="submit" id="SignUpButton" name="SignUpButton" class="SignUpButton"><p style="font-size:30px;">Sign Up</p><br><span style="font-family:Consolas;font-size:20px; "> (I am ready for the challenge!)</span></button></p></div>


<!-- Show form on click. -->
<script> 
$( "#clickme" ).click(function() {
	$( "#SignUpForm" ).show( "slow", function() {
		// Animation complete.
	});
});
</script> <!-- script for the exercise options -->
<script type="text/javascript">
$(':radio').change(function (event) { // when any radio button changes,
    var id = $(this).data('id'); // get the id from data-id
    $('#' + id) // find the div with that id.
    .addClass('workout_options') // give it the class
    .siblings().removeClass('workout_options'); // and remove the class from all it’s siblings
    // siblings are nodes before and after with the same parent.
});
</script>

</body>
</html>

<?php
// connnecting to MYSQL with PDO.

// Connection data (server_address, database, username, password)
$hostdb = 'localhost';
$namedb = 'caf_users';
$userdb = 'root';
$passdb = 'mypassword';

if (isset($_POST['SignUpButton'])) {

$YesOrNo=$_POST["YesOrNo"];
$fname=$_POST["fname"];
$lname=$_POST["lname"];
$Gender=$_POST["Gender"];
$email=$_POST["email"];
//check if user entered the exact password twice.
if ($_POST["password"] === $_POST["confirm_password"]) {
	$password=$_POST["password"];
	$hash = password_hash($passwod, PASSWORD_DEFAULT);}
	// The first parameter is the password string that needs to be hashed,
	//and the second parameter specifies the algorithm that should be used for generating the hash.
	//encrypted by bcrypt algorithm.
	else {
		echo "Passwords are mismatched. Please try again.";
	};
	$UserAge=$_POST["UserAge"];
// Display message if successfully connect, otherwise retains and outputs the potential error
try {
	$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb); //Initiate connection witht the PDO object instance.
	$conn->exec("SET CHARACTER SET utf8");  // Sets encoding UTF-8
	echo 'Connected to database';

	// Define an insert query
	$sql = "INSERT INTO `users` ('Workout','first_name','last_name','gender','Email_Address','Password','User_Age')
	VALUES
	($YesOrno,$fname,$lname,$Gender,$email,$password,$UserAge)";
	$count = $conn->exec($sql);

	$conn = null;        // Disconnect
	if($count !== false) echo 'Number of rows added: '. $count;
}
catch(PDOException $e) {
	echo $e->getMessage();
}
}
	?>

Hello again people.

 

I have made some changes to my code to make it work, and also applied your advices to my code.

 

It works really great and all, and no error code is being generated, but unfortunately it is still not getting my query inserted into the database.

 

the only message I get is the echo I have placed to check whether database is connected or not, and it says it is connected.

 

Please consider the updated code and tell me what's wrong now?

 

Thanks.

<html> 
<head>
<meta charset="UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script> <!-- Load Jquery -->

<script>
$(document).ready(function(){ //Specify a function to execute when the DOM is fully loaded.
  $("button").click(function(){ // הפעלת פקודה על הכפתור.
    $("#SignUpButton").remove(); // Remove the SignUpButton onclick.
  });
});
</script>
<!-- below is the tag that allows reading the css settings from an external .css file. -->
<link rel="stylesheet" type="text/css" href="CSSFILE.css">
</head>
<title> Welcome to Click-And-Fit website.Soon you'll be in better shape!</title>
<body>

<img src="Demo_Photo.jpg" class="Demo_Photo" alt="CAF Demo Image" height=350 width="300">

<img src="Click_and_Fit!.jpg" class="Logo" alt="Click And Fit logo" height="200" width="200">

<p style="text-align:center">Welcome to Click-And-Fit!<br><br>Would you like to make a change in your life?
<br><br><FONT COLOR="#551A8B" ><b>Click-And-Fit</b></FONT><br><br>
Let's make this change happen by sign up to our website with the following form beyond.<br><br>
You need to provide some of your daily lifestyle habits. (e.g.:Like if you're a smoker)</p> <br><br><br>


<div class="container">
    <a href="" class="button"><strong>Already have an account?</strong></a>
</div>

<div align="center">
<form action="" id="SignUpForm" autocomplete="on" style="display:none" method="post"> <!-- Form is Hidden until the user is clicking the "Sign Up" button. -->
<input type="hidden" name="Language" value="English">
Fill up the following fields:<br><br>
First name:<input type="text" name="fname" required><br><br>
Last name: <input type="text" name="lname" required><br><br>
Age: <input type="number" name="UserAge" min="1" max="120" required><br><br>
Gender: <input type="radio" name="Gender" value="male">Male<br>
<input type="radio" name="Gender" value="Female">Female<br>
E-mail Address: <input type="email" name="email" autocomplete="off" required><br><br>
Pick your new password: <input type="password"  maxlength=”40” name="Password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"> Add password strength checker here.<br><br> <!-- Uses regular expression. -->
Confirm Password:  <input type="password" maxlength=”40” name="ConfirmPassword" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"><br><br> <!-- A better way is to use onblur to check user's type match. -->
 <hr>
 <script>
 (function(){
        $("#submit").click(function(){
        $(".error").hide(); //Bind an event handler to the "error" JavaScript event.
        var hasError = false;
        var passwordVal = $("#Password").val();
        var checkVal = $("#ConfirmPassword").val();
        if (passwordVal == '') {
            $("#Password").after('<span class="error">Please enter a password.</span>');
            hasError = true;
        } else if (checkVal == '') {
            $("#ConfirmPassword").after('<span class="error">Please re-enter your password.</span>');
            hasError = true;
        } else if (passwordVal != checkVal ) {
            $("#ConfirmPassword").after('<span class="error">Passwords do not match.</span>');
            hasError = true;
        }
        if(hasError == true) {return false;}
    });
});
 </script>
 
<script>
//The validationMessage property of a DOM node contains the message the browser displays to the user when a node's validity is checked and fails.
document.getElementById("name").validationMessage;
document.getElementById("lname").validationMessage;
document.getElementById("UserAge").validationMessage;
document.getElementById("Gender").validationMessage;
document.getElementById("email").validationMessage;
document.getElementById("Password").validationMessage;
document.getElementById("ConfirmPassword").validationMessage;
</script>

Now let's go through your prefered food. Check the appropriate boxed beyond.<br><br>
This will help us to better understand your food discipline:<br>

<p style="text-align:center"><b> Meat And Poultry:</b></p>
<div id="MeatCheckBox">
<input type="checkbox" name="FoodTypes[]" value="Hamburger">Hamburger<br>
<input type="checkbox" name="FoodTypes[]" value="Steak">Steak<br>
<input type="checkbox" name="FoodTypes[]" value="GroundBeef">Ground Beef<br>
<input type="checkbox" name="FoodTypes[]" value="Bacon">Bacon<br>
<input type="checkbox" name="FoodTypes[]" value="Beef">Beef<br>
<input type="checkbox" name="FoodTypes[]" value="Salami">Salami<br>
<input type="checkbox" name="FoodTypes[]" value="Chicken">Chicken (In all its forms)<br>
<input type="checkbox" name="FoodTypes[]" value="NoMeat">I don't eat meat at all (Vegeterian/Vegan)<br>

</div>
 <p style="text-align:center"><b> Fish And Seafood:</b></p>
 <div id="FishAndSeaFood">
 <input type="checkbox" name="FoodTypes[]" value="Fish">Fish<br>
 <input type="checkbox" name="FoodTypes[]" value="Sushi">Sushi<br>
  <input type="checkbox" name="FoodTypes[]" value="CannedFish">Canned Fish<br>
  <input type="checkbox" name="FoodTypes[]" value="Oysters">Seafood<br>
    <input type="checkbox" name="FoodTypes[]" value="SmokedSalmon">Smoked Salmon<br>
  </div>
 
 <div id="Vegetables">
 <p style="text-align:center"><b> Do you eat vegtables?</b></p><br>
 <input type="radio" name="YesOrNo" value="Yes">Yes <!-- Give both options the same name,Because they are related. -->
<input type="radio" name="YesOrNo" value="No">No<br>
 </div>
 <hr>
 

<p>Do you workout as part of your lifestyle?</p><br>
<input type="radio" name='workout_options' value='valuable' data-id="DoWorkout" class="workout_options" /> I do workout occasionally
<input type="radio" name='workout_options' value='valuable' data-id="DoNotWorkout" class="workout_options" /> I am not working out<br><br><br>
<section>
    <div id=DoWorkout class="workout_options"><p>We see you're not having any exercise at the moment.<br><br>Did you know that doing some kind of activity like running or cardio 3 times a week improve your life quality?<br><br>We'll help you go straight from zero to hero!</p></div>
    <div id=DoNotWorkout class="workout_options">What type of workout you're working on at the moment? Please choose from the options beyond:<br><br><br>
    
    <input type="checkbox" name="Cardio" value="Cardio" data-id="Cardio"/>Cardio/Aerobics<br><br> 
    <input type="checkbox" name=" Weight_Lifting" value=" Weight_Lifting" data-id="Weight_Lifting"/>Weight Lifting/ Anaerobics</div><br>
</section>

<input type="submit" value="Submit Details" name="SubmitDetails" id="SubmitDetails">

</div>
</form>

<p style="text-align:center;"><a href="#" id="Learn_More"> Learn more about Click-And-Fit</a></p>

<div id="clickme">
<p align="center"><button type="submit" id="SignUpButton" name="SignUpButton" class="SignUpButton"><p style="font-size:30px;">Sign Up</p><br><span style="font-family:Consolas;font-size:20px; "> (I am ready for the challenge!)</span></button></p></div>


<!-- Show form on click. -->
<script> 
$( "#clickme" ).click(function() {
	$( "#SignUpForm" ).show( "slow", function() {
		// Animation complete.
	});
});
</script> <!-- script for the exercise options -->
<script type="text/javascript">
$(':radio').change(function (event) { // when any radio button changes,
    var id = $(this).data('id'); // get the id from data-id
    $('#' + id) // find the div with that id.
    .addClass('workout_options') // give it the class
    .siblings().removeClass('workout_options'); // and remove the class from all it’s siblings
    // siblings are nodes before and after with the same parent.
});
</script>

</body>
</html>

PHP Code:

<?php

require('password_compat-master/lib/password.php'); //backward compatibility for the passord_hash function.

// connnecting to MYSQL with PDO.

// Connection data (server_address, database, username, password)
$hostdb = "localhost";
$namedb = 'caf_users';
$userdb = "root";
$passdb = '3563077';

if (isset($_POST['SubmitDetails'])) {

$YesOrNo=$_POST["YesOrNo"];
$fname=$_POST["fname"];
$lname=$_POST["lname"];
$Gender=$_POST["Gender"];
$email=$_POST["email"];
$Password=$_POST["Password"];
$ConfirmPassword=$_POST["ConfirmPassword"];

//check if user entered the exact password twice.

     if($Password == $ConfirmPassword)	{
     	
    
	$hash = password_hash($Password, PASSWORD_DEFAULT);
}
	// The first parameter is the password string that needs to be hashed,
	//and the second parameter specifies the algorithm that should be used for generating the hash.
	//encrypted by bcrypt algorithm.
	else {
		echo "Passwords are mismatched. Please try again.";
	};
	$UserAge=$_POST["UserAge"];
// Display message if successfully connect, otherwise retains and outputs the potential error
try {
	$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb); //Initiate connection witht the PDO object instance.
	$conn->exec("SET CHARACTER SET utf8");  // Sets encoding UTF-8
	echo 'Connected to database.';

	// Define an insert query
	$sql = "INSERT INTO `users` ('Workout','first_name','last_name','gender','Email_Address','Password','User_Age')
	VALUES
	($YesOrNo,$fname,$lname,$Gender,$email,$Password,$UserAge)";
	$count = $conn->exec($sql);

	$conn = null;        // Disconnect
	if($count !== false) echo 'Number of rows added: '. $count;
}
catch(PDOException $e) {
	echo $e->getMessage();
}
}
	?>

The query is mos likely failing for some reason. Add the following 

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // force pdo to throw an exception id an error occurs.

After    $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);

Which button is submitting the form - the one actually in the form or the one outside of the form.

Does the code following this condition ever get executed?

if (isset($_POST['SubmitDetails'])) {

put an echo right after just to see.

Better yet - loop through what values are actually in the $_POST array and echo them out.

foreach($_POST as $post) 
{
echo $post . "<br />";
}

 

......

 

PHP Code:

	// Define an insert query
	$sql = "INSERT INTO `users` ('Workout','first_name','last_name','gender','Email_Address','Password','User_Age')
	VALUES
	($YesOrNo,$fname,$lname,$Gender,$email,$Password,$UserAge)";

 

Sure that you don't see anything wrong in your INSERT sentence?....

 

You are enclosing all the field names using single quotes which make the sentence invalid ... you would have noticed that with the proper error_reporting and display_error setup either in your php.ini (prefered) or directly in your code adding this 2 lines after your opening <?php tag:

   // Define how to display/report errors
   ini_set("display_errors", "1");
   error_reporting(-1);

maybe you tried to enclose your fieldname on backticks (`) but that is absolutely unneccesary if you are not using reservated mysql words or other special identifiers.

 

An additional note: Using the values of your $_POST variables directly in your query make your code fully open to SQL Injections, you should be using Prepared sentences and be sure that PDO is using real ones and not emulating preparated sentences which leave you in the same spot that your code is now.... for real Prepared sentences be sure to include

 PDO::ATTR_EMULATE_PREPARES => false in the options of your PDO definition.

Edited by mikosiko

Hello people i have been working on debugging my project according to your solutions.

 

I have now switched to PDO and using prepared statements. My only problem is I cannot insert the registration date to the database.

 

the column 'Registration_Date' in the database (MySQL) is in type 'DATETIME' , and I been digging for hours for the format I should be inserting the query,but no success there.

 

I should mentioned the error message the MySQL server return is: Error: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

 

I have tried many possible syntaxes, and I have got many errors. Tried to fix them but without any success.

 

I also suspect this variable: $Registration_Date is part of the issue.

 

Please have a look in my updated code ,and you may be able to help me.

 

Thank you so much!!

 

PHP code:

<?php

require('password_compat-master/lib/password.php'); //backward compatibility for the passord_hash function.

ini_set('error_reporting',E_ALL^E_NOTICE);

//Server initial configuration.

$servername = "localhost";
$username = "root";
$password = "3563077";
$dbname = "caf_users";

try {


	$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
	// set the PDO error mode to exception
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	// prepare sql and bind parameters
	//Values in the query below are parameterized queries.
	$stmt = $conn->prepare("INSERT INTO users (Workout,first_name,last_name,gender,Email_Address,Password,User_Age,workout_options,Registration_Date)
    VALUES (?,?,?,?,?,?,?,?,?");

	$stmt->bindParam(':Workout', $YesOrNo);
	$stmt->bindParam(':first_name', $fname);
	$stmt->bindParam(':last_name', $lname);
	$stmt->bindParam(':gender', $Gender);
	$stmt->bindParam(':Email_Address', $email);
	$stmt->bindParam(':Password', $Password);
	$stmt->bindParam(':User_Age',$UserAge);
	$stmt->bindparam(':workout_options',$workout_options);
	$stmt->bindParam(':Registration_Date',$Registration_Date);
	
	// insert a row
	 
	$YesOrNo=$_POST["YesOrNo"];
	$fname=$_POST["fname"];
	$lname=$_POST["lname"];
	$Gender=$_POST["Gender"];
	$email=$_POST["email"];
	$Password=$_POST["Password"];
	$ConfirmPassword=$_POST["ConfirmPassword"];

	//check if user entered the exact password twice.

	if($Password == $ConfirmPassword)	{


		$hash = password_hash($Password, PASSWORD_DEFAULT);
	}
	
	else {
		echo "Passwords are mismatched. Please try again.";
		 
	};
	$UserAge=$_POST["UserAge"];
	$workout_options=$_POST["workout_options"];
	$Registration_Date=date("Y-m-d H:i:s");
	
	$stmt->execute();

	/* insert another row
	 $firstname = "Mary";
	$lastname = "Moe";
	$email = "mary@example.com";
	$stmt->execute();

	// insert another row
	$firstname = "Julie";
	$lastname = "Dooley";
	$email = "julie@example.com";
	$stmt->execute();
	*/

	echo "New records created successfully";
}
catch(PDOException $e)
{
	echo "Error: " . $e->getMessage();
}
$conn = null; //Disconnect.

?>

Thanks in advance!!

when you use ? place holders in the prepared query, you would use numerical indexes in the bindParam() statements.
 
your $stmt->bindParam(':Workout', $YesOrNo); would need to be - 

$stmt->bindParam(1, $YesOrNo);

repeat for parameters, 2, 3, 4, ....

 

here's the relevant php.net documentation - 

Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.

 

FYI - I find that named parameters are easier to keep track of and match to the columns your inserting into the database.

This is especially true when you have many columns to fill. I name the parameter similar to the real column name, so it's easier to track down when you mistakenly leave out one and you get an Sql error letting you know that your parameter count doesn't match your column count.

Hi guys.

 

I have tried your suggestions and made some changes to the code.

 

It don't bring any errors on page loading. but it do show error when I try to sumbit the details to the server.

 

Again i receive a message code like that:

 

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 2

 

line 2 is my html code, and i don't understand what I have to do with that.

 

Here's an updated code of the html and php codes:

<html>
<head>
<meta charset="UTF-8">
<script
	src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Load Jquery -->

<script>
$(document).ready(function(){ //Specify a function to execute when the DOM is fully loaded.
  $("button").click(function(){ // הפעלת פקודה על הכפתור.
    $("#SignUpButton").remove(); // Remove the SignUpButton onclick.
  });
});
</script>
<!-- below is the tag that allows reading the css settings from an external .css file. -->
<link rel="stylesheet" type="text/css" href="CSSFILE.css">
</head>
<title>Welcome to Click-And-Fit website.Soon you'll be in better shape!</title>
<body>

	<img src="Demo_Photo.jpg" class="Demo_Photo" alt="CAF Demo Image"
		height=350 width="300">

	<img src="Click_and_Fit!.jpg" class="Logo" alt="Click And Fit logo"
		height="200" width="200">

	<p style="text-align: center">
		Welcome to Click-And-Fit!<br>
		<br>Would you like to make a change in your life? <br>
		<br>
		<FONT COLOR="#551A8B"><b>Click-And-Fit</b></FONT><br>
		<br> Let's make this change happen by sign up to our website with the
		following form beyond.<br>
		<br> You need to provide some of your daily lifestyle habits.
		(e.g.:Like if you're a smoker)
	</p>
	<br>
	<br>
	<br>


	<div class="container">
		<a href="" class="button"><strong>Already have an account?</strong></a>
	</div>

	<div align="center">
		<form action="" id="SignUpForm" autocomplete="on"
			style="display: none" method="post">
			<!-- Form is Hidden until the user is clicking the "Sign Up" button. -->
			<input type="hidden" name="Language" value="English"> Fill up the
			following fields:<br>
			<br> First name:<input type="text" name="fname" required><br>
			<br> Last name: <input type="text" name="lname" required><br>
			<br> Age: <input type="number" name="UserAge" min="1" max="120"
				required><br>
			<br> Gender: <input type="radio" name="Gender" value="male">Male<br>
			<input type="radio" name="Gender" value="Female">Female<br> E-mail
			Address: <input type="email" name="email" autocomplete="off" required><br>
			<br> Pick your new password: <input type="password" maxlength=”40”
				name="Password" required
				pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"> Add password
			strength checker here.<br>
			<br>
			<!-- Uses regular expression. -->
			Confirm Password: <input type="password" maxlength=”40”
				name="ConfirmPassword" required
				pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"><br>
			<br>
			<!-- A better way is to use onblur to check user's type match. -->
			<hr>
			<script>
 (function(){
        $("#submit").click(function(){
        $(".error").hide(); //Bind an event handler to the "error" JavaScript event.
        var hasError = false;
        var passwordVal = $("#Password").val();
        var checkVal = $("#ConfirmPassword").val();
        if (passwordVal == '') {
            $("#Password").after('<span class="error">Please enter a password.</span>');
            hasError = true;
        } else if (checkVal == '') {
            $("#ConfirmPassword").after('<span class="error">Please re-enter your password.</span>');
            hasError = true;
        } else if (passwordVal != checkVal ) {
            $("#ConfirmPassword").after('<span class="error">Passwords do not match.</span>');
            hasError = true;
        }
        if(hasError == true) {return false;}
    });
});
 </script>

			<script>
//The validationMessage property of a DOM node contains the message the browser displays to the user when a node's validity is checked and fails.
document.getElementById("name").validationMessage;
document.getElementById("lname").validationMessage;
document.getElementById("UserAge").validationMessage;
document.getElementById("Gender").validationMessage;
document.getElementById("email").validationMessage;
document.getElementById("Password").validationMessage;
document.getElementById("ConfirmPassword").validationMessage;
</script>

			Now let's go through your prefered food. Check the appropriate boxed
			beyond.<br>
			<br> This will help us to better understand your food discipline:<br>

			<p style="text-align: center">
				<b> Meat And Poultry:</b>
			</p>
			<div id="MeatCheckBox">
				<input type="checkbox" name="FoodTypes[]" value="Hamburger">Hamburger<br>
				<input type="checkbox" name="FoodTypes[]" value="Steak">Steak<br> <input
					type="checkbox" name="FoodTypes[]" value="GroundBeef">Ground Beef<br>
				<input type="checkbox" name="FoodTypes[]" value="Bacon">Bacon<br> <input
					type="checkbox" name="FoodTypes[]" value="Beef">Beef<br> <input
					type="checkbox" name="FoodTypes[]" value="Salami">Salami<br> <input
					type="checkbox" name="FoodTypes[]" value="Chicken">Chicken (In all
				its forms)<br> <input type="checkbox" name="FoodTypes[]"
					value="NoMeat">I don't eat meat at all (Vegeterian/Vegan)<br>

			</div>
			<p style="text-align: center">
				<b> Fish And Seafood:</b>
			</p>
			<div id="FishAndSeaFood">
				<input type="checkbox" name="FoodTypes[]" value="Fish">Fish<br> <input
					type="checkbox" name="FoodTypes[]" value="Sushi">Sushi<br> <input
					type="checkbox" name="FoodTypes[]" value="CannedFish">Canned Fish<br>
				<input type="checkbox" name="FoodTypes[]" value="Oysters">Seafood<br>
				<input type="checkbox" name="FoodTypes[]" value="SmokedSalmon">Smoked
				Salmon<br>
			</div>

			<div id="Vegetables">
				<p style="text-align: center">
					<b> Do you eat vegtables?</b>
				</p>
				<br> <input type="radio" name="YesOrNo" value="Yes">Yes
				<!-- Give both options the same name,Because they are related. -->
				<input type="radio" name="YesOrNo" value="No">No<br>
			</div>
			<hr>


			<p>Do you workout as part of your lifestyle?</p>
			<br> <input type="radio" name='workout_options' value='valuable'
				data-id="DoWorkout" class="workout_options" /> I do workout
			occasionally <input type="radio" name='workout_options'
				value='valuable' data-id="DoNotWorkout" class="workout_options" /> I
			am not working out<br>
			<br>
			<br>
			<section>
				<div id=DoWorkout class="workout_options">
					<p>
						We see you're not having any exercise at the moment.<br>
						<br>Did you know that doing some kind of activity like running or
						cardio 3 times a week improve your life quality?<br>
						<br>We'll help you go straight from zero to hero!
					</p>
				</div>
				<div id=DoNotWorkout class="workout_options">
					What type of workout you're working on at the moment? Please choose
					from the options beyond:<br>
					<br>
					<br> <input type="checkbox" name="Cardio" value="Cardio"
						data-id="Cardio" />Cardio/Aerobics<br>
					<br> <input type="checkbox" name=" Weight_Lifting"
						value=" Weight_Lifting" data-id="Weight_Lifting" />Weight Lifting/
					Anaerobics
				</div>
				<br>
			</section>

			<input type="submit" value="Submit Details" name="SubmitDetails"
				id="SubmitDetails">
	
	</div>
	</form>

	<p style="text-align: center;">
		<a href="#" id="Learn_More"> Learn more about Click-And-Fit</a>
	</p>

	<div id="clickme">
		<p align="center">
			<button type="submit" id="SignUpButton" name="SignUpButton"
				class="SignUpButton">
				<p style="font-size: 30px;">Sign Up</p>
				<br>
				<span style="font-family: Consolas; font-size: 20px;"> (I am ready
					for the challenge!)</span>
			</button>
		</p>
	</div>


	<!-- Show form on click. -->
	<script> 
$( "#clickme" ).click(function() {
	$( "#SignUpForm" ).show( "slow", function() {
		// Animation complete.
	});
});
</script>
	<!-- script for the exercise options -->
	<script type="text/javascript">
$(':radio').change(function (event) { // when any radio button changes,
    var id = $(this).data('id'); // get the id from data-id
    $('#' + id) // find the div with that id.
    .addClass('workout_options') // give it the class
    .siblings().removeClass('workout_options'); // and remove the class from all it’s siblings
    // siblings are nodes before and after with the same parent.
});
</script>

</body>
</html>

PHP:

<?php

require('password_compat-master/lib/password.php'); //backward compatibility for the passord_hash function.

ini_set('error_reporting',E_ALL^E_NOTICE);

//Server initial configuration.

$servername = "localhost";
$username = "root";
$password = "3563077";
$dbname = "caf_users";

try {


	$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
	// set the PDO error mode to exception
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	// prepare sql and bind parameters
	//Values in the query below are parameterized queries.
	$stmt = $conn->prepare("INSERT INTO users (Workout,first_name,last_name,gender,Email_Address,Password,User_Age,workout_options,Registration_Date)
    VALUES (?,?,?,?,?,?,?,?,?");

	$stmt->bindParam(1,$YesOrNo);
	$stmt->bindParam(2,$fname);
	$stmt->bindParam(3,$lname);
	$stmt->bindParam(4,$Gender);
	$stmt->bindParam(5,$email);
	$stmt->bindParam(6,$Password);
	$stmt->bindParam(7,$UserAge);
	$stmt->bindParam(8,$workout_options);
	$stmt->bindParam(9,$Registration_Date);
	
	// insert a row
	
if (isset($_POST['SubmitDetails']))	
{
	
	$YesOrNo=$_POST["YesOrNo"];
	$fname=$_POST["fname"];
	$lname=$_POST["lname"];
	$Gender=$_POST["Gender"];
	$email=$_POST["email"];
	$Password=$_POST["Password"];
	$ConfirmPassword=$_POST["ConfirmPassword"];

	//check if user entered the exact password twice.

	if($Password == $ConfirmPassword)	{


		$hash = password_hash($Password, PASSWORD_DEFAULT);
	}
	// The first parameter is the password string that needs to be hashed,
	//and the second parameter specifies the algorithm that should be used for generating the hash.
	//encrypted by bcrypt algorithm.
	else {
		echo "Passwords are mismatched. Please try again.";
		 
	};
	$UserAge=$_POST["UserAge"];
	$workout_options=$_POST["workout_options"];
	$Registration_Date=date("Y-m-d H:i:s");
	
	$stmt->execute();

	/* insert another row
	 $firstname = "Mary";
	$lastname = "Moe";
	$email = "mary@example.com";
	$stmt->execute();

	// insert another row
	$firstname = "Julie";
	$lastname = "Dooley";
	$email = "julie@example.com";
	$stmt->execute();
	*/

	echo "New records created successfully";
}}
catch(PDOException $e)
{
	echo "Error: " . $e->getMessage();
}
$conn = null; //Disconnect.

?>

the error message is from the sql query. the message mentions sql or mysql three times. the problem is in line 2 of your sql query statement.

 

here's a tip that will help you to write better and easier to debug code. always form your sql query statement in a php variable. this lets you echo the sql query statement for debugging purposes and separates the syntax of the php code that prepares/runs the sql query from the sql query statement itself (which is where the problem is in this case.)

$query = "INSERT INTO users (Workout,first_name,last_name,gender,Email_Address,Password,User_Age,workout_options,Registration_Date)
VALUES (?,?,?,?,?,?,?,?,?";

$stmt = $conn->prepare($query);

once you do this, you will be able to see what's wrong with the sql query syntax just by looking at the code - the closing ) is missing. the ) that you had near the end of the query was part of the ->prepare() syntax, not part of the sql syntax.

  • Like 1

Hi!

 

i have worked through this, and figured it out! 

 

there was some mess with the query single qoute positions and brackets and double quote position as well.

 

All fixed and works perfect, and now I can finally insert data into the database!

 

Although,data is not shown completely on the mysql table- specifically an array of choices,but I will open a new thread about it.

 

 

Thank you for your consistent help, I am now more aware of errors in the process.

 

Could you also please explain and demostrate can I echo the contents of my sql query in case I am using $conn as a connection parameters, and then point it to the query itself? (Like it's done in the case of this thread).

 

Thanks.

  • Solution

Working Code:

<html>
<head>
<meta charset="UTF-8">
<script
	src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Load Jquery -->

<script>
$(document).ready(function(){ //Specify a function to execute when the DOM is fully loaded.
  $("button").click(function(){ // הפעלת פקודה על הכפתור.
    $("#SignUpButton").remove(); // Remove the SignUpButton onclick.
  });
});
</script>
<!-- below is the tag that allows reading the css settings from an external .css file. -->
<link rel="stylesheet" type="text/css" href="CSSFILE.css">
</head>
<title>Welcome to Click-And-Fit website.Soon you'll be in better shape!</title>
<body>

	<img src="Demo_Photo.jpg" class="Demo_Photo" alt="CAF Demo Image"
		height=350 width="300">

	<img src="Click_and_Fit!.jpg" class="Logo" alt="Click And Fit logo"
		height="200" width="200">

	<p style="text-align: center">
		Welcome to Click-And-Fit!<br>
		<br>Would you like to make a change in your life? <br>
		<br>
		<FONT COLOR="#551A8B"><b>Click-And-Fit</b></FONT><br>
		<br> Let's make this change happen by sign up to our website with the
		following form beyond.<br>
		<br> You need to provide some of your daily lifestyle habits.
		(e.g.:Like if you're a smoker)
	</p>
	<br>
	<br>
	<br>


	<div class="container">
		<a href="" class="button"><strong>Already have an account?</strong></a>
	</div>

	<div align="center">
		<form action="" id="SignUpForm" autocomplete="on"
			style="display: none" method="post">
			<!-- Form is Hidden until the user is clicking the "Sign Up" button. -->
			<input type="hidden" name="Language" value="English"> Fill up the
			following fields:<br>
			<br> First name:<input type="text" name="fname" required><br>
			<br> Last name: <input type="text" name="lname" required><br>
			<br> Age: <input type="number" name="UserAge" min="1" max="120"
				required><br>
			<br> Gender: <input type="radio" name="Gender" value="male">Male<br>
			<input type="radio" name="Gender" value="Female">Female<br> E-mail
			Address: <input type="email" name="email" autocomplete="off" required><br>
			<br> Pick your new password: <input type="password" maxlength=”40”
				name="Password" required
				pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"> Add password
			strength checker here.<br>
			<br>
			<!-- Uses regular expression. -->
			Confirm Password: <input type="password" maxlength=”40”
				name="ConfirmPassword" required
				pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"><br>
			<br>
			<!-- A better way is to use onblur to check user's type match. -->
			<hr>
			<script>
 (function(){
        $("#submit").click(function(){
        $(".error").hide(); //Bind an event handler to the "error" JavaScript event.
        var hasError = false;
        var passwordVal = $("#Password").val();
        var checkVal = $("#ConfirmPassword").val();
        if (passwordVal == '') {
            $("#Password").after('<span class="error">Please enter a password.</span>');
            hasError = true;
        } else if (checkVal == '') {
            $("#ConfirmPassword").after('<span class="error">Please re-enter your password.</span>');
            hasError = true;
        } else if (passwordVal != checkVal ) {
            $("#ConfirmPassword").after('<span class="error">Passwords do not match.</span>');
            hasError = true;
        }
        if(hasError == true) {return false;}
    });
});
 </script>

			<script>
//The validationMessage property of a DOM node contains the message the browser displays to the user when a node's validity is checked and fails.
document.getElementById("name").validationMessage;
document.getElementById("lname").validationMessage;
document.getElementById("UserAge").validationMessage;
document.getElementById("Gender").validationMessage;
document.getElementById("email").validationMessage;
document.getElementById("Password").validationMessage;
document.getElementById("ConfirmPassword").validationMessage;
</script>

			Now let's go through your prefered food. Check the appropriate boxed
			beyond.<br>
			<br> This will help us to better understand your food discipline:<br>

			<p style="text-align: center">
				<b> Meat And Poultry:</b>
			</p>
			<div id="MeatCheckBox">
				<input type="checkbox" name="FoodTypes[]" value="Hamburger">Hamburger<br>
				<input type="checkbox" name="FoodTypes[]" value="Steak">Steak<br> <input
					type="checkbox" name="FoodTypes[]" value="GroundBeef">Ground Beef<br>
				<input type="checkbox" name="FoodTypes[]" value="Bacon">Bacon<br> <input
					type="checkbox" name="FoodTypes[]" value="Beef">Beef<br> <input
					type="checkbox" name="FoodTypes[]" value="Salami">Salami<br> <input
					type="checkbox" name="FoodTypes[]" value="Chicken">Chicken (In all
				its forms)<br> <input type="checkbox" name="FoodTypes[]"
					value="NoMeat">I don't eat meat at all (Vegeterian/Vegan)<br>

			</div>
			<p style="text-align: center">
				<b> Fish And Seafood:</b>
			</p>
			<div id="FishAndSeaFood">
				<input type="checkbox" name="FoodTypes[]" value="Fish">Fish<br> <input
					type="checkbox" name="FoodTypes[]" value="Sushi">Sushi<br> <input
					type="checkbox" name="FoodTypes[]" value="CannedFish">Canned Fish<br>
				<input type="checkbox" name="FoodTypes[]" value="Oysters">Seafood<br>
				<input type="checkbox" name="FoodTypes[]" value="SmokedSalmon">Smoked
				Salmon<br>
			</div>

			<div id="Vegetables">
				<p style="text-align: center">
					<b> Do you eat vegtables?</b>
				</p>
				<br> <input type="radio" name="YesOrNo" value="Yes">Yes
				<!-- Give both options the same name,Because they are related. -->
				<input type="radio" name="YesOrNo" value="No">No<br>
			</div>
			<hr>


			<p>Do you workout as part of your lifestyle?</p>
			<br> <input type="radio" name='workout_options' value='valuable'
				data-id="DoWorkout" class="workout_options" /> I do workout
			occasionally <input type="radio" name='workout_options'
				value='valuable' data-id="DoNotWorkout" class="workout_options" /> I
			am not working out<br>
			<br>
			<br>
			<section>
				<div id=DoWorkout class="workout_options">
					<p>
						We see you're not having any exercise at the moment.<br>
						<br>Did you know that doing some kind of activity like running or
						cardio 3 times a week improve your life quality?<br>
						<br>We'll help you go straight from zero to hero!
					</p>
				</div>
				<div id=DoNotWorkout class="workout_options">
					What type of workout you're working on at the moment? Please choose
					from the options beyond:<br>
					<br>
					<br> <input type="checkbox" name="Cardio" value="Cardio"
						data-id="Cardio" />Cardio/Aerobics<br>
					<br> <input type="checkbox" name=" Weight_Lifting"
						value=" Weight_Lifting" data-id="Weight_Lifting" />Weight Lifting/
					Anaerobics
				</div>
				<br>
			</section>

			<input type="submit" value="Submit Details" name="SubmitDetails"
				id="SubmitDetails">
	
	</div>
	</form>

	<p style="text-align: center;">
		<a href="#" id="Learn_More"> Learn more about Click-And-Fit</a>
	</p>

	<div id="clickme">
		<p align="center">
			<button type="submit" id="SignUpButton" name="SignUpButton"
				class="SignUpButton">
				<p style="font-size: 30px;">Sign Up</p>
				<br>
				<span style="font-family: Consolas; font-size: 20px;"> (I am ready
					for the challenge!)</span>
			</button>
		</p>
	</div>


	<!-- Show form on click. -->
	<script> 
$( "#clickme" ).click(function() {
	$( "#SignUpForm" ).show( "slow", function() {
		// Animation complete.
	});
});
</script>
	<!-- script for the exercise options -->
	<script type="text/javascript">
$(':radio').change(function (event) { // when any radio button changes,
    var id = $(this).data('id'); // get the id from data-id
    $('#' + id) // find the div with that id.
    .addClass('workout_options') // give it the class
    .siblings().removeClass('workout_options'); // and remove the class from all it’s siblings
    // siblings are nodes before and after with the same parent.
});
</script>

</body>
</html>

PHP:


<?php

require('password_compat-master/lib/password.php'); //backward compatibility for the passord_hash function.

ini_set('error_reporting',E_ALL^E_NOTICE);

//Server initial configuration.

$servername = "localhost";
$username = "root";
$password = "3563077";
$dbname = "caf_users";

try {


	$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
	// set the PDO error mode to exception
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	// prepare sql and bind parameters
	//Values in the query below are parameterized queries.
	$stmt = $conn->prepare("INSERT INTO users (Food_Types,first_name,last_name,gender,Email_Address,Password,User_Age,workout_options,Registration_Date)
    VALUES (?,?,?,?,?,?,?,?,?)");
//While binding parameters,the second parameter will always be a variable.
	$stmt->bindParam('1',$FoodTypes);
	$stmt->bindParam('2',$fname);
	$stmt->bindParam('3',$lname);
	$stmt->bindParam('4',$Gender);
	$stmt->bindParam('5',$email);
	$stmt->bindParam('6',$Password);
	$stmt->bindParam('7',$UserAge);
	$stmt->bindParam('8',$workout_options);
	$stmt->bindParam('9',$Registration_Date);
	
	// insert a row
	
if (isset($_POST['SubmitDetails']))	
{
	
	$FoodTypes=implode(':',$_POST["FoodTypes"]); // $FoodTypes will contain all values glued together with a ';' in between them.
	$fname=$_POST["fname"];
	$lname=$_POST["lname"];
	$Gender=$_POST["Gender"];
	$email=$_POST["email"];
	$Password=$_POST["Password"];
	$ConfirmPassword=$_POST["ConfirmPassword"];

	//check if user entered the exact password twice.

	if($Password == $ConfirmPassword)	{


		$hash = password_hash($Password, PASSWORD_DEFAULT);
	}
	// The first parameter is the password string that needs to be hashed,
	//and the second parameter specifies the algorithm that should be used for generating the hash.
	//encrypted by bcrypt algorithm.
	else {
		echo "Passwords are mismatched. Please try again.";
		 
	};
	$UserAge=$_POST["UserAge"];
	$workout_options=$_POST["workout_options"];
	$Registration_Date=date("Y-m-d H:i:s");
	
	$stmt->execute();

	/* insert another row
	 $firstname = "Mary";
	$lastname = "Moe";
	$email = "mary@example.com";
	$stmt->execute();

	// insert another row
	$firstname = "Julie";
	$lastname = "Dooley";
	$email = "julie@example.com";
	$stmt->execute();
	*/

	echo "New records created successfully";
}}
catch(PDOException $e)
{
	echo "Error: " . $e->getMessage();
}
$conn = null; //Disconnect.

?>
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.