Trying to insert data into my table but I keep getting an undefined index because there are "no value set when I submit my form". The if (isset($_POST['submit'])) removes my error even when I run the .php alone but no data is inserted when I submit my form. Any help is appreciated. Thank you
My form.html
<form name="supportForm" class="form" action="database.php" method="POST" onsubmit="return validateForm()">
<label>Name:</label>
<input type="text" name="name"/>
<br/>
<label>Client ID:</label>
<input type="text" name="clientID"/>
<br/>
<label>E-mail address:</label>
<input type="email" name="email"/>
<br/>
<label>Phone number:</label>
<input type="tel" name="tel"/>
<br/>
<br/>
Support Type:<br>
<input type="radio" name="suppType" value="Question/Inquiry">Question/Inquiry<br>
<input type="radio" name="suppType" value="Software">Software Issue<br>
<input type="radio" name="suppType" value="Hardware">Hardware Issue<br>
<input type="radio" name="suppType" value="Connectivity">Connectivity<br>
</br>
Operating System:
<select id="select">
<option disabled selected value="">Choose a product</option>
<option value="w7" name="OS">Windows 7</option>
<option value="w8" name="OS">Windows 8/8.1</option>
<option value="w10" name="OS">Windows 10</option>
</select>
<br> </br>
Problem Description:
<br><textarea id="ta" rows="10" cols="80" name="pDesc"></textarea></br>
<input type="checkbox" name="terms" value="agree">
I agree to the terms and conditions.
<br> </br>
<input type="hidden" name="submitted" value="true">
<input type="submit" name="submit" onClick="validateSubmit()">
</form>
My PHP file
<?php
//Creates static credentials
define('DB_NAME', 'data');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
//Creates connection to the database
$con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);
//Checks for connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
//If there are no connection, error
if (!$con) {
die ('Could not connect' . mysqli_error());
}
//Select the 'data' database
$con->select_db(DB_NAME);
//Checks if database 'data' has been selected
if (mysqli_select_db($con, DB_NAME)) {
echo "Database exists <br>";
} else {
echo "Database does not exist";
}
//Successful connection message
echo "Connected successfully <br>";
if (isset($_POST['submit'])) {
//Retrieving values from support form
$name = $_POST['name'];
$clientID = $_POST['clientID'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$suppType = $_POST['suppType'];
$OS = $_POST['OS'];
$pDesc = $_POST['pDesc'];
//Inserting values into a table
$sql = "INSERT INTO info (fullname, clientID, email, tel,
suppType, OS, pDesc)
VALUES ($name, $clientID, $email, $tel,
$suppType, $OS, $pDesc)";
if (!mysqli_query($con, $sql)) {
echo "No data";
} else {
echo "Data recorded successfully";
}
}
//Closes connection
mysqli_close($con);
You must write name="OS" in <select> not in <option>
<select id="select" name="OS">
<option disabled selected value="">Choose a product</option>
<option value="w7">Windows 7</option>
<option value="w8">Windows 8/8.1</option>
<option value="w10">Windows 10</option>
</select>
And Sql must be like this you need apostrophes ('') around variables
$sql = "INSERT INTO `info` (fullname, clientID, email, tel, suppType, OS, pDesc)
VALUES ('$name', '$clientID', '$email', '$tel', '$suppType', '$OS', '$pDesc')";
You not showing us the validateForm() function, therefore we won't really know whats happening there, nonetheless I have edited your form and did a validation using php,
what you need to do first is to check if all values are set before jumping to insert into db, and make sure email is a proper email, also the select option the name attribute needs to be on the select tag not on the option tag, the option must only have values.
Then Validate,Filter and sanitize user input before storing to the
database. Treat every userinput on your form as if its from a very dangerous hacker.
There's something called prepared statements, in mysqli and PDO you should try to learn that and use it :) you will enjoy it, I will leave it to you to research as to why you need to use prepared statements.
This is how your code should look
<form name="supportForm" class="form" action="database.php" method="POST">
<label>Name:</label>
<input type="text" name="name"/>
<br/>
<label>Client ID:</label>
<input type="text" name="clientID"/>
<br/>
<label>E-mail address:</label>
<input type="email" name="email"/>
<br/>
<label>Phone number:</label>
<input type="tel" name="tel"/>
<br/>
<br/>
Support Type:<br>
<input type="radio" name="suppType" value="Question/Inquiry">Question/Inquiry<br>
<input type="radio" name="suppType" value="Software">Software Issue<br>
<input type="radio" name="suppType" value="Hardware">Hardware Issue<br>
<input type="radio" name="suppType" value="Connectivity">Connectivity<br>
</br>
Operating System:
<select id="select" name="OS">
<option value="0">Choose a product</option>
<option value="w7">Windows 7</option>
<option value="w8">Windows 8/8.1</option>
<option value="w10">Windows 10</option>
</select>
<br> </br>
Problem Description:
<br>
<textarea id="ta" rows="10" cols="80" name="pDesc"></textarea>
</br>
<input type="checkbox" name="terms" value="agree">
I agree to the terms and conditions.
<br> </br>
<input type="hidden" name="submitted" value="true">
<input type="submit" name="submit">
</form>
Then database.php
<?php
//Creates static credentials
define('DB_NAME', 'data');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$errors = ""; //checking for errors
//Creates connection to the database
$con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);
//Checks for connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
//If there are no connection, error
if (!$con) {
die('Could not connect' . mysqli_error());
}
//Select the 'data' database
$con->select_db(DB_NAME);
//Checks if database 'data' has been selected
if (mysqli_select_db($con, DB_NAME)) {
echo "Database exists <br>";
} else {
echo "Database does not exist";
}
//Successful connection message
echo "Connected successfully <br>";
if (isset($_POST['submit'])) {
//check values are set
if (empty($_POST['name'])) {
echo "enter name";
$errors++;
} else {
$name = userIput($_POST['name']);
}
if (empty($_POST['clientID'])) {
echo "enter id";
$errors++;
} else {
$clientID = userIput($_POST['clientID']);
}
if (empty($_POST['email'])) {
echo "enter email";
$errors++;
} else {
$email = userIput($_POST['email']);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) { //validate email,
echo "enter valid email";
$errors++;
}
}
if (empty($_POST['tel'])) {
echo "enter tel";
$errors++;
} else {
$tel = userIput($_POST['tel']);
}
if (!isset($_POST['suppType'])) {
echo "select one option";
$errors++;
} else {
$suppType = userIput($_POST['suppType']);
}
if (isset($_REQUEST['OS']) && $_REQUEST['OS'] === "0") {
echo "please select product";
$errors++;
} else {
$OS = userIput($_POST['OS']);
}
if (empty($_POST['pDesc'])) {
echo "enter Description";
$errors++;
} else {
$pDesc = userIput($_POST['pDesc']);
}
if ($errors <= 0) { // No errors
//prepare and insert query
$sql = $con->prepare("INSERT INTO info (fullname, clientID, email, tel,suppType, OS, pDesc) VALUES (?, ?, ?, ?, ?, ?, ?)");
$sql->bind_param("sssssss", $name, $clientID, $email, $tel, $suppType, $OS, $pDesc);
if ($sql->execute()) {
echo "records inserted successfully";
} else {
echo "Could not insert " . mysqli_error();
}
$sql->close();
$con->close();
}
}
function userIput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Hope this will help a little, and you will learn a thing or two, and I'm always available for suggessions, just incase I missed something. Thanks
Related
Although everything looks fine in my program (e.g. register2.php), I have some syntax and binding issues. As it keeps throwing the error on line 73 even though the data successfully entered my database named "webprojadmin", and the table named "users".
here is my connected PDO database:
<?php
session_start();
$host = "127.0.0.1:3308";
$username = "root";
$password = "root";
$dbname = "webprojadmin";
$dsn = "mysql:host=$host;dbname=$dbname";
$optionen = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
// Create connection
$cxn = new PDO($dsn, $username, $password, $optionen);
// set the PDO error mode to exception
$cxn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Success: A proper connection to MySQL was made! The"." ".$dbname." "."database is great." . PHP_EOL;
//echo "Host URL: " . $host . PHP_EOL;
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
And here is my program, register2.php
<?php
require "dbcxn.php";
?>
<center>
<div>
<h1>Add a new web user account</h1>
<form action="" method="post">
<p>Full Name:<input type="text" name="fullname" placeholder="enter your full name"></p>
<p>Email:<input type="text" name="email" placeholder="enter your email address"></p>
<p>Password:<input type="password" name="pass" placeholder="enter passowrd"></p>
<p>Type<select name="utype">
<option value="FA">Academic, Faculty & Staff</option>
<option value="UG">Undergraduate Student</option>
<option value="PG">Postgraduate Student</option>
<option value="AU">Undergraduate Alumni</option>
<option value="AP">Postgraduate Alumni</option>
</select><p>
<p>Bio:<br><textarea id="textboxid" type="text" name="bio" placeholder="May you introduce to us, briefly?"></textarea></p>
<p>Awards:<br><textarea id="textboxid" type="text" name="awards" placeholder="Have you received any awards? If yes, what are they?"></textarea></p>
<p>Publications:<br><textarea id="textboxid" type="text" name="pub" placeholder="Have you published any written works? If yes, what are they?"></textarea></p>
<p>Thesis Topic:<br><textarea id="textboxid" type="text" name="ttopic" placeholder="What is the title of the Thesis you are doing/about to do/recently done?"></textarea></p>
<p>Thesis abstract:<br><textarea id="textboxid" type="text" name="tabstract" placeholder="If you have told the thesis topic, what is it about? Tell us briefly. If not, leave it blank."></textarea></p>
<p><input type="submit" name="btn_register" value="Create an account"/></p>
</form>
</div>
</center>
<?php
if (isset($_POST["btn_register"])) //button name "btn_register"
{
$fullname = strip_tags($_POST["fullname"]);
$email = $_POST["email"];
$pass = $_POST["pass"];
$utype = $_POST["utype"];
$bio = $_POST["bio"];
$awards = $_POST["awards"];
$pub = $_POST["pub"];
$ttopic = $_POST["ttopic"];
$tabstract = $_POST["tabstract"];
$sql = "INSERT INTO users (fullname, email, pass, utype, bio, awards, pub, ttopic, tabstract) VALUES ('$fullname', '$email', '$pass', '$utype', '$bio', '$awards', '$pub', '$ttopic', '$tabstract')";
echo ("<pre>\n".$sql."\n</pre>\n");
if(empty($fullname)) {
$errorMsg[]="Please enter username"; //check username textbox not empty
}
else if(empty($email)) {
$errorMsg[]="Please enter email"; //check email textbox not empty
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errorMsg[]="Please enter a valid email address"; //check proper email format
}
else if(empty($pass)) {
$errorMsg[]="Please enter password"; //check passowrd textbox not empty
}
else if(strlen($pass) < 6) {
$errorMsg[] = "Password must be atleast 6 characters"; //check passowrd must be 6 characters
}
else
{
try
{
$select_stmt=$cxn->prepare("SELECT fullname, email FROM users
WHERE fullname=:ufname OR email=:uemail"); // sql select query
$select_stmt->execute(array(':ufname'=>$fullname, ':uemail'=>$email)); //execute query
$row=$select_stmt->fetch(PDO::FETCH_ASSOC);
if($row["fullname"]==$fullname){
$errorMsg[]="Sorry username already exists"; //check condition username already exists
}
else if($row["email"]==$email){
$errorMsg[]="Sorry email already exists"; //check condition email already exists
}
else if(!isset($errorMsg)) //check no "$errorMsg" show then continue
{
$new_pass = password_hash($pass, PASSWORD_DEFAULT); //encrypt password using password_hash()
$query = "INSERT INTO users (fullname, email, pass, utype, bio, awards, pub, ttopic, tabstract) VALUES ('$fullname', '$email', '$pass', '$utype', '$bio', '$awards', '$pub', '$ttopic', '$tabstract')";
//$query2 = $sql;
//$query2run = $cxn->prepare($query2);
//$query2exec = $query2run->execute();
//$row=$query2run->fetch(PDO::FETCH_ASSOC);
$insert_stmt=$cxn->prepare("INSERT INTO users (fullname, email, pass, utype, bio, awards, pub, ttopic, tabstract) VALUES (:ufname,:uemail,:upass,:uutype,:ubio,:uawards,:upub,:uttopic,:utabstract)"); //sql insert query
if ($insert_stmt->execute(array( ':ufname' =>$fullname,
':uemail'=>$email,
':upass'=>$new_pass,
':uutype'=>$utype,
':upass'=>$bio,
':upass'=>$awards,
':upass'=>$pub,
':upass'=>$ttopic,
':upass'=>$tabstract))) {
$registerMsg = "Register Successfully..... Please Click On Login Account Link"; //execute query success message
header("refresh:1; index.php");
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
if(isset($errorMsg))
{
foreach($errorMsg as $error)
{
?>
<div>
<strong>WRONG ! <?php echo $error; ?></strong>
</div>
<?php
}
}
if(isset($registerMsg))
{
?>
<div>
<strong><?php echo $registerMsg; ?></strong>
</div>
<?php
}
?>
</section>
I cannot figure out what is wrong with my code. The data is not getting stored in phpmyadmin. may be its a syntax error.I ll be glad if someone could find the problem with my code. Please help me out on this!
It is a simple form asking for the details of the person who needs blood. I need the details to be stored into the database named 'blood_share_system' and the table name 'acceptors'.
my html file:
<form action="needblood.inc.php"method="post">
<fieldset>
<legend>Personal Information</legend>
<label>FirstName</label><br>
<input type="text"name="first"required><br>
<label>LastName</label><br>
<input type="text"name="last"required><br>
<label>PatientFirstName</label><br>
<input type="text"name="pfirst" required><br>
<lable>PatientLastName</label><br>
<input type="text"name="plast"<br>
</legend>
</fieldset>
<fieldset>
<legend>Contact Information</legend>
<lable>Phone Number</label><br>
<input type="tel"placeholder="10-digit PhoneNumber"name="phno" required><br>
<lable>Email Address</label><br>
<input type="email" placeholder="Valid email address"name="email"><br>
</fieldset>
<fieldset>
<legend>Blood Group Information</legend>
<label>Blood Group</label><br>
<select name="bgroup">
<option value="1">O-positive</option>
<option value="2">O-negative</option>
<option value="3">A-positive</option>
<option value="4">A-negative</option>
<option value="5">B-positive</option>
<option value="6">B-negative</option>
<option value="7">AB-positive</option>
<option value="8">AB-negative</option>
</select><br>
<label>Quantity required(1Unit:350ml):</label><br>
<button class="nbtn"id="snbtn"onclick="nbuttonClick()">-</button>
<input type="number" readonly="true" id="inc" value="0"name="quantity"required>
<button class="pbtn"id="sbtn"onclick="buttonClick()">+</button>Unit</h4><br>
<input type="number" id="result">ml
</fieldset>
<fieldset>
<legend>Location Details</legend>
<label>Locality</lable><br>
<input type="text"name="loc"required><br>
<label>Pincode</label><br>
<input type="number"name="pincode"required>
</fieldset>
<input type="submit" name="submit"value="Submit">
</form>
my php file:
<?php
//first if
if(isset($_POST['submit'])){
$dbserverName = "localhost";
$dbuserName = "root";
$dbpassword = "";
$dbname = "blood_share_system";
$conn = mysqli_connect( $dbserverName , $dbuserName , $dbpassword , $dbname);
//2nd if
if(!$conn){
echo "connection was not established with server";
}//2nd if close
//3rd if
if(!mysqli_select_db($conn,'blood_share_system')){
echo "not connected to the database";
}//3rd if close
$first=mysqli_real_escape_string($conn,$_POST['first']);
$last=mysqli_real_escape_string($conn,$_POST['last']);
$pfirst=mysqli_real_escape_string($conn,$_POST['pfirst']);
$plast=mysqli_real_escape_string($conn,$_POST['plast']);
$phno=mysqli_real_escape_string($conn,$_POST['phno']);
$email=mysqli_real_escape_string($conn,$_POST['email']);
$bgroup=mysqli_real_escape_string($conn,$_POST['bgroup']);
$quantity=mysqli_real_escape_string($conn,$_POST['quantity']);
$locality=mysqli_real_escape_string($conn,$_POST['loc']);
$pincode=mysqli_real_escape_string($conn,$_POST['pincode']);
if (!preg_match("/^[a-zA-Z]*$/" , $first) || !preg_match("/^[a-zA-Z]*$/" , $last)||!preg_match("/^[a-zA-Z]*$/" , $pfirst)||!preg_match("/^[a-zA-Z]*$/" , $plast) ){
trigger_error('Enter valid names!',E_USER_ERROR);
} else {
if(!preg_match("/^[0-9]{10}$/", $phno)){
trigger_error('Enter 10 digit phone number!');
} else{
if (!filter_var( $email , FILTER_VALIDATE_EMAIL )){
trigger_error('Enter valid email address!',E_USER_ERROR);
} else{
if(!preg_match("/^[0-9]{6}$/", $pincode)){
trigger_error('Enter valid pincode!',E_USER_ERROR);
} else {
$sql="INSERT INTO acceptors('$first','$last','$pfirst','$plast','$phno','$email','$bgroup','$quantity','$locality','$pincode');";
if(!mysqli_query($conn, $sql)){
echo "Not inserted";
} else {
echo"Inserted";
}
}
}
}
}
}
One of the possible cause is use of insert into statement instead of insert into... values statement.
If you are using insert into statement, then you need to provide all the column values in the correct order of the columns.
I am trying to log the users name, email, and region as well as their steamid via an html form.
The html form is here:
<form class="cptxt" action="/insert.php" method="post">
PUBG NAME: <input type="text" name="username" placeholder="Enter In Game
Name">
<br><br>
Email: <input type="text" name="email" placeholder="Enter Email"><br><br>
SteamID: <input type="text" name="sid" value="<?php echo
$steamprofile['steamid'] ?>" ><br><br>
SELECT REGION:
<select name="region">
<option value="NA">North America</option>
<option value="EU">Europe</option>
<option value="AS">Aisa</option>
<option value="OC">Oceianic</option>
</select> <br>
<br>
<input type="submit" value="Submit">
</form>
This is the insert.php file
<?php
require('connect.php');
include ('steamauth/userInfo.php');
if(!$con)
{
echo "NOT CONNECTED";
}
if(!mysqli_select_db($con,'pubgfinder'))
{
echo "db not selected";
}
$Name = $_POST['username'];
$Email = $_POST['email'];
$Sid = $_POST['sid']
$Region = $_POST['region'];
$sql = "INSERT INTO users (Name,Email,Region,Sid) VALUES
('$Name','$Email','$Region','$Sid')";
if(!mysqli_query($con,$sql))
{
echo "NOT INSERTED";
}
else
{
echo "INSERTED";
}
header("refresh:2; url=home.php");
?>
So far what I get is the form working, besides the steamid part of it. It writes the steamid into the form field as well, but doesn't send to the database.
Please help. Am I writing this wrong? What's the issue here?
I am facing problems connecting my HTML form to database. I am very new at this. Please do help me.
This is the HTML Login form code
logout.html
<form name="form" onsubmit="submit1()" action="connectivity-sign-up.php" method="POST" >
<div id="errorBox"></div>
<input type="text" name="Name" value="" placeholder="First Name" class="input_name" >
<input type="text" name="LastName" value="" placeholder="Last Name" class="input_name" >
</div>
<div id="email_form">
<input type="text" name="Email" value="" placeholder="Your Email" class="input_email">
</div>
<div id="Re_email_form">
<input type="text" name="enterEmail" value="" placeholder="Re-enter Email" class="input_Re_email">
</div>
<div id="password_form">
<input type="password" name="Password" value="" placeholder="New Password" class="input_password">
</div>
<!--birthday details start-->
<div>
<h3 class="birthday_title">Birthday</h3>
</div>
<div>
<select name="birthday_month" >
<option value="" selected >Month</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
</select>
<select name="birthday_day" >
<option value="" selected>Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<select name="birthday_year">
<option value="" selected>Year</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
</select>
</div>
<!--birthday details ends-->
<div id="radio_button">
<input type="radio" name="radiobutton" value="Female">
<label >Female</label>
<input type="radio" name="radiobutton" value="Male">
<label >Male</label>
</div>
<div>
<p id="sign_user" onClick="Submit()" value= "Submit" >Sign Up </p>
<input type="submit" value="Submit">
</div>
</form>
The Submit1() function is the validate function. When I click Submit it should first validate and then send the data to the form. Now the validate function works properly but how do I call it such that it will send the data once validated.And here is the PHP connectivity part
File name : connectivity-sign-up.php
<?php define('DB_HOST', 'localhost');
define('DB_NAME', 'customerdb');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
function Signin()
{
$fname = $_POST['Name'];
$lname = $_POST['LastName'];
$email = $_POST['Email'];
$password = $_POST['Password'];
$query = "INSERT INTO custtable (fname,lname,email,password) VALUES ('$fname','$lname','$email','$password')";
$data = mysql_query ($query)or die(mysql_error());
if($data)
{
echo "YOUR REGISTRATION IS COMPLETED...";
}
}
?>
When user click submit button call Signin() function.
if (isset($_POST['submit'])) {
Signin();
}
-
<?php define('DB_HOST', 'localhost');
define('DB_NAME', 'customerdb');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db = mysql_select_db(DB_NAME, $con) or die("Failed to connect to MySQL: " . mysql_error());
if (isset($_POST['submit'])) {
Signin();
}
function Signin()
{
$fname = $_POST['Name'];
$lname = $_POST['LastName'];
$email = $_POST['Email'];
$password = $_POST['Password'];
$query = "INSERT INTO custtable (fname,lname,email,password) VALUES ('$fname','$lname','$email','$password')";
$data = mysql_query($query) or die(mysql_error());
if ($data) {
echo "YOUR REGISTRATION IS COMPLETED...";
}
}
?>
Update html : <input type="submit" name="submit" value="Submit">
<!--birthday details ends-->
<div id="radio_button">
<input type="radio" name="radiobutton" value="Female">
<label>Female</label>
<input type="radio" name="radiobutton" value="Male">
<label>Male</label>
</div>
<div>
<p id="sign_user" onClick="Submit()" value="Submit">Sign Up </p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
When click Sign Up, the information will be send to connectivity-sign-up.php, and execute the code in connectivity-sign-up.php. And Signin() is not invoked, there is just a declare.
<?php define('DB_HOST', 'localhost');
define('DB_NAME', 'customerdb');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
function Signin()
{
$fname = $_POST['Name'];
$lname = $_POST['LastName'];
$email = $_POST['Email'];
$password = $_POST['Password'];
$query = "INSERT INTO custtable (fname,lname,email,password) VALUES ('$fname','$lname','$email','$password')";
$data = mysql_query ($query)or die(mysql_error());
if($data)
{
echo "YOUR REGISTRATION IS COMPLETED...";
}
}
//invoke Signin
Signin();
?>
If you remove the method declaration for Signin() and just have the entire page as a script, then the logic you have in the function will execute. This would result in the following file:
<?php define('DB_HOST', 'localhost');
define('DB_NAME', 'customerdb');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
$fname = $_POST['Name'];
$lname = $_POST['LastName'];
$email = $_POST['Email'];
$password = $_POST['Password'];
$query = "INSERT INTO custtable (fname,lname,email,password) VALUES ('$fname','$lname','$email','$password')";
$data = mysql_query ($query)or die(mysql_error());
if($data)
{
echo "YOUR REGISTRATION IS COMPLETED...";
}
?>
Another alternative is to actually call the function somewhere in the page like so:
Signin()
The better option would be executing the Signin() function somewhere in the page.And you would need to add a connetion between the connectivity-sign-up.php and logout.html file
I am trying to make Sign Up Now! area for a restaurant website and want to insert data of new members in the members_t table of database members with all running on localhost. I am using PHP and HTML for the purpose. Moreover, I am doing form validation using javaScript in a separate file which is working perfectly!
Code for PHP:
<?php
$user="root";
$password="";
$database="members";
$con = mysql_connect('localhost',$user,$password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con) or die( "Unable to select database");
if(isset($_POST['sign_up']) && !empty($_POST['sign_up']))
{
$sql = "INSERT INTO members_t('Name', 'Email', 'Password', 'Phone', 'Address', 'Sex', 'More') VALUES('".$_POST['username']."','".$_POST['email']."','".$_POST['passid_1']."','".$_POST['zip']."','".$_POST['address']."','".$_POST['sex']."','".$_POST['desc']."');";
$resultDI = mysql_query($sql, $con) or die(mysql_error());
mysql_close($con);
echo "Successfolly run database query!";
}
else
{
echo("Failed to update database!!!");
}
?>
Code for HTML:
<html>
<body>
<h2 class="letter_spacing">Not a Member?<span><br>Sign Up Now:</br></span></h2>
<form id = "register" name="registration" method = "post" onSubmit="return formValidation();">
<ul>
<li><label for="username">* Full Name:</label></li>
<li><input type="text" name="username" size="50" /></li>
<li><label for="email">* Email:</label></li>
<li><input type="text" name="email" size="50" /></li>
<li><label for="passid_1">* Desired Password:</label></li>
<li><input type="password" name="passid_1" size="12" /></li>
<li><label for="passid_2">* Re-Enter Password:</label></li>
<li><input type="password" name="passid_2" size="12" /></li>
<li><label for="zip">* Contact Number:</label></li>
<li><input type="text" name="zip" /></li>
<li><label for="address">* Address:</label></li>
<li><input type="text" name="address" size="50" /></li>
<li><label id="gender">* Sex:</label></li>
<li><input type="radio" name="msex" value="Male" /><span>Male</span></li>
<li><input type="radio" name="fsex" value="Female" /><span>Female</span></li>
<li><label for="desc">Anything More:</label></li>
<li><textarea name="desc" id="desc" cols="40" rows="4"></textarea></li>
<li><label for="note" ><h6>Note: All feilds marked with * are necessary</h6></label></li>
<li><input class="button1" type="submit" name="sign_up" value="Sign Up!" /></li>
</ul>
</form>
</body>
</html>
I have tried to keep the code in a separate file called insert.php and added the action field to the HTML form tag yet of no use.
I am never able to insert data into the database. It seems the PHP code never goes into the
if(isset($_POST['sign_up']) && !empty($_POST['sign_up']))
block.
Try this:
<form id="register" action="" method="post" name="registration" onSubmit="return formValidation();">
<input type="text" name="username" size="50" />
<input type="text" name="email" size="50" />
<input type="password" name="passid_1" size="12" />
<input type="password" name="passid_2" size="12" />
<input type="text" name="zip" />
<input type="text" name="address" size="50" />
<input type="radio" name="sex" value="Male" /><span>Male</span>
<input type="radio" name="sex" value="Female" /><span>Female</span>
<textarea name="desc" id="desc" cols="40" rows="4"></textarea>
<input class="button1" type="submit" name="sign_up" value="Sign Up!" />
</form>
<?php
if (isset($_POST['sign_up']) && !empty($_POST['sign_up'])) {
// escape all submitted data before inserting into database
foreach ($_POST as $key => $value) {
$_POST[$key] = mysql_real_escape_string(strip_tags($value));
}
$result = mysql_query("
INSERT INTO members_t (Name, Email, Password, Phone, Address, Sex, More)
VALUES ('{$_POST['username']}', '{$_POST['email']}', '{$_POST['passid_1']}', '{$_POST['zip']}', '{$_POST['address']}', '{$_POST['sex']}', '{$_POST['desc']}')
") or die(mysql_error());
if (mysql_affected_rows() == 1) {
echo "Successfully run database query!";
} else {
echo("Failed to update database!!!");
}
}
?>
Note that name of the radio buttons should be the same "sex" not "msex" and "fsex" as in your code. And I have added the action attribute in the form tag plus some other modifications you can easily notice.
First of all, i have cleaned up the code a little so it looks nice and smooth. Then i have removed the !empty part you made, cant see the reason why you want to verify that it actually is empty when you already used isset.
HTML:
<?php
$hostname = "";
$user = "root";
$password = "";
$database = "members";
$desc = $_POST['desc'];
$con = mysql_connect($hostname, $user, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con) or die( "Unable to select database");
if(isset($_POST['sign_up']))
{
if(isset($_POST['username'])){
$username = $_POST['username'];
}
else {
echo "The username is not set"; die;
}
if(isset($_POST['email'])){
$email = $_POST['email'];
}
else {
echo "The email is not set"; die;
}
if(isset($_POST['zip'])){
$zip = $_POST['zip'];
}
else {
echo "The zip code is not set"; die;
}
if(isset($_POST['address'])){
$address = $_POST['address'];
}
else {
echo "The gender is not set"; die;
}
if(isset($_POST['sex'])){
$sex = $_POST['sex'];
}
else {
echo "The gender is not set"; die;
}
if(isset($_POST['passid_1'])){
$passid = $_POST['passid_1'];
}
else {
echo "The password is not set"; die;
}
if(isset($_POST['passid_2'])){
$passid2 = $_POST['passid_2'];
}
else {
echo "The re-entered password is not set"; die;
}
if($passwid == $passid2){
$correctpid = $passwid;
}
else {
echo "The passwords do not match"; die;
}
$sql = "INSERT INTO members_t('Name', 'Email', 'Password', 'Phone', 'Address', 'Sex', 'More') VALUES('$username', '$email','$correctpid', '$zip', '$address', '$sex', '$desc');";
mysql_query($sql) or die(mysql_error());
mysql_close($con);
echo "Successfolly run database query!";
}
else
{
echo("Failed to update database!!!");
}
?>
I have made the php code to check if all the fields are filled with data. If not the site die and gives them a error message. It kills the website before it can set anything into the database.
-- I made some more changes to the code after comments, thanks btw.