I'm new to php, trying to make this simple form but I keep finding different examples of how to do it but they're all done with mysql and I've been told to switch to mysqli.
<html>
<head>
<title>
</title>
</head>
<body>
<form action="process.php" method="post">
<table>
<tr><th>Student Details</th></tr>
<tr>
<td><label for="student_name">Student Name</label></td>
<td><input type="text" name="student_name" id="student_name"/> </td>
</tr>
<tr>
<td><label for="student_email">Student Email</label></td>
<td><input type="email" name="student_email" id="student_email"/> </td>
</tr>
<tr>
<td><label for="student_city">Student City</label></td>
<td><input type="text" name="student_city" id="student_city"/> </td>
</tr>
<tr>
<td><button name= "submit"type="submit">Submit</button></td>
</tr>
</table>
</form>
</body>
</html>
Could someone please look at this code and tell me how to:
A) Avoid the following errors:
Undefined variable: insert in C:\Users\CEO\Google
Drive\Form\process.php on line 30
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
in C:\Users\CEO\Google Drive\Form\process.php on line 30
B) Apparently this form is a total security risk, what should I add to fix that?
<?php
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'college';
$conn = mysqli_connect($server, $user, $pass, $db); //Connect to Database
if(isset($_POST['submit'])){
$name = $_POST['student_name'];
$email = $_POST['student_email'];
$city = $_POST['student_city'];
if($name != "" || $email != "" || $city != ""){
$insert = "INSERT INTO students(student_name, student_email,student_contact) VALUES ('$name','$email','$city')";
$query = mysqli_query($conn,$insert);
echo "Data inserted";
}else{
echo "Failed to insert data";
}
}
if (!mysqli_query($insert, $conn)) {
die('Error: ' . mysqli_error($conn));
}
echo "1 record added";
mysqli_close($conn);
You assign to $insert inside the if block. But then you try to perform the query outside the if block. So if the if condition is not met, you'll still try to call mysqli_query(), but with an uninitialized variable. You should move that into the if.
if(isset($_POST['submit'])){
$name = $_POST['student_name'];
$email = $_POST['student_email'];
$city = $_POST['student_city'];
if($name != "" || $email != "" || $city != ""){
$insert = "INSERT INTO students(student_name, student_email, student_contact)
VALUES ('$name','$email','$city')";
if (mysqli_query($conn,$insert)) {
echo "Data inserted";
}else{
echo "Failed to insert data: " . mysqli_error($conn);
}
} else {
echo "You have to fill in name, email, or city";
}
}
But it's better to use prepared statements.
if(isset($_POST['submit'])){
$name = $_POST['student_name'];
$email = $_POST['student_email'];
$city = $_POST['student_city'];
if($name != "" || $email != "" || $city != ""){
$insert = mysqli_prepare("INSERT INTO students(student_name, student_email, student_contact)
VALUES (?, ?, ?)") or die(mysqli_error($conn));
mysqli_stmt_bind_param($insert, "sss", $name, $email, $city);
if (mysqli_stmt_execute($insert)) {
echo "Data inserted";
}else{
echo "Failed to insert data: " . mysqli_error($conn);
}
} else {
echo "You have to fill in name, email, or city";
}
}
Related
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
?>
wait please, dont post this as a duplicate because ive done research and tried everything but cant get it to work, i keep getting this error "Fatal error: Call to a member function prepare() on string in C:\wamp64\www\Etego\dbcontroller.php on line 63" i am trying to get people on my inscription form not to use the same email twice, thanks in advance! heres the code :
dbcontroller.php
<?php
class DBController {
public $host = "localhost";
public $user = "root";
public $password = "";
public $database = "members";
public $conn;
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
return $conn;
}
function runQuery($query) {
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
function numRows($query) {
$result = mysqli_query($this->conn,$query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
function updateQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query1: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function insertQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query2: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function deleteQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query3: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
}
/* Email already exists */
/*line 63*/
$db = new DBController;
$db->database->prepare("SELECT * FROM members WHERE email = ?");
$reqemail->execute(array($email));
$emailexist = $reqemail->rowCount();
if($emailexist == 0) {
} else {
$error_message = "Email already exists";
}
//end of email existance
?>
index2.php
<!-- how to make members when login "keep me signed in" and ho to make users 13+ with the date input -->
<?php
if(!empty($_POST["register-user"])) {
/* Form Required Field Validation */
foreach($_POST as $key=>$value) {
if(empty($_POST[$key])) {
$error_message = "All Fields are required";
break;
}
}
/* Password Matching Validation */
if($_POST['password'] != $_POST['confirm_password']){
$error_message = 'Passwords should be same<br>';
}
/* Email Validation */
if(!isset($error_message)) {
if (!filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL)) {
$error_message = "Invalid Email Address";
}
}
/* Validation to check if gender is selected */
if(!isset($error_message)) {
if(!isset($_POST["gender"])) {
$error_message = " All Fields are required";
}
}
/* Validation to check if Terms and Conditions are accepted */
if(!isset($error_message)) {
if(!isset($_POST["terms"])) {
$error_message = "Accept Terms and Conditions to Register";
}
}
if(!isset($error_message)) {
require_once("dbcontroller.php");
$db_handle = new DBController();
$query = "INSERT INTO members (username, firstname, lastname, password, email, gender, dob) VALUES
('" . $_POST["userName"] . "', '" . $_POST["firstName"] . "', '" . $_POST["lastName"] . "', '" . md5($_POST["password"]) . "', '" . $_POST["userEmail"] . "', '" . $_POST["gender"] . "' , '" . $_POST["dob"] . "' )";
$result = $db_handle->insertQuery($query);
if(!empty($result)) {
$error_message = "";
$success_message = "You have registered successfully!";
unset($_POST);
} else {
$error_message = "Problem in registration. Try Again!";
}
}
}
?>
<html>
<?php
include 'C:\wamp64\www\Etego\stylesignup.css';
?>
<head>
<title>https://Etego/signup.com</title>
</head>
<body>
<form name="frmRegistration" method="post" action="">
<table border="0" width="500" align="center" class="demo-table">
<?php if(!empty($success_message)) { ?>
<div class="success-message"><?php if(isset($success_message)) echo $success_message; ?></div>
<?php } ?>
<?php if(!empty($error_message)) { ?>
<div class="error-message"><?php if(isset($error_message)) echo $error_message; ?></div>
<?php } ?>
<tr>
<td>User Name</td>
<td><input type="text" class="demoInputBox allinsc" name="userName" value="<?php if(isset($_POST['userName'])) echo $_POST['userName']; ?>"></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" class="demoInputBox allinsc" name="firstName" value="<?php if(isset($_POST['firstName'])) echo $_POST['firstName']; ?>"></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" class="demoInputBox allinsc" name="lastName" value="<?php if(isset($_POST['lastName'])) echo $_POST['lastName']; ?>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" class="demoInputBox allinsc" name="password" value=""></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="password" class="demoInputBox allinsc" name="confirm_password" value=""></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" class="demoInputBox allinsc" name="userEmail" value="<?php if(isset($_POST['userEmail'])) echo $_POST['userEmail']; ?>"></td>
</tr>
<tr>
<td>Date Of birth</td>
<td><input type="date" value="<?php print(date("YYYY-MM-DD"))?>" class="demoInputBox" name="dob" value="<?php if(isset($_POST['dob'])) echo $_POST['dob']; ?>"></td>
</tr>
<tr>
<td>Gender</td>
<td><input type="radio" name="gender" value="Male" <?php if(isset($_POST['gender']) && $_POST['gender']=="Male") { ?>checked<?php } ?>> Male
<input type="radio" name="gender" value="Female" <?php if(isset($_POST['gender']) && $_POST['gender']=="Female") { ?>checked<?php } ?>> Female
<input type="radio" name="gender" value="not specified" <?php if(isset($_POST['gender']) && $_POST['gender']=="not specified") { ?>checked<?php } ?>> not specified
</td>
</tr>
<tr>
<td colspan=2>
<input type="checkbox" name="terms"> I accept Terms and Conditions <input type="submit" name="register-user" value="Register" class="btnRegister"></td>
</tr>
</table>
</form>
<div class="header1"></div>
<div class="hdetail1"></div>
<h class="etegotxt1">Etego</h>
<img src="Etego_Logo.png" alt="Etego logo" width="50" height="50" class="logo1">
</body></html>
There are a number of issues here:
Where you are trying to prepare a statement you are using $db->database->prepare() and if you look at your class the propery database it is a String containing the string members i.e. public $database = "members"; Which explains the error that is being reported
You also appear to have got the mysqli_ API and the PDO API confused and are using some PDO API functions, that will never work they are totally different beasts.
So also change this
/* Email already exists */
/*line 63*/
$db = new DBController;
$db->database->prepare("SELECT * FROM members WHERE email = ?");
$reqemail->execute(array($email));
$emailexist = $reqemail->rowCount();
if($emailexist == 0) {
} else {
$error_message = "Email already exists";
}
To
/* Email already exists */
/*line 63*/
$db = new DBController;
$stmt = $db->conn->prepare("SELECT * FROM members WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0) {
$error_message = "Email already exists";
}
and you will be using the connection object to prepare the query and all mysqli_ API functions, methods and properties.
UPDATE: Still getting dup accounts created
Your dup account check is in the wrong place in my opinion and should be moved into the index2.php.
Or after this line add a test against $error_message because you are forgetting to test if the Dup email check produced an error.
if(!isset($error_message)) {
require_once("dbcontroller.php");
if ( !isset($error_message) ) {
My strong suggestion would be to do the Dup Email check in index2 and remove it from dbconnect.php as it does not really belong in dbconnect.php as that would be run unnecessarily everytime you want to connect to a database in any script!
The thing is your $database variable is a string that does not have prepare() function. Instead you might want to use the $conn variable that is holding a valid database connection.
To do that, change
$db->database->prepare("SELECT * FROM members WHERE email = ?");
to
$stmt = $db->conn->prepare("SELECT * FROM members WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
Here is the PHP official documentation.
I have a problem, while am connecting phpmyadmin database from my php.
The below code is for form,
<div id="wb_element_instance53" class="wb_element">
<form class="wb_form wb_mob_form" method="post"><input type="hidden" name="wb_form_id" value="18498be5"><textarea name="message" rows="3" cols="20" class="hpc"></textarea>
<table>
<tr>
<th class="wb-stl-normal">Name </th>
<td><input type="hidden" name="wb_input_0" value="Name"><input class="form-control form-field" type="text" value="" name="wb_input_0" required="required"></td>
</tr>
<tr>
<th class="wb-stl-normal">Email </th>
<td><input type="hidden" name="wb_input_1" value="E-mail"><input class="form-control form-field" type="text" value="" name="wb_input_1" required="required"></td>
</tr>
<tr class="area-row">
<th class="wb-stl-normal">Message </th>
<td><input type="hidden" name="wb_input_2" value="Message"><textarea class="form-control form-field form-area-field" rows="3" cols="20" name="wb_input_2" required="required"></textarea></td>
</tr>
<tr class="form-footer">
<td colspan="2"><button type="submit" class="btn btn-default">Submit</button></td>
</tr>
</table>
</form>
<script type="text/javascript">
Then, i tried to connect phpmyadmin database using php code below,
<?php
/*
$connect=mysqli_connect('localhost','root','','Contact_db') ;
if(mysqli_connect_errno($connect))
{
echo 'Failed to connect';
}
// create a variable
if (isset($_POST['name'])) {
$name = $_POST['name'];
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
}
if (isset($_POST['message'])) {
$message = $_POST['message'];
}
$sql ="INSERT INTO contac_ds ('Name','email','message') VALUES ('$name','$email,'$message')";
//Execute the query
mysqli_query($connect,$sql);
?>
But, the above showing the error:
Notice: Undefined variable: name in this line "$sql ="INSERT INTO contac_ds ('Name','email','message') VALUES ('$name','$email,'$message')";"
Notice: Undefined variable: email in in this line "$sql ="INSERT INTO contac_ds ('Name','email','message') VALUES ('$name','$email,'$message')";"
Notice: Undefined variable: message in in this line "$sql ="INSERT INTO contac_ds ('Name','email','message') VALUES ('$name','$email,'$message')";"
What if the isset() fails??
Repair:
have a $sql only if the params are set..
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message']) ){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$sql ="INSERT INTO contac_ds ('Name','email','message') VALUES ('$name','$email,'$message')";
//Execute the query
mysqli_query($connect,$sql);
}
The problem is that $_POST search for name of the input. You name is wb_input_0, try this:
if (isset($_POST['wb_input_0'])) {
$name = $_POST['wb_input_0'];
}
And the same for email and message. However i would not advice to name inputs like that
try this:
$email ='';
$name ='' ;
$message ='';
print_r($_POST);//to review is all vars in form.
if (isset($_POST['name'])) {
$name = $_POST['name'];
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
}
if (isset($_POST['message'])) {
$message = $_POST['message'];
}
if (isset($_POST['name'])) {
$name = $_POST['name'];
}else{
$name = '';
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
}else{
$email = '';
}
if (isset($_POST['message'])) {
$message = $_POST['message'];
}else{
$message = '';
}
Do yourself a favour and prepare your statement:
$sql ="INSERT INTO contac_ds ('Name','email','message') VALUES (?,?,?)";
$stmt = mysqli_prepare($connect, $sql);
$name="";
if (isset($_POST['name'])) {
$name = $_POST['name'];
}
$email="";
if (isset($_POST['email'])) {
$email = $_POST['email'];
}
$message="";
if (isset($_POST['message'])) {
$message = $_POST['message'];
}
mysqli_stmt_bind_param($stmt,"sss",$name,$email,$message);
mysqli_stmt_execute($stmt);
Note that your current $_POST won't have those fields because your named them differently (and twice) so you also need to fix that.
I'm trying to execute an sql query that insert a record into a database on WAMP server, but when after pressing the submit button on form, that calls the php code, nothing happens. it just shows the message "Record insertion failed" i provided in the script. after trying and searching for a period of time, i'm unable to find WHERE IS THE ERROR IN QUERY. the code is give below:
<?php
$server="localhost";
$user="root";
$password="";
$database="dbname";
$con = mysqli_connect($server,$user,$password,$database);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//variables getting values from HTML form
if(isset($_POST['Submit-Personal'])){
$name = $_POST['name'];
$cnic = $_POST['cnic'];
$date = $_POST['booking-date'];
$ocassion = $_POST['ocassion'];
$address = $_POST['address'];
$phoneno = $_POST['phone-no'];
$bridemobile = $_POST['bride-mobile'];
$groommobile = $_POST['groom-mobile'];
$familymobile = $_POST['family-mobile'];
$email = $_POST['email'];
$refering = $_POST['refering'];
$share = $_POST['share'];
$permission = $_POST['permission'];
// attempt insert query execution
$qry = "insert into personal_detail (Name, CNIC, Date, Ocassion, Address,
Phone_No, Bride_Mobile, Groom_Mobile,
Family_Mobile,EMail,Referring,Share,Permission) values
('$name','$cnic','$date','$ocassion','$address','$phoneno','$bridemobile','$gro
ommobile','$familymobile','$email','$refering','$share','$permission')";
if(mysqli_query($con,$qry))
{
$message = "Record Saved Successfully";
echo "<script type='text/javascript'>alert('$message');</script>";
}
else
{
$message = "Record Insertion Failed!";
echo "<script type='text/javascript'>alert('$message');</script>";
}
I have another table it's working completely fine. Means saves records into the table if the entries in the form are made as required.To me the syntax of both is looking completely same, but don't why the one not working: the PHP code that' working fine for other table is given below:
<?php
$server="localhost";
$user="root";
$password="";
$database="camouflage_studio";
$con = mysqli_connect($server,$user,$password,$database);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){
$name = $_POST['name'];
$cn = $_POST['contact-number'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
//query
$qry = "insert into contact_us (Name,Contact_No,EMail,Subject,Message) values ('$name','$cn','$email','$subject','$message')";
if(mysqli_query($con,$qry))
{
$message = "Record Saved Successfully";
echo "<script type='text/javascript'>alert('$message');</script>";
}
else
{
$message = "Record Insertion Failed!";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
mysqli_close($con);
?>
#Muhammad Aatif here i have a similar example of your with same column and table name.
I have used mysqli_real_escape_string($conn, $_POST['name_of_form']) against SQL INJECTION to know more you can visit this site sql injection link
HERE IS THE HTML FORM CODE IN FILE NAME: INDEX.PHP
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<form action="process.php" method="post">
<p>enter name</p>
<input type="text" name="name"><br>
<p>enter cnic</p>
<input type="text" name="cnic"><br>
<p>enter data</p>
<input type="date" name="date"><br>
<p>enter Occassion</p>
<input type="text" name="ocassion"><br>
<p>enter Address</p>
<input type="text" name="address"><br>
<p>enter phone_no</p>
<input type="text" name="phone_no"><br>
<p>enter Bride mobil</p>
<input type="text" name="bride_mobile"><br>
<p>enter Groom mobile</p>
<input type="text" name="groom_mobile"><br>
<p>enter family mobile</p>
<input type="text" name="family_mobile"><br>
<p>enter email</p>
<input type="text" name="email"><br>
<p>enter Referring</p>
<input type="text" name="referring"><br>
<p>enter share</p>
<input type="text" name="share"><br>
<p>enter permission</p>
<input type="text" name="permission"><br>
<input type="submit" name="Submit-Personal"><br>
</form>
</body>
</html>
HERE IS THE PHP CODE IN FILE NAME: PROCESS.PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "demo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['Submit-Personal'])){
$name = mysqli_real_escape_string($conn, $_POST['name']);
$cnic = mysqli_real_escape_string($conn, $_POST['cnic']);
$date = mysqli_real_escape_string($conn, $_POST['date']);
$ocassion = mysqli_real_escape_string($conn, $_POST['ocassion']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$phone_no = mysqli_real_escape_string($conn, $_POST['phone_no']);
$bride_mobile = mysqli_real_escape_string($conn, $_POST['bride_mobile']);
$groom_mobile = mysqli_real_escape_string($conn, $_POST['groom_mobile']);
$family_mobile = mysqli_real_escape_string($conn, $_POST['family_mobile']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$referring = mysqli_real_escape_string($conn, $_POST['referring']);
$share = mysqli_real_escape_string($conn, $_POST['share']);
$permission = mysqli_real_escape_string($conn, $_POST['permission']);
$sql = "INSERT INTO personal_detail (Name,CNIC, Date,Ocassion,Address,Phone_No,Bride_Mobile,Groom_Mobile,Family_Mobile,EMail,Referring,Share,Permission) VALUES ('$name','$cnic','$date','$ocassion','$address','$phone_no','$bride_mobile','$groom_mobile', '$family_mobile','$email','$referring','$share','$permission')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
echo "<script type='text/javascript'>alert('sucess');</script>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
HERE IS THE OUTPUT RESULT
HERE IS THE TABLE IMAGE
FEEL FREE TO ASK MORE QUESTIONS
The proper way to prevent sql injection is to use MYSQLI->PREPARED STATEMENT CLICK ON THIS LINK TO GET BREIF DETAIL SQL INJECTION
i have made a registration from (followed e.g from w3schools.com) where they have used the $_SERVER["PHP_SELF"] in the action of form method.
$_SERVER["PHP_SELF"] this helps for validation part but it doesn't allow to insert data into db.
I have also written code for mobile no. where only numbers should be inserted but that is also not working.Please help.
<html>
<head>
<title>Meeting Room Application</title>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $mobErr = $uidErr = $pwdErr = $roleErr = "";
$txtname = $gender = $txtmob = $txteid = $txtuid = $txtpwd = $role = "";
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["txtname"])) {
$nameErr = "Name is required";
} else {
$txtname = test_input($_POST["txtname"]);
// check if name only contains letters and whitespace
if(!preg_match("/^[a-zA-Z ]*$/", $txtname)) {
$nameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["txteid"])) {
$emailErr = "Email is required";
} else {
$txteid = test_input($_POST["txteid"]);
// check if e-mail address is well-formed
if(!filter_var($txteid, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if(empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
if(empty($_POST["txtmob"])) {
$mobErr = "Mobile is required";
} else {
$txtmob = test_input($_POST["txtmob"]);
//check only numbers are given
if(preg_match("/^d{10}$/", $txtmob)) {
$mobErr = "Only numbers are allowed";
}
}
if(empty($_POST["txtuid"])) {
$uidErr = "User Id is required";
} else {
$txtuid = test_input($_POST["txtuid"]);
}
if(empty($_POST["txtpwd"])) {
$pwdErr = "Password is required";
} else {
$txtpwd = test_input($_POST["txtpwd"]);
}
if(empty($_POST["role"])) {
$roleErr = "Role is required";
} else {
$role = test_input($_POST["role"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<table align="center" cellpadding="5" cellspacing="5">
<tr>
<th colspan="2"><img src="Hitech Logo1.png" alt="HiTech"></th>
</tr>
<tr>
<th colspan="2"><h1>User Registration</h1></th>
</tr>
<tr>
<td colspan="2" align="left"><font color="red">All fields are mandatory</font></td>
</tr>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<tr>
<td>Full Name : </td>
<td><input type="text" name="txtname" value="<?php echo $txtname ?>"> <font color="red"><?php echo $nameErr; ?></td>
</tr>
<tr>
<td>Gender : </td>
<td><input type="radio" name="gender" <?php if(isset($gender) && $gender == "Male") echo "checked"; ?> value="Male">Male
<input type="radio" name="gender" <?php if(isset($gender) && $gender == "Female") echo "checked"; ?> value="Female">Female
<font color="red"><?php echo $genderErr; ?>
</td>
</tr>
<tr>
<td>Mobile No. : (+91)</td>
<td><input type="text" name="txtmob" maxlength="10" value="<?php echo $txtmob ?>">
<font color="red"><?php echo $mobErr; ?>
</td>
</tr>
<tr>
<td>Email Id : </td>
<td><input type="text" name="txteid" value="<?php echo $txteid ?>">
<font color="red"><?php echo $emailErr; ?>
</td>
</tr>
<tr>
<td>User Id : </td>
<td><input type="text" name="txtuid" value="<?php echo $txtuid ?>">
<font color="red"><?php echo $uidErr; ?>
</td>
</tr>
<tr>
<td>Password : </td>
<td><input type="password" name="txtpwd" value="<?php echo $txtpwd ?>">
<font color="red"><?php echo $pwdErr; ?>
</td>
</tr>
<tr>
<td>Role : </td>
<td><input type="radio" name="role" <?php if(isset($role) && $role == "User") echo "checked"; ?> value="User">User
<input type="radio" name="role" <?php if(isset($role) && $role == "Admin") echo "checked"; ?> value="Admin">Admin
<font color="red"><?php echo $roleErr; ?>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" name="btnsave">
</td>
</tr>
</form>
</tr>
</table>
<?php
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = ""; // Mysql password
$db_name = "testmra"; // Database name
// Connect to server and select databse.
$conn = mysqli_connect($host, $username, $password) or die("cannot connect");
mysqli_select_db($conn, $db_name);
$name = mysqli_real_escape_string($conn, $_POST['txtname']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$mobile = mysqli_real_escape_string($conn, $_POST['txtmob']);
$email = mysqli_real_escape_string($conn, $_POST['txteid']);
$username = mysqli_real_escape_string($conn, $_POST['txtuid']);
$userpass = mysqli_real_escape_string($conn, $_POST['txtpwd']);
$role = mysqli_real_escape_string($conn, $_POST['role']);
$res = mysqli_query($conn, "SELECT username FROM trialusers WHERE username='$username'");
$row = mysqli_fetch_row($res);
if($row > 0) {
echo "Username $username has already been taken";
} else {
$sql = "INSERT INTO newuser (name,gender,contactno,emailid,username,userpass,role)VALUES('$name','$gender','$mobile','$email','$username','$userpass','$role')";
if(mysqli_query($conn, $sql)) {
header("location:registration.php");
} else {
die('Error: Cannot connect to db');
}
}
?>
</body>
</html>
Change the last part of your code to this:
<?php
if(!empty($_POST)){
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="testmra"; // Database name
// Connect to server and select databse.
$conn=mysqli_connect($host,$username,$password) or die("cannot connect");
mysqli_select_db($conn,$db_name);
$name = mysqli_real_escape_string($conn, $_POST['txtname']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$mobile = mysqli_real_escape_string($conn, $_POST['txtmob']);
$email = mysqli_real_escape_string($conn, $_POST['txteid']);
$username = mysqli_real_escape_string($conn, $_POST['txtuid']);
$userpass = mysqli_real_escape_string($conn, $_POST['txtpwd']);
$role= mysqli_real_escape_string($conn, $_POST['role']);
$res=mysqli_query($conn,"SELECT username FROM trialusers WHERE username='$username'");
$row=mysqli_fetch_row($res);
if($row>0)
{
echo "Username $username has already been taken";
}
else
{
$sql="INSERT INTO newuser (name,gender,contactno,emailid,username,userpass,role)VALUES('$name','$gender','$mobile','$email','$username','$userpass','$role')";
if (mysqli_query($conn,$sql))
{
header("location:registration.php");
}
else
{
die('Error: Cannot connect to db' );
}
}
}
?>
This will trigger the data insert part only when you actually post data from the form and will remove the error you see. BTW the code you are using is outdated and use a mysql library that is deprecated. Please consider update to PDO
It is not always possible to receive a POST request on your page so keep your bottom PHP code into a condition
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="testmra"; // Database name
// Connect to server and select databse.
$conn=mysqli_connect($host,$username,$password) or die("cannot connect");
mysqli_select_db($conn,$db_name);
$name = mysqli_real_escape_string($conn, $_POST['txtname']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$mobile = mysqli_real_escape_string($conn, $_POST['txtmob']);
$email = mysqli_real_escape_string($conn, $_POST['txteid']);
$username = mysqli_real_escape_string($conn, $_POST['txtuid']);
$userpass = mysqli_real_escape_string($conn, $_POST['txtpwd']);
$role= mysqli_real_escape_string($conn, $_POST['role']);
$res=mysqli_query($conn,"SELECT username FROM trialusers WHERE username='$username'");
$row=mysqli_fetch_row($res);
if($row>0)
{
echo "Username $username has already been taken";
}
else
{
$sql="INSERT INTO newuser (name,gender,contactno,emailid,username,userpass,role)VALUES('$name','$gender','$mobile','$email','$username','$userpass','$role')";
if (mysqli_query($conn,$sql))
{
header("location:registration.php");
}
else
{
die('Error: Cannot connect to db' );
}
}
}