I am attempting a registration form that saves the data into a sql db. I'm not doing form validation just yet as what is most troubling me is getting this stuff onto sql. I'd appreciate any advice!!
I have a form.php file that should be doing the hard work. When I submit my form, at this point, I get a blank screen and nothing loads into the database.
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$password = $_POST['password'];
$email = $_POST['email'];
$cell = $_POST['cell'];
$experience = $_POST['experience'];
$ip = $_POST['ip'];
$password = md5($_POST['password']);
$connection = msql_connect(localhost, USERNAME, PASSWORD);
$db = mysql_select_db(registration,$connection);
mysql_query("INSERT INTO userTable (fname,lname,password,email,cell,experience,ip) VALUES ('$fname', '$lname', '$password', '$email', '$cell', '$experience', '$ip')")
or die (mysql_error());
echo "Thank you for your registration";
?>
And I have an html file that contains this:
<form method = "post" action = "form.php">
<h2>User Information</h2>
<div><label>First Name:</label>
<input type = "text" name = "fname"></div>
<div><label>Last Name:</label>
<input type = "text" name = "lname"></div>
<div><label>Password:</label>
<input type = "password" name = "password"></div>
<div><label>Email:</label>
<input type="text" name="email"></div>
<div><label>Cellphone:</label>
<input type="text" name="cell"></div>
<input type="hidden" name="ip" value='<?php echo $IP ?>'/>
<h2>What Is Your Experience Mountain Biking?</h2>
<p><input type="radio" name="experience" value="n00b"
checked>n00b
<input type="radio" name="experience" value="intermediate">Intermediate
<input type="radio" name="experience" value="extreme">Extreme
</p>
<p><input type="submit" name="submit" value="Register"></p>
</form>
Finally, I have a sql database (I'm running xampp locally) called "registration"
The table I've created is called "userTable" and it contains 8 fields including ID (auto incrementing) and the 7 other values I've included up top. Any idea what the heck I'm doing wrong?
What is the problem?
1) The problem is that it does INSERT query each time you load this page - mean each time it inserts empty values. Why?
Simply because there's no condition that checks if all fields has been posted, so instead of:
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$password = $_POST['password'];
$email = $_POST['email'];
$cell = $_POST['cell'];
$experience = $_POST['experience'];
$ip = $_POST['ip'];
You should check if $_POST super-global has some keys.
So before doing any queries - first of all check if $_POST isn't empty
<?php
//This means that user did submit the form
if ( !empty($_POST) ){
//all your stuff goes here
}
?>
<html>
.....
</html>
2) Are you sure you are in control of your code? Apparently not.
You MUST check if some function returned TRUE and then make following actions relying on it's one.
For example, are you sure that mysql_query("your sql query") was succeed at?
3) Enable error_reporting to E_ALL, so just put error_reporting(E_ALL) at the top of your page, like this:
<?php
error_reporting(E_ALL);
So that you can always debug your script "on fly"
4) You are doing everything to make this code hard to maintain, Why?
Look at this:
<?php
//Debug mode:
error_reporting(E_ALL);
//Sure you want to show some error if smth went wrong:
$errors = array();
/**
*
* #return TRUE if connection established
* FALSE on error
*/
function connect(){
$connection = mysql_connect(localhost, USERNAME, PASSWORD);
$db = mysql_select_db(registration,$connection);
if (!$connection || !$db ){
return false;
} else {
return true;
}
}
//So this code will run if user did submit the form:
if (!empty($_POST)){
//Connect sql server:
if ( !connect() ){
$errors[] = "Can't establish link to MySQL server";
}
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$password = $_POST['password'];
$email = $_POST['email'];
$cell = $_POST['cell'];
$experience = $_POST['experience'];
//Why post ip? not smth like $_SERVER['REMOTE_ADDR']...
$ip = $_POST['ip'];
$password = md5($_POST['password']);
//No error at this point - means that it successfully connected to SQL server:
if ( empty($errors) ){
//let's prevent sql injection:
$fname = mysql_real_escape_string($fname);
//Please do this for all of them..
}
//Now we should try to INSERT the vals:
$query = "INSERT INTO `userTable` (`fname`,`lname`,`password`,`email`,`cell`,`experience`,`ip`) VALUES ('$fname', '$lname', '$password', '$email', '$cell', '$experience', '$ip')";
//So try it:
if ( !mysql_query($query) ){
//
//die (mysql_error());
$errors[] = "Can't insert the vals";
} else {
//Or on success:
print ("Thank you for your registration");
//or you can do redirect to some page, like this:
//header('location: /thanks.php');
}
}
?>
<form method="post">
<h2>User Information</h2>
<div><label>First Name:</label>
<input type = "text" name = "fname"></div>
<div><label>Last Name:</label>
<input type = "text" name = "lname"></div>
<div><label>Password:</label>
<input type = "password" name = "password"></div>
<div><label>Email:</label>
<input type="text" name="email"></div>
<div><label>Cellphone:</label>
<input type="text" name="cell"></div>
<input type="hidden" name="ip" value='<?php echo $IP ?>'/>
<h2>What Is Your Experience Mountain Biking?</h2>
<p><input type="radio" name="experience" value="n00b"
checked>n00b
<input type="radio" name="experience" value="intermediate">Intermediate
<input type="radio" name="experience" value="extreme">Extreme
</p>
<?php if ( !empty($errors) ) : ?>
<?php foreach($errors as $error): ?>
<p><b><?php echo $error; ?></b></p>
<?php endforeach; ?>
<?php endif; ?>
<p><input type="submit" name="submit" value="Register"></p>
</form>
Solved my own problem
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$password = $_POST['password'];
$email = $_POST['email'];
$cell = $_POST['cell'];
$experience = $_POST['experience'];
$ip = $_POST['ip'];
$fname = mysql_real_escape_string($fname);
$lname = mysql_real_escape_string($lname);
$email = mysql_real_escape_string($email);
$password = md5($_POST['password']);
$servername="localhost";
$username="user";
$conn= mysql_connect($servername,$username, password)or die(mysql_error());
mysql_select_db("registration",$conn);
$sql="insert into userTable (fname,lname,password,email,cell,experience,ip) VALUES ('$fname', '$lname', '$password', '$email', '$cell', '$experience', '$ip')";
$result=mysql_query($sql,$conn) or die(mysql_error());
print "<h1>you have registered sucessfully</h1>";
echo "Thank you for your registration to the ";
mysql_close($connection);
?>
Related
I really can not find what am I doing wrong in my registration form, unfortunately the page is just reloading instead of inserting values from form to my DB table.
Register.php
<?php
require_once("./Connection.php");
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
$sql = "insert into agents (firstName, lastName, email, phone, password) value ('".$firstName."', '".$lastName."', '".$email."','".$phone."','".$hashPassword."')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Registration successfully";
}
}
?>
Connection.php
<?php
$conn = mysqli_connect("localhost","root","","KBHestate");
if(!$conn){
die("Connection error: " . mysqli_connect_error());
}
Register Form
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="text" name="firstName" value="" placeholder="First Name">
<input type="text" name="lastName" value="" placeholder="Surname">
<input type="text" name="email" value="" placeholder="Email">
<input type="text" name="phone" value="" placeholder="Phone">
<input type="password" name="password" value="" placeholder="Password">
<button type="submit" name="submit">Submit</button>
</form>
Please make sure the following line has no problem when it is interpreted by the PHP:
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
On the other hand, please make sure that the password field is wide enough to store the $hasPassword data
Your code looks fine, it should work. I am hoping you are having Register form in the same file Register.php
But as you mentioned it's just reload the page that means there must be a exception/error from mysql query that is not handled in your code.
You have not shared your table structure. So, I am answering you based on the common mistake.
Like one of your table column width is varchar(10) and you are trying to pass data of length 20 char.
So, i suggest you to add below code in your Register.php as the else condition for if($result). So, it will display the error if any.
else {
echo("Error description: " . $conn->error);
}
Now your Register.php code will be look like below:
<?php
require_once("./Connection.php");
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
$sql = "insert into agents (firstName, lastName, email, phone, password) value ('".$firstName."', '".$lastName."', '".$email."','".$phone."','".$hashPassword."')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Registration successfully";
}else {
echo("Error description: " . $conn->error);
}
}
?>
html webpage screenshotphp code shown on button clickmySql database tableI need to store user login data. i am using phpMyAdmin. When I click on submit button, data is not stored. Instead the php code is shown. Both code files are given below. What I am doing wrong. Help me. I
am unable to store user data using phpmyadmin in xampp.
my html code
<html>
<head>
<title>Yahoo Signin And Signup Form</title>
</head>
<body>
<h2 style="color: midnightblue">yahoo!</h2>
<hr color="magenta">
<form method="post" action="connect.php" >
<fieldset style="background:#6495ED;">
<legend style="padding:20px 0; font-size:20px;">Signup:</legend>
<label for ="firstName">Enter First Name</label><br>
<input type="text" placeholder="First name" id="firstName" name ="firstName">
<br>
<label for ="lastName">Enter Last Name</label><br>
<input type="text" placeholder="Last name" id="lastName" name ="lastName">
<br>
<label for ="email">Enter Email</label><br>
<input type="text" placeholder="Email" id="email" name ="email"><br>
<label for ="password">Enter Password</label><br>
<input type="password" placeholder="Password" id="password" name ="password">
<br>
<label for ="number">Enter Mobile Number</label><br>
<input placeholder="03---" id="number" name ="number"><br>
<label for ="date">Enter Date of Birth</label><br>
<input type="text" placeholder="DD/MM/YY" id="date" name ="date"><br>
<label for ="gender">Enter Gender</label><br>
<input type="text" placeholder="Male/Female/Other" id="gender" name
="gender"><br>
<br><button style="background-color:orangered;border-
color:dodgerblue;color:lightyellow">Signup</button>
</fielsdet>
</form>
</body>
</html>
my connect.php
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','phpdata');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password,
number, date, gender)
values(?,?,?,?,?,?,?)");
$stmt->bind_param("ssssiss",$firstName, $lastName, $email, $password,
$number, $date, $gender);
$stmt->execute();
echo "Sign up successful";
$stmt->close();
$con->close();
}?>
Use prepare instead of query. All everything is ok.:
$stmt = $con->prepare("INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values(?,?,?,?,?,?,?)");
And make button type as submit:
<br><button type="submit" style="background-color:orangered;border-color:dodgerblue;color:lightyellow">Signup</button>
here is the code, it works fine with me
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','phpdata');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values("'.$firstName.'","'.$lastName.'","'.$email.'","'.$password.'","'.$number.'","'.$date.'","'.$gender.'")");
if ($con->query($stmt) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$con->close();
}//end of else of connection
?>
Add type in your submit button.
<button type='submit' style="background-color:orangered;border-color:dodgerblue;color:lightyellow">Signup</button>
and also your question marks and params ara not matching. it should be match. otherwise data won't store your db
correct that line also
The main problem is you are not loading code via apache server try to open http://localhost/signup.html instead of C:/xmapp/htdocs/connect.php
It seems you want to user PDO but your connection string not correct
<?php
$firstName = trim($_POST['firstName']);
$lastName = trim($_POST['lastName']);
$email = trim($_POST['email']);
$password = md5(trim($_POST['password']));
$number = trim($_POST['number']);
$date = trim($_POST['date']);
$gender = trim($_POST['gender']);
$con= new PDO("mysql:host=127.0.0.1;dbname=phpdata", 'root', 'root');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqli = "INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values(?,?,?,?,?,?,?)";
try {
$stmt= $con->prepare($sqli);
$stmt->bindParam(1,$firstName);
$stmt->bindParam(2,$lastName);
$stmt->bindParam(3,$email);
$stmt->bindParam(4,$password);
$stmt->bindParam(5,$number);
$stmt->bindParam(6,$date);
$stmt->bindParam(7,$gender);
$status = $stmt->execute();
echo "Sign up successful";
$stmt->close();
$con->close();
} catch(PDOException $e) {
echo "Error ".$e->getMessage();
}
?>
another problem is with your html form button type is missing
<button type="submit".... />
Here is the complete code after analyzing it for a lot of time. in your $stmt variable there was no query, it was empty. This code works fine just copy and paste it.
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','abc');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$sql = "INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values('$firstName','$lastName','$email','$password','$number','$date','$gender')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
$con->close();
}//end of else of connection
?>
I am writing a form using php and mysql. The main goal is to make the form
(1) detect missing field.
(2) update user input after successful submit and
(3) most importantly to avoid re-submission on reload/refresh.
I am able to manage the first and the third one but doesn't have any idea on the second one.
Here's my code (able to achieve first and third)
form1.php
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
$name = "";
$class = "";
$school = "";
if(isset($_POST["submit"])){
$name = $_POST["name"];
$class = $_POST["class"];
$school = $_POST["school"];
$output = false;
if(empty($_POST["name"]) || empty($_POST["class"]) || empty($_POST["school"])){
echo 'field cannot be empty';
$output_form = true;
}
if(!empty($_POST["name"]) && !empty($_POST["class"]) && !empty($_POST["school"])){
$hostname = "localhost";
$admin = "root";
$password = "";
$database = "testdatabase";
$dbc = mysqli_connect($hostname, $admin, $password, $database) or die("database connection error");
$insert_query = "INSERT INTO `sorty` (`name`, `class`, `school`) VALUES ('$name', '$class', '$school')";
$insert_result = mysqli_query($dbc, $insert_query) or die("error");
if($insert_result == 1)
echo "data inserted";
else
echo "insert query failed";
mysqli_close($dbc);
header('Location: form2.php');
}
}
else
$output = true;
if($output){
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Name: <input type="text" name="name" value="<?php echo $name?>"/><br/>
Class: <input type="text" name="class" value="<?php echo $class?>"/><br/>
School: <input type="text" name="school" value="<?php echo $school?>"/><br/>
<input type="submit" value="submit" name="submit"/>
</form>
<?php
}
?>
</body>
</html>
My second file form2.php(succesful page after form submission)
<body>
Name: /*user input here*/<br/>
Class: /*user input here*/<br/>
School: /*user input here*/<br/>
As I can't access the variable $name, $class, $school of form.php I am having problem updating the user input data. So is there anyway to access the variable across file or is it not possible to do in this way.
user_name you may check this out. and read the code. i hope you will get the answer. You may add session for showing the message that the specified operation is done. thank you :)
I wanna update just one data from a record using php form but the thing is, when i do that, the rest of the data gets removed from the record.. What do i do :/ here are my codes for updating. What is the mistake i am making.. I am very confused. Would really appreciate some help.
<?php
include('db.php');
if(isset($_POST['update']))
{
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "winc sports";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
$id = $_POST['id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$country=$_POST['country'];
$phone=$_POST['phone'];
$email=$_POST['email'];
$select = "SELECT * FROM studens WHERE id = '$id'";
$selected = mysqli_query($connect, $select);
$row = mysqli_fetch_assoc($selected);
if (empty($_POST['fname'])) {$fname = $row['fname'];} else {$fname = $_POST['fname'];}
if (empty($_POST['country']))
{
$country = $row['country'];
}
else {
$country = $_POST['country'];
}
if (empty($_POST['id'])) {
$id = $row['id'];
}
else {
$id = $_POST['id'];
}
if (empty($_POST['age'])) {$age = $row['age'];} else {$age = $_POST['age'];}
if (empty($_POST['phone'])) {$phone = $row['phone'];} else {$phone = $_POST['phone'];}
if (empty($_POST['email'])) {$email = $row['email'];} else {$email = $_POST['email'];}
$query = "UPDATE students SET Fname= '$fname', Lname = '$lname', Nationality = '$country', PhoneNumber = '$phone', Email= '$email', Age = '$age' WHERE Id = '$id'";
$result = mysqli_query($connect, $query);
var_dump($result);
if($result)
{
echo 'Data Updated';
}else
{
echo 'Data Not Updated';
}
mysqli_close($connect);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP INSERT DATA USING PDO</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="updating.php" method="post">
<input type="text" name="id" placeholder="Enter new ID"><br><br>
<input type="text" name="fname" placeholder="Enter new First Name"><br><br>
<input type="text" name="lname" placeholder="Enter new Last Name"><br><br>
<input type="number" name="age" placeholder="Enter new age" min="13" max="90"><br><br>
<input type="text" name="country" placeholder="Enter new Nationality"><br><br>
<input type="number" name="phone" placeholder="Enter new Phone Number"><br><br>
<input type="text" name="email" placeholder="Enter new Email"><br><br>
<input type="submit" name="update" value="update">
</form>
</body>
</html>
The select statement is fetching data from a table called studens. This looks like a typo of the actual table so it won't actually fetch any results for you to update. Thus, the data you wind up updating the table with is empty. Rename the initial select table to students and it should properly fetch the data.
Also, please look into prepared statements or various other methods to sanitize inputs. Using POST variables directly in a query makes you extremely vulnerable to SQL Injection.
I'm sorry to ask such a narrow question, but I have this code in PHP and it is supposed to update a user's account. There is no error being returned and my IDE cannot identify the problem either. The problem is now that the code is not updating the database. I hope I can get some help on the subject.
Here is my PHP code:
<?php
session_start();
$con = mysqli_connect("mysql.serversfree.com", "u190182631_embo", "17011998embo", "u190182631_login");
$username = $_POST['user_name'];
$last = $_POST['lname'];
$first = $_POST['fname'];
$address = $_POST['address'];
$email = $_POST['email'];
$year = $_POST['year'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"UPDATE users SET last_name = '$last'
WHERE user_name = $_SESSION[user_name]");
mysqli_close($con);
}
?>
Any my HTML form if that is needed:
<form method="post" action="update.php">
Username: <input type="text" name="user_name" value="<?php echo $_SESSION['user_name']?>"><br><br>
Email: <input type="text" name="email" value="<?php echo $_SESSION['user_email']?>"><br><br>
Last Name: <input type="text" name="lname" value="<?php echo $_SESSION['last_name']?>"><br><br>
First Name: <input type="text" name="fname" value="<?php echo $_SESSION['first_name']?>"><br><br>
Street Address: <input type="text" name="address" value="<?php echo $_SESSION['address']?>"><br><br>
Year Graduated: <input type="text" name="year" value="<?php echo $_SESSION['year']?>"><br><br>
<input type="submit" value="Update Information"><br>
</form>
<form method="link" action="manage.php">
<input type = "submit" value = "Cancel"><br>
</form>
Any help would be great!
Try this - it will also help against SQL injection attacks:
$db = new mysqli("mysql.serversfree.com", "u190182631_embo", "17011998embo", "u190182631_login");
$username = $_POST['user_name'];
$last = $_POST['lname'];
$first = $_POST['fname'];
$address = $_POST['address'];
$email = $_POST['email'];
$year = $_POST['year'];
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = $db->prepare("UPDATE users SET last_name = ? AND WHERE user_name = ?;");
$stmt->bind_param("ss", $last, $_SESSION['user_name']);
$stmt->execute();
$stmt->close();
}
The big problem here is that you don't know how to debug the problem yourself, nor what information to include in a request for help.
There is no error being returned
How do you know? you don't check for any error from the query. Consider:
$upd="UPDATE users SET last_name = '$last'
WHERE user_name = $_SESSION[user_name]";
if (!mysqli_query($con,$upd)) {
print "query failed: $upd \n\n<br />" . mysqli_error();
}
You've shown a fragment of the code used to generate the form - but not what actually got sent to to the browser,
As Fred -ii- says, it seems very strange that $_SESSION[user_name] is not quoted in your SQL.
try this
mysqli_query($con,"UPDATE users SET last_name = '$last' WHERE user_name = {$_SESSION['user_name']}");
Update this line of code:
mysqli_query($con,"UPDATE users SET last_name = '$last'
WHERE user_name = $_SESSION[user_name]");
with the new one:
mysqli_query($con,"UPDATE users SET last_name = '$last'
WHERE user_name = $_SESSION['user_name']");
Hope it will work!