So i have a website, and i am trying to test the new user register functionality. I am not getting an output for any of the echos in my LogInHelper.php file. The goal is to be able to enter information for a new user, post it to LogInHelper.php, see if the passwords entered are equal, and if they are not, update the result div to the error message.
this is my LogIn.php file containing the html:
<!DOCTYPE html>
<html>
<head>
<title>Ticket Log In</title>
<script src = "../../jquery.js"></script>
<style>
body{
padding:0;
margin:0;
}
#box {
background:blue;
text-align:center;
padding:10px;
color:white;
width:500px;
height:300px;
margin: 0 auto;
}
#LogIn {
background:blue;
text-align:center;
padding:10px;
color:white;
width:500px;
height:300px;
margin: 0 auto;
}
</style>
<script>
$(document).ready(function(){
$("#sub").click(function(){
var fist_name = $("#firstname").val();
var last_name = $("#lastname").val();
var user_email = $("#email").val();
var department_id = $("#department").val();
var user_pass = $("#pass").val();
var user_pass2 = $("#pass2").val();
$.post("LogInHelper.php",{firstname:first_name,lastname:last_name,email:user_email,department:department_id,pass:user_pass,pass2:user_pass2},function(data){
$("#result").html(data);
});
});
$("#sub2").click(function(){
var loginuser_email = $("#loginemail").val();
var loginuser_pass = $("#loginpass").val();
$.post("LogInHelper.php",{loginemail:loginuser_email,loginpass:loginuser_pass},function(data){
$("#result2").html(data);
});
});
$('#box').hide();
$('.new').click(function() {
$('#box').toggle();
$('#LogIn').toggle();
});
});
</script>
</head>
<body>
<div id="box">
<input type ="submit" class = "new" value = "New User Register">
<h2>New User Register Here:</h2>
<input type ="text" name="firstname" id="firstname" placeholder="Enter Your First Name"/></br>
<input type ="text" name="lastname" id="lastname" placeholder="Enter Your Last Name"/></br>
<input type ="text" name="email" id="email" placeholder="Enter Your email"/></br>
<form action="LogInHelper.php" method="post">
<select id = "department" name = "department">
<?php
$servername = "localhost";
$username = "quantco_Ted";
$password = "Quantum1";
$database = "quantco_Interns";
$con = mysqli_connect($servername,$username,$password,$database);
if($con->connect_error){
die("Connection failed " . $con->connect_error);
}
$sql = "select Department_name,id from Department";
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($result)) {
$department = $row['Department_name'];
$id = $row['id'];
echo "<option value = '$id'>$department</option>";
}
?></select></form>
<input type ="password" name="pass" id="pass" placeholder="Enter Your Password"/>
<input type ="password" name="pass2" id="pass2" placeholder="Re-Enter Your Password"/>
</br></br>
<input type ="submit" name = "sub" value = "Register" id = "sub"/>
<div id="result"></div>
</div>
<div id="LogIn">
<input type ="submit" class = "new" value = "New User Register">
<h2>Registered User Log In:</h2>
<input type ="text" name="loginemail" id="loginemail" placeholder="Enter Your Email"/></br>
<input type ="password" name="loginpass" id="loginpass" placeholder="Enter Your Password"/>
</br></br>
<input type ="submit" name = "sub2" value = "Submit" id = "sub2"/>
<div id="result2"></div>
</div>
</body>
</body>
</html>
Here is my LogInHelper file that receives the posts:
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$database = "db";
$con = mysqli_connect($servername,$username,$password,$database);
if($con->connect_error){
die("Connection failed " . $con->connect_error);
}
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$id = $_POST['department'];
$email = $_POST['email'];
$pass = md5($_POST['pass']);
$pass2 = md5($_POST['pass2']);
echo $firstname;
echo $lastname;
echo $id;
echo $email;
echo $pass;
echo $pass2;
$sel = "select * from Employee where email='$email'";
$run = mysqli_query($con,$sel);
$check_email = mysqli_num_rows($run);
if(!($pass==$pass2)){
echo "<h2>Your emails do not match, please try again!</h2>";
exit();
}
else if($check_email==1){
echo "<h2>This email is already registered, please try another!</h2>";
exit();
}
else{
$insert = "insert into Employee (email, first, last, department_id,pass,) values ('$email','$firstname','$lastname','$id', '$pass')";
$run_insert = mysqli_query($con,$insert);
if($run_insert){
echo "<h2>Registration Successful, Thanks!</h2>";
}
}
mysqli_close($con);
?>
I have check your $("#sub").click(function(){ and found that you have typo mistake in var fist_name = $("#firstname").val(); so it should be var first_name = $("#firstname").val();
Please update this after that it will work
Related
LOGINPAGE.html:
This is where the user will input their username and password. PHP method is POST.
<html>
<head>
<title>
LOG IN
</title>
<style>
body {
text-align: center;
}
</style>
</head>
<body>
<form action = "loginDatabase.php" method = "POST">
<label>User name:</label>
<input type="text" id="userNameID" name="userNameName" required>
<br />
<label>Password:</label>
<input type="password" id="passwordID" name="passwordName" required>
<br />
<input type="submit" id="submitLoginID" name="submitLoginName">
</form>
</body>
</html>
LOGINDATABASE.php:
This is the processing part where the mysql query will reference the record to be displayed on ADMINPAGE.php based on the username given on LOGINPAGE.php. I cannot figure out want went wrong in line 7 since I always get an error Notice: Undefined index: userNameName in /opt/lampp/htdocs/UsersDatabaseProgram/loginDatabase.php on line 7
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include('connect.php');
session_start();
$result = mysqli_query($con, "SELECT * FROM addUsers WHERE userName = '" . $_GET['userNameName'] . "'");
if ($_SERVER ["REQUEST_METHOD"] == "POST") {
$userName = $_POST['userNameName'];
$password = $_POST['passwordName'];
/*
This doesnt work
$email = $row['email'];
$userlevel = $row['userLevel'];
*/
$sql = "SELECT * FROM addUsers WHERE userName = '".$userName."' AND password = '".$password."'";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
if ($row["userLevel"] == "user") {
$_SESSION["userName"] = $userName;
header('location: userPage.php');
} elseif ($row["userLevel"] == "admin") {
$_SESSION["userName"] = $userName;
header('location: adminPage.php');
} else {
echo "<h1> Login failed. Invalid username or password.</h1>";
}
}
?>
ADMINPAGE.php:
This is where the name of the user, user level, and user status will be displayed.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include('connect.php');
include('loginDatabase.php');
?>
<html>
<head>
<style>
body {
text-align: center;
}
</style>
</head>
<body>
<h2>Admin</h2>
Log-out <br />
View records <br />
Add Record <br />
<label>Welcome</label><br />
<?php echo $_SESSION["userName"] ?>
<br />
<label>User level: </label>
<?php
while ($row = mysqli_fetch_array($result)) {
?>
<input type = "text" name = "userLevelName" value = " <?php echo $row['userLevel']; ?>"> <br />
<label>Email: </label>
<input type = "text" name = "userEmailName" value = " <?php echo $row['email']; ?>">
<?php
}
?>
<br />
</body>
</html>
You're sending the data as a POST then trying to access it as GET (then retrieving it again on line 11 !!).
Change it to something like this:-
if ($_SERVER ["REQUEST_METHOD"] == "POST") {
$userName = $_POST['userNameName'];
$password = $_POST['passwordName'];
}
$result = mysqli_query($con, "SELECT * FROM addUsers WHERE userName = '$userName'");
I want to create form in HTML files. let say it calls index.html ( client will see this page), and the HTML will be included some ajax codes where it links to php (server connect to Mysql)
So that client can do (insert delete edit) to database by inserting form in the index.html. How possibly to do that?. Please give me a simple code so that I can learn. Thank you so much. I found that PHP can link to others php to retrieve the data. But I would love to use HTML instead ,to link to php on the server.
Thank you so much.
edited code
enter code here (this is index.html)
<html>
<head>
<title>Submit Form Using AJAX PHP and javascript</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="css/style.css" />
<script>
function myFunction() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var contact = document.getElementById("contact").value;
var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
if (name == '' || email == '' || password == '' || contact == '')
{
alert("Please Fill All Fields");
}
else
{
//AJAX code to submit form.
$.ajax({
type: "POST",
url: "https://../test2.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}</script>
</head>
<body>
<div id="mainform">
<div class="innerdiv">
<h2>Submit Form</h2>
//div starts here
<form id="form">
<h3>Fill Your Information!</h3>
<div>
<label>Name :</label>
<br/>
<input type="text" id="name" /><br/>
<br/>
<label>Email :</label>
<br/>
<input type="text" id="email"/><br/>
<br/>
<label>Password :</label>
<br/>
<input type="password" id="password" /><br/>
<br/>
<label>Contact No :</label>
<br/>
<input type="text" id="contact" /><br/>
<br/>
<input type="button" id="submit" onclick="myFunction()" value="Submit"/>
</div>
</form>
<div id="clear"></div>
</div>
</body>
</html>
and this is the php.
//Fetching Values from URL
$name2 = $_POST['name1'];
$email2 = $_POST['email1'];
$password2 = $_POST['password1'];
$contact2 = $_POST['contact1'];
$servername = "localhost";
$username = "user";
$password = "userpwd";
$dbname = "dbname";
// Establishing connection with server..
$dbc = mysqli_connect($servername, $username, $password , $dbname)
or die('Error connecting to MySQL server.');
// Selecting Database
if (isset($_POST['name1'])) {
//Insert query
$query = mysqli_query("insert into form_element(name, email, password, contact) values ('$name2', '$email2', '$password2','$contact2')");
echo "Form Submitted succesfully";
}
//connection closed
mysqli_close($dbc);
?>
I don't get it work.
I don't have all the div's you had in there before, but you should be able to add them!
This should work once you put in the right username, password and database name in connection.php
If this doesn't work or isn't what you wanted, please let me know!
This is also up and running at http://emmetstudios.com/form, if you want to see it in operation.
Here's the code, (put it all in the same folder, different files):
connection.php:
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "yourusername";
$dbpass = "yourpassword";
$dbname = "yourdatabasename";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
success.php:
<?php
require 'connection.php';
$conn = Connect();
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$password = $conn->real_escape_string($_POST['password']);
$contact = $conn->real_escape_string($_POST['contact']);
$query = "INSERT into form_element (name,email,password,contact) VALUES('" . $name . "','" . $email . "','" . $password . "','" . $contact . "')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
echo "Successful!";
$conn->close();
?>
index.php:
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<form id="form" action="success" method="post" onsubmit="return validateForm()" name="upload">
Name:<br>
<input type="text" name="name"> <br><br>
Email:<br>
<input type="text" name="email"> <br><br>
Password:<br>
<input type="password" name="password"> <br><br>
Phone Number:<br>
<input type="text" name="contact"> <br><br>
<input id="submit" type="submit" value="Submit">
</form>
<script>
function validateForm() {
var name = document.forms["form"]["name"].value;
if (name == "") {
alert("Name must be filled out");
return false;
}
var email = document.forms["form"]["email"].value;
if (email == "") {
alert("Email must be filled out");
return false;
}
var password = document.forms["form"]["password"].value;
if (password == "") {
alert("Password must be filled out");
return false;
}
var contact = document.forms["form"]["contact"].value;
if (contact == "") {
alert("contact must be filled out");
return false;
}
}
</script>
</body>
</html>
I'm wondering if and how I could check if a username is being used.
I heard you can do this with jQuery but i just want something simple since I'm a beginner.
I have tried it but i can't seam to get it right. I just have it connected to a mysql database but since when a username with the same password as another account tries to logon, theres an issue, so i need this to stop people adding multiple usernames.
Here is my simple code for the registration form and the php
<form action="" method="POST">
<p><label>name : </label>
<input id="password" type="text" name="name" placeholder="name" /></p>
<p><label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" /></p>
<p><label>E-Mail : </label>
<input id="password" type="email" name="email"/></p>
<p><label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" /></p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Register" />
</form>
</div>
<?php
require('connect.php');
// If the values are posted, insert them into the database.
if (isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$query = "INSERT INTO `user` (username, password, email, name) VALUES ('$username', '$password', '$email', '$name')";
$result = mysql_query($query);
if($result){
}
}
?>
For starters you don't want to just rely on something like unique field for doing this, of course you will want to add that attribute to your username column within your database but above that you want to have some sort of frontal protection above it and not rely on your database throwing an error upon INSERT INTO, you're also going to want to be using mysqli for all of this and not the old version, mysql. It's vulnerable to exploitation and no longer in common practice, here's what each of your files should look like:
connect.php
<?php
$conn = mysqli_connect("localhost","username","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
register.php
<form action="insertuser.php" method="POST">
Username:
<input type="text" name="username" placeholder="Username" />
<br />
Password:
<input type="password" name="password" placeholder="Password" />
<br />
Name:
<input type="text" name="name" placeholder="Name" />
<br />
Email address:
<input type="text" name="email" placeholder="Email address" />
<br /><br />
<input type="submit" value="Register" />
</form>
<?php
// If there's an error
if (isset($_GET['error'])) {
$error = $_GET['error'];
if ($error == "usernametaken") {
echo "<h4>That username is taken!</h4>";
} elseif ($error == "inserterror") {
echo "<h4>Some kind of error occured with the insert!</h4>";
} else {
echo "<h4>An error occured!</h4>";
}
echo "<br />";
}
?>
Already have an account? Login here
insertuser.php
<?php
// Stop header errors
ob_start();
// Check if form has been posted
if (isset($_POST['username'])){
// Requre database connection file
require('connect.php');
// Clean the variables preventing SQL Injection attack
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$name = mysqli_real_escape_string($conn, $_POST['name']);
// Check if the username exists
// Construct SELECT query to do this
$sql = "SELECT id FROM user WHERE username = '".$username."';";
$result = mysqli_query($conn, $sql);
$rowsreturned = mysqli_num_rows($result);
// If the username already exists
if ($rowsreturned != 0) {
echo "Username exists, redirecting to register.php with an error GET variable!";
// Redirect user
header('Location: register.php?error=usernametaken');
} else {
// Construct the INSERT INTO query
$sql = "INSERT INTO user (username, password, email, name) VALUES ('".$username."', '".$password."', '".$email."', '".$username."');";
$result = mysqli_query($conn, $sql);
if($result){
// User was inserted
echo "User inserted!";
/* DO WHATEVER YOU WANT TO DO HERE */
} else {
// There was an error inserting
echo "Error inserting, redirecting to register.php with an error GET variable!";
// Redirect user
header('Location: register.php?error=inserterror');
}
}
}
?>
Good luck with whatever you're working on and I hope this helps!
James
if (isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$query = "select username from user where username = '$username'";
$res = mysql_query($query);
$rows = mysqli_num_rows($res);
if ($rows > 0) {
print 'Username already exists...';
} else {
$query = "INSERT INTO `user` (username, password, email, name) VALUES ('$username', '$password', '$email', '$name')";
$result = mysql_query($query);
if($result){
}
}
}
Here is another example :) , succes.
<?php
//Set empty variables.
$usernameError = $emailError = $passwordError = $nameError = $okmsg = "";
$username = $password = $email = $name = "";
if (isset($_POST['submit'])) {
//Check if empty labels form
if (empty($_POST['name'])) {
$userError = "The 'name' is required.";
echo '<script>window.location="#registrer"</script>';
} else { $name = $_POST['name']; }
if (empty($_POST['email'])) {
$emailError = "El 'Email' es requerido.";
echo '<script>window.location="#registrer"</script>';
} else {
$email = $_POST['email'];
//Check only contain letters and whitespace.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailError = "El 'Email' is not valid. ";
echo '<script>window.location="#registrer"</script>';
}
}
if (empty($_POST['password'])) {
$passwordError = "The 'password' is requiered.";
echo '<script>window.location="#registrer"</script>';
} else {
$password = $_POST['password'];
}
}
//Check if correctly filled
if ($name && $username && $email && $password) {
require('connect.php');
//Query SQL
$sql = "SELECT * FROM user WHERE username='$username'"; //String SQL
$query = mysqli_query($ConDB, $sql);//Query
//Securite
$username = mysqli_real_escape_string($ConDB, $username);
$password = mysqli_real_escape_string($ConDB, $username);
$passw = sha1($password);//For securite.
$name = mysqli_real_escape_string($ConDB, $username);
$email = mysqli_real_escape_string($ConDB, $username);
if ($existe = mysqli_fetch_object($query)) {
$usernameError = "The 'Username' is already exists.";
echo '<script>window.location="#registrer"</script>';
} else {
$sql = "INSERT INTO user (username, password, email, name) VALUES ('$username', '$passw', '$email', '$name')";
mysqli_query($ConDB, $sql);
$okmsg = "Register with succes.";
mysqli_close($ConDB);//Close conexion.
echo '<script>window.location="#registrer"</script>';
}
}
?>
<a name="registrer"></a>
<form action="" method="POST">
<p><label>name : </label>
<input id="password" type="text" name="name" placeholder="name" /></p>
<?php echo $nameError; ?>
<p><label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" /></p>
<?php echo $usernameError; ?>
<p><label>E-Mail : </label>
<input id="password" type="email" name="email"/></p>
<?php echo $emailError; ?>
<p><label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" /></p>
<?php echo $passwordError; ?>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Register" />
<?php echo $okmsg; ?>
</form>
--
-- DATA BASE: `user`
--
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
CREATE TABLE user (
id int(11) unsigned not null auto_increment primary key,
name varchar(50) not null,
email varchar(80) not null unique,
username varchar(30) not null unique,
password varchar(40) not null
)engine=InnoDB default charset=utf8 collate=utf8_general_ci;
You can try use jQuery AJAX for what you want.
First, add this to your registration.php file
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// when user submit the form
$('form').on('submit', function(event){
$.ajax({
url: "check_username.php",
type: "POST",
dataType: "JSON",
data: {
username: $("#username").val() // get the value from username textbox
},
success: function(data){
if(data.status == "exists"){
alert('Username already existed');
}
else{
$('form').submit();
}
},
});
event.preventDefault();
});
</script>
So now your registration.php file will look like this
registration.php
<form action="" method="POST">
<p>
<label>name : </label>
<input id="password" type="text" name="name" placeholder="name" />
</p>
<p>
<label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" />
</p>
<p>
<label>E-Mail : </label>
<input id="password" type="email" name="email"/>
</p>
<p>
<label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" />
</p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Register" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// when user typing in 'username' textbox
$('form').on('submit', function(event){
$.ajax({
url: "check_username.php",
type: "POST",
dataType: "JSON",
data: {
username: $("#username").val() // get the value from username textbox
},
success: function(data){
if(data.status == "exists"){
alert('Username already existed');
}
else{
$('form').submit();
}
},
});
event.preventDefault();
});
</script>
Then create php file named check_username.php to check the username submitted by user if it is already existed in database or still available.
check_username.php
<?php
// Check if 'username' textbox is not empty
if(!empty($_POST['username'])){
$username = trim(mysqli_real_escape_string($_POST['username']));
// Check the database if the username exists
$query = "SELECT username FROM `user` WHERE username = '".$username."'";
$result = mysqli_query($query);
if(mysqli_num_rows($result) > 0){
// if username already exist
// insert into array, to be sent to registration.php later
$response['status'] = 'exists';
}
else{
// if username available
$response['status'] = 'available';
}
}
header('Content-type: application/json');
echo json_encode($response);
exit;
?>
Here is how it works:
1. When user click the register button, jQuery will call check_username.php.
2. Now in check_username.php it will check the database if the username submitted already exists or still available.
3. Whatever the result either exists or available, check_username.php will send the result back to registration.php as string contains 'exists' or 'available'.
4. registration.php now get the result and will check the result sent by check_username.php if it contain 'exists' or 'available'. If the string is 'exists' then alert will be triggered. If the string is 'available', the form will be submitted.
I'm using JQuery to call a php script which will add a record to the mySQL database.
This works fine for the first time I try to add something, but if I want to add more records to the database, it will not add anything. There are no errors in the console or php error log. It does not work if I refresh or reopen the page either.
jquery:
$(document).ready(function(){
$("#myForm").submit(function(){
var username = $("#username").val();
var password = $("#password").val();
var repassword = $("#repassword").val();
var email = $("#email").val();
var reemail = $("#reemail").val();
if(password != repassword)
{
alert("Passwords do not match");
return false;
}
else if(email != reemail)
{
alert("Emails do not match");
return false;
}
else {
$.post("signup_script.php",
{
username: username,
password: username,
email: email
});
}
});
});
php:
<?php
include_once('profile_Functions.php');
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
createUser($username,$password,$email);
?>
html:
<div class="body"></div>
<div class="grad"></div>
<div class="header">
<div>odd<span>job</span></div>
</div>
<br>
<div class="signup">
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script type = "text/javascript" src="js/js_functions.js"></script>
<form id ="myForm" action ="" method = "post" >
<input type="text" placeholder="username" id ="username" required = "required" maxlength = "15"><br>
<input type ="email" placeholder = "email" id = "email" required = "required" maxlength = "50"><br>
<input type ="email" placeholder = "re-enter email" id = "reemail" required = "required" maxlength = "50"><br>
<input type="password" placeholder="password" id="password" required = "required" pattern = "(?=.*\d)(?=.*[A-Z]).{10,}"><br>
<input type="password" placeholder="re-enter password" id ="repassword" required = "required"><br>
<p class = "passwordreq">Password must:</p>
<ol class = "passwordreq">
<li>Have 10 characters</li>
<li>Have one number</li>
<li>Have one uppercase letter</li>
</ol>
<input type="submit" value="sign up" id ="submit">
<input type="button" value="go back" onclick="window.location='index.html'">
</form>
insert function:
function setup(){
extract($_GET);
extract($_POST);
extract($_SERVER);
$host="localhost";
$user="root";
$passwd="";
$connect=mysql_connect($host,$user,$passwd) or die("error connecting mysql server");
mysql_select_db('oddjob',$connect) or die("error accessing db");
}
function createUser($name, $pass, $email){
setup();
$hashed_password = password_hash($pass, PASSWORD_DEFAULT);
$sql = "insert into profiles (UserName, Password, Email) values ('$name', '$hashed_password', '$email'); ";
$res = mysql_query($sql);
}
I wonder if the solution is related to this question: https://stackoverflow.com/a/6143475/652519.
Can you add the error function to your post function? Like so:
$.post("signup_script.php",
{
username: username,
password: username,
email: email
})
.error(function() { alert("error"); });
Then we can see if there are errors that happen upon insert in the DB.
You should close your connection each time
mysql_close($connect)
I need to create a form that will check it fills; if true, refresh itself after submit button is clicked.
viewing.php post to be display in earliest submission first with timestamp in descending order.
I have this connected to my local database to store and display data entered.
I have tried every code from forums and youtube but nothing works.
Below is the code:
index.php:
<style rel="stylesheet" type="text/css">
body {
left:20px;
font-size:15pt;
}
label, input, textarea{
left:20px;
margin:5px 5px 5px 5px;
font-size:15pt;
}
div {
width:50%;
background-color:lightgrey;
}
</style>
</head>
<body>
<div> <!--id="auto"-->
<form name="ajax" action="insert.php" method="post" id="contact">
<br>
<label>Please Enter Your Comments :</label>
<br><br>
<label>Name :<span>*</span>
<input type="text" name="Name" id="Name" value="" placeholder="Name" autocomplete="off"/>
</label>
<br>
<label>Enter Your Wishes : <span>*</span>
<br>
<textarea name="Comment" rows="10" cols="30" id="Comment" placeholder="Message" autocomplete="off"></textarea>
</label>
<br>
<input type="submit" value="Submit" onclick="aa();"/>
<input type="reset" value="Clear"/>
</form>
</div>
<script type="text/javascript">
location.refresh(true);
$('#contact').submit(function () {
sendContactForm();
return false;
});
</script>
</body>
</html>
insert.php:
<?php
session_start();
require 'config.php';
if(isset($_POST['Name'], $_POST['Comment'])){
$fields = [
'Name' => $_POST['Name'],
'Comment' => $_POST['Comment']
];
foreach ($fields as $field => $data) {
if (empty($data)){
$errors[] = 'The '.$field . ' field is required.';
}
}
}
else {
$errors[] = 'Error.';
}
// This function will run within each post array including multi-dimensional arrays
function ExtendedAddslash(&$params)
{
foreach ($params as &$var) {
// check if $var is an array. If yes, it will start another ExtendedAddslash() function to loop to each key inside.
is_array($var) ? ExtendedAddslash($var) : $var=addslashes($var);
unset($var);
}
}
// Initialize ExtendedAddslash() function for every $_POST variable
ExtendedAddslash($_POST);
$ID = $_POST['ID'];
$Name = $_POST['Name'];
$Comment = $_POST['Comment'];
/*$db_host = 'localhost:8889';
$db_username = 'root';
$db_password = 'root';
$db_name = 'Event';*/
mysql_connect( $db_host, $db_username, $db_password) or die(mysql_error());
mysql_select_db($db_name);
// search submission ID
$query = "SELECT * FROM 'demo' WHERE 'Name' = '$ID'";
$sqlsearch = mysql_query($query);
$resultcount = mysql_numrows($sqlsearch);
if ($resultcount > 0) {
mysql_query("UPDATE `demo` SET
`Name` = '$Name',
`Comment` = '$Comment',
WHERE `ID` = '$ID'")
or die(mysql_error());
} else {
mysql_query("INSERT INTO `demo` (ID, Name, Comment) VALUES ('$ID','$Name', '$Comment') ")
or die(mysql_error());
}
header('Location: index.php');
?>'
viewing.php:
<style rel="stylesheet" type="text/css">
body {
font-size:20pt;
}
</style>
<body>
<?php
require 'config.php';
$conn = mysqli_connect( $db_host, $db_username, $db_password, $db_name);
// Create connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Name, Comment FROM demo";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//echo "<table><tr><th>Name</th><th>Comment</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "<tr><td>".$row["Name"]." ".$row["Comment"]."</td></tr>";
echo "<fieldset>From : ".$row["Name"]."<br>".$row["Comment"]."<br></fieldset><br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
config.php:
<?php
/*Configuration Settings*/
$db_username = 'root';
$db_password = 'root';
$db_name = 'Event';
$db_host = 'localhost';
$port = 8889;
$socket = 'localhost:/Applications/MAMP/tmp/mysql/mysql.sock';
?>