How to insert data to mysql using php - php

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' );
}
}
}

Related

How to join PHP with HTML forms to make a working page?

I stuck at creating a form that will work i.e. take user input and insert into DB.
I have a code, that i know works on its own. the PHP code when run bare with hard-coded values, works. FORM without PHP works.
When I put it all together, nope. I would really appreciate any input!
P.S. I know some names might be odd and it overall very simple, but I don't want to spend time on something that might not even work, and I really have to make it working, preferably yesterday.
HTML:
<?php require 'insert.php';?>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>Absolute classes registration</h2>
<p><span class = "error">* required field.</span></p>
<form method = "post" action = "<?php
echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>Username:</td>
<td><input type = "text" name = "username">
<span class = "error">* <?php echo $usernameErr;?></span>
</td>
</tr>
<tr>
<td>E-mail: </td>
<td><input type = "text" name = "email">
<span class = "error">* <?php echo $emailErr;?></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td> <input type = "text" name = "password">
<span class = "error"><?php echo $passwordErr;?></span>
</td>
</tr>
<td>
<input type = "submit" name = "submit" value = "Submit">
</td>
</table>
</form>
</body>
</html>
PHP:
<?php
require 'dbconn.php';
// define variables and set to empty values
$usernameErr = $emailErr = $passwordErr = "";
$username = $email = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$usernameErr = "Name is required";
}else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password required";
}else {
$password = test_input($_POST["password"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
}else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$sql = "INSERT INTO User_tbl (username, password, email) VALUES (:username, :password, :email)";
$stmt = $pdo->prepare($sql);
//$stmt->bindParam(':token',$token,PDO::PARAM_STR);
$stmt->bindParam(':username',$username,PDO::PARAM_STR);
$stmt->bindParam(':password',$password,PDO::PARAM_STR);
//$stmt->bindParam(':fname',$user_fname,PDO::PARAM_STR);
//$stmt->bindParam(':lname',$user_lname,PDO::PARAM_STR);
//$stmt->bindParam(':telephone',$user_telephone,PDO::PARAM_STR);
$stmt->bindParam(':email',$email,PDO::PARAM_STR);
//$token = '436546brty546b45y'; // generate unique token
$username = $_POST["username"];
$password = $_POST["password"]; //encrypt password
//$fname = $_POST['fname'];
//$lname = $_POST['lname'];
//$telephone = $_POST['telephone'];
$email = $_POST["email"];
$stmt->execute();
$stmt->close();
//header('location: welcome.php');
?>
Conn:
<?php
$servername = 'redacted';
$login = 'redacted';
$password = 'redacted';
$DBname = 'redacted';
// Establish database connection.
$pdo = new PDO("mysql:host=$servername;dbname=$DBname", $login, $password);
//print error or success
if ($pdo->connect_error) {
die("Connection failed."/* . $conn->connect_error*/);
}
if ($pdo) {
echo "Connected successfully";
}
?>

Problem showing a variable from 1 .php to another one

So, I have a problem when trying to modify only 1 user columns data in the database. The code I`ve made will only modify the data of the last user in the database and not the current user.
For example: I am logged on Asd account with the columns:
email username nume prenume tara
if i edit it,it will show the values on this one in the database but it will not show them on screen
if i have more users like asd abc abcd
it will show the values of abcd
<?php include('server.php');
$result = mysqli_query($db,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
if($username=$row['username'])
{
$email=$row['email'];
$user=$row['username'];
$nume=$row['nume'];
$prenume=$row['prenume'];
$tara=$row['tara'];
$oras=$row['oras'];
$adresa=$row['adresa'];
$numar=$row['numar'];
}
}
?>
<form method="post" action="editprofil.php">
<table class="table-fill">
<thead>
<tr>
<th class="text-left" style="font-size:32px;padding-bottom:1em;" >Profil</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-left">Username</td>
<td class="text-left"><?php echo $user ?></td>
</tr>
<tr>
<td class="text-left">Nume</td>
<td class="text-left"><input type="text" name="nume" /></td>
</tr>
<tr>
<td class="text-left">Prenume</td>
<td class="text-left"><input type="text" name="prenume" /></td>
</tr>
<tr>
<td class="text-left" >Email </td>
<td class="text-left"> <?php echo $email; ?></td>
</tr>
<tr>
<td class="text-left">Tara</td>
<td class="text-left"><input type="text" name="tara" /></td>
</tr>
<tr>
<td class="text-left">Oras</td>
<td class="text-left"><input type="text" name="oras" /></td>
</tr>
<tr>
<td class="text-left">Adresa</td>
<td class="text-left"><input type="text" name="adresa"/></td>
</tr>
<tr>
<td class="text-left">Telefon mobil</td>
<td class="text-left"><input type="text" name="telefon" /></td>
</tr>
<tr>
<td class="text-left">Data nasterii</td>
<td class="text-left"><input type="text" name="varsta" /></td>
</tr>
</tbody>
</table>
<div class="input-container"style="padding-top:1em;">
<input type="username" name="username" id="#{label}" />
<label for="#{label}">Confirm username</label>
<div class="bar"></div>
</div>
<div class="input-container"style="padding-top:1em;">
<input type="password" name="password" id="#{label}" />
<label for="#{label}">Confirm password</label>
<div class="bar"></div>
</div>
<div class="button-container">
<button type="submit" class="btn" name="edit_user">Register</button>
</div>
</form>
server.php
<?php
session_start();
$username = "";
$oras ="";
$nume ="";
$prenume ="";
$tara ="";
$adresa ="";
$telefon ="";
$varsta ="";
$email="";
$errors = array();
$db = mysqli_connect('localhost', 'root', '12345678', 'registration');
if (isset($_POST['reg_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
$user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO users (username, email, password)
VALUES('$username', '$email', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['success'] = "You are now logged in";
header('location: primapagina.php');
}
}
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['success'] = "You are now logged in";
header('location: primapagina.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
if (isset($_POST['edit_user']))
{
$oras = mysqli_real_escape_string($db, $_POST['oras']);
$tara = mysqli_real_escape_string($db, $_POST['tara']);
$adresa = mysqli_real_escape_string($db, $_POST['adresa']);
$nume = mysqli_real_escape_string($db, $_POST['nume']);
$prenume = mysqli_real_escape_string($db, $_POST['prenume']);
$telefon = mysqli_real_escape_string($db, $_POST['telefon']);
$varsta = mysqli_real_escape_string($db, $_POST['varsta']);
$password = md5(mysqli_real_escape_string($db, $_POST['password']));
$username = mysqli_real_escape_string($db, $_POST['username']);
$sql = "UPDATE users SET tara='$tara', oras='$oras', nume='$nume', prenume='$prenume', tara='$tara', adresa='$adresa' WHERE password = '$password' and username='$username' ";
mysqli_query($db, $sql);
}
?>
As # AKX wrote, when you type "$username = $row['username']", you're assigning the row's username into $username and always be true, executing the code inside the if all time for all your records. Here you will find more information PHP If PHP Expressions
As I can see in your code, You are fetching all the records from the users table, at the last iteration all the variable like $email, $user.... have the last row information that's why the code is updating the last user.

Fatal error: Call to a member function prepare() on string

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.

How to validate PHP Form input and database submittion

Am just getting my hand on php and I need some little help please. I am working on a registration form with server-side validation, then after validation, the form input should be submitted to the database. I entered data, click submit button, but the data were not submitted to the database. There is no error message. I like you to help me point out where have been wrong and give me a possible solution. Thanks.
Index.php
<?php
include ('signup.php');
?>
<div class="maindiv">
<div class="login"></div>
<div class="wrapper">
<div class="pageintro">
<p>PHP</p>
<p>PROJECT 1</p>
</div>
<div class="regform">
<form name="reg" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<p class="regformp">Fill all Fields</p>
<div class="regwrap">
<div class="inp">Full Name</div>
<div class="inp1"><input type="text" name="FullName" value="<?php echo $FullName; ?>"></div>
<span class="error"><?php echo $fullnameErr;?></span>
<div class="inp">E-Mail</div>
<div class="inp1"><input type="text" name="Email" value="<?php echo $Email; ?>"></div>
<span class="error"><?php echo $emailErr;?></span>
<div class="inp">Password</div>
<div class="inp1"><input type="password" name="Password"></div>
<span class="error"><?php echo $passwordErr;?></span>
<div class="inp">Confirm Password</div>
<div class="inp1"><input type="password" name="ConfirmPassword"></div>
<span class="error"><?php echo $conpasswordErr;?></span>
<div class="inp">Gender</div>
<div class="inp1"><input type="radio" name="Gender" value="Male" <?php if(isset($Gender)&& $Gender=="Male") echo "checked"; ?> >Male <input type="radio" name="Gender" <?php if(isset($Gender)&& $Gender=="Female") echo "checked"; ?> Value="Female">Female</div>
<span class="error"><?php echo $genderErr;?></span>
<div class="inp">Date Of Birth</div>
<div class="inp1"><select name="DayOfBirth"><option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option></select> <select name="MonthOfBirth"><option>Jan</option>
<option>Feb</option>
<option>Mar</option>
<option>Apr</option>
<option>May</option></select> <select name="YearOfBirth"><option>1970</option>
<option>1971</option>
<option>1972</option>
<option>1973</option>
<option>1974</option></select></div>
<span class="error"><?php echo $dobErr;?></span>
<span class="error"><?php echo $mobErr;?></span>
<span class="error"><?php echo $yobErr;?></span>
<div class="inp2"><input type="submit" name="submit" value="SIGN UP"></div></div>
</form>
signup.php
<?php
include ('project1db.php');
//Define variables
$fullnameErr="";
$emailErr="";
$passwordErr="";
$conpasswordErr="";
$genderErr="";
$dobErr="";
$mobErr="";
$yobErr="";
$FullName="";
$Email="";
$Password="";
$ConfirmPassword="";
$Gender="";
$DayOfBirth="";
$MonthOfBirth="";
$YearOfBirth="";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["FullName"])){
$fullnameErr = "Name is required";
}
else{
$FullName = test_input($_POST["FullName"]);
//Check if name only contains letters and whitespace
if(!preg_match("/^[a-zA-Z]*$/",$FullName)){
$fullnameErr = "Enter Valid name please!";
}
}
if(empty($_POST["Email"])){
$emailErr = "Email is required";
}else{
$EMail = test_input($_POST["Email"]);
//Check if e-mail address is correct
if(!filter_var($EMail, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email address";
}
}
if(empty($_POST["Password"])){
$passwordErr = "Password is required";
}else{
$Password = test_input($_POST["Password"]);
//Check password
if(!preg_match("/^[a-z0-9]{6,}$/",$Password)){
$passwordErr = "Password should contain 6+ characters, lowercase and numbers!";
}
}
if(empty($_POST["ConfirmPassword"])){
$conpasswordErr = "Confirm your Password!";
}
else{
$ConfirmPassword = test_input($_POST["ConfirmPassword"]);
//Confirm if password match
if($ConfirmPassword != $Password){
$conpasswordErr = "Password not match!";
}
}
if(empty($_POST["Gender"])){
$genderErr = "Select your Gender!";
}else{
$Gender = test_input($_POST["Gender"]);
}
if(empty($_POST["DayOfBirth"])){
$dobErr = "Select your Day Of Birth";
}else{
$DayOfBirth = test_input($_POST["DayOfBirth"]);
}
if(empty($_POST["MonthOfBirth"])){
$mobErr = "Select your Month Of Birth";
}else{
$MonthOfBirth = test_input($_POST["MonthOfBirth"]);
}
if(empty($_POST["YearOfBirth"])){
$yobErr = "Select your Year Of Birth";
}else{
$YearOfBirth = test_input($_POST["YearOfBirth"]);
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if($fullnameErr = $emailErr = $passwordErr = $conpasswordErr = $genderErr = $dobErr = $mobErr = $yobErr = ""){
$sql = "INSERT into usersignup (FullName, Email, Password, Gender, DayOfBirth, MonthOfBirth, YearOfBirth) VALUES(?,?,?,?,?,?,?)";
if($stmt = $conn->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("ssssisi", $FullName, $Email, $Password, $Gender, $DayOfBirth, $MonthOfBirth, $YearOfBirth);
/* Set the parameters values and execute
the statement again to insert another row */
$FullName = $_REQUEST['FullName'];
$Email = $_REQUEST['Email'];
$Password = $_REQUEST['Password'];
$Gender = $_REQUEST['Gender'];
$DayOfBirth = $_REQUEST['DayOfBirth'];
$MonthOfBirth = $_REQUEST['MonthOfBirth'];
$YearOfBirth = $_REQUEST['YearOfBirth'];
$stmt->execute();
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not prepare query: $sql. " . $conn->error;
}
// Close statement
$stmt->close();
// Close connection
$conn->close();
}
else{
}
?>
Database Connection
project1db.php
<?php
$dbhost = 'localhost:3308';
$dbuser = 'root';
$dbpass = '';
$dbname = 'phpproject';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(!$conn )
{
die('Could not connect: '.mysqli_error());
}
echo 'Connected successfully';
I have figured out the problem and the problem have been solved.
First problem is with the Mysql database. The AutoIncrement colunm precisely was not set to AutoIncrement. So, I open PhpMyadmin to alter and set the Id colunm to AutoIncrement.
Second Problem was with the conditional statement here:
if($fullnameErr = $emailErr = $passwordErr = $conpasswordErr = $genderErr = $dobErr = $mobErr = $yobErr = "")
The correct line of code which later worked properly is:
if(empty($fullnameErr) && empty($emailErr) && empty($passwordErr) && empty($conpasswordErr) && empty($genderErr) && empty($dobErr) && empty($mobErr) && empty($yobErr))
This is an important information for those who got confused after they have validated the data input but didn't know how to save the data into the database table.

Why won't the data from my php upload to my sql server?

I've started writing a community-based website with a login (user / pass / avatar etc.). All of these variables are being stored on a sql server so I can access them for the login, etc.
I've looked all over google, and my code seems sound, and my email validation is sent. But none of the data uploads to my sql database, so no users can be created.
I've included the code for my website below, with the connect info taken out for security reasons. Why aren't I able to write data to my database? Any help would be appreciated.
register.php
<?php require('top.php'); ?>
<div id="full">
<?php
$form = " <form action='register.php' method='post'>
<table cellspacing='10px'>
<tr>
<td></td>
<td>Required Feilds <font color='red'>*</font></td>
</tr>
<tr>
<td>First Name:</td>
<td><input type='text' name='firstname' class='textbox'><font color='red'>*</font></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type='text' name='lastname' class='textbox'><font color='red'>*</font></td>
</tr>
<tr>
<td>Username:</td>
<td><input type='text' name='username' class='textbox'><font color='red'>*</font></td>
</tr>
<tr>
<td>Email:</td>
<td><input type='text' name='email' class='textbox'><font color='red'>*</font></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password' class='textbox'><font color='red'>*</font></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type='password' name='repassword' class='textbox'><font color='red'>*</font></td>
</tr>
<tr>
<td>Avatar:</td>
<td><input type='file' name='avatar' > </td>
</tr>
<tr>
<td>Website Address:</td>
<td><input type='text' name='website' class='textbox'></td>
</tr>
<tr>
<td>YouTube Username:</td>
<td><input type='text' name='youtube' class='textbox'></td>
</tr>
<tr>
<td>Bio:</td>
<td><textarea name='bio' cols='35' rows='5' class='textbox'></textarea> </td>
</tr>
<tr>
<td></td>
<td><input type='submit' name='submitbtn' value='Register' class='button'></td>
</tr>
</table>
</form>";
if($_POST['submitbtn']) {
$firstname = strip_tags($_POST['firstname']);
$lastname = strip_tags($_POST['lastname']);
$username = strip_tags($_POST['username']);
$email = strip_tags($_POST['email']);
$password = strip_tags($_POST['password']);
$repassword = strip_tags($_POST['repassword']);
$website = strip_tags($_POST['website']);
$youtube = strip_tags($_POST['youtube']);
$bio = strip_tags($_POST['bio']);
$name = $_FILES['avatar']['name'];
$type = $_FILES['avatar']['type'];
$size = $_FILES['avatar']['size'];
$tmpname = $_FILES['avatar']['tmp_name'];
$ext = substr($name, strrpos($name, '.'));
if ($firstname && $lastname && $username && $email && $password && $repassword) {
if ($password == $repassword){
if ( strstr($email, "#") && strstr($email, ".") && strlen($email) >= 6) {
require('connect.php');
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$query = mysql_query("SELECT * FROM users WHERE email='$email'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$pass = md5(md5($password));
$date =date("F d, Y");
if ($name) {
move_uploaded_file($tmpname, "avatars/$username.$ext");
$avatar = "$username.$ext";
}
else
$avatar = "avatars/defavatar.png";
$code = substr(md5(rand (1111111111, 99999999999999999)), 2, 25);
mysql_query("INSERT INTO users VALUES ('','$firstname','$lastname,'$username','$email','$pass','$avatatar','$bio','$website','$youtube','','0','$code','0','$date')");
$webmaster = "email#email.com";
$subject = "Activate Your Account";
$headers = "From: a person <$webmaster>";
$message = "Hello $firstname. Welcome to awebsite.com Below is a link for you to activate your account.\n\n Click Here to Activate Your Account: http://awebsite.netii.net/activate.php?code=$code";
mail ($email, $subject, $message, $headers);
echo "Thank You for registering. To access your account please activate your account by folowing the link sent to <b>$email</b>. If you do not see the email in your inbox, check your junk mail as it may have been filtered. If you are expeiriencing any problems please contact the site administrator at <a href='mailto:email#email.com'>email#email.com</a>";
}
else
echo "That email is already taken. $form";
}
else
echo "That username is already taken. $form";
}
else
echo "You did not enter a valid email. $form";
}
else
echo "Your Passwords did not match. $form";
}
else
echo "You did not fill in all the required feilds. $form";
}
else
echo "$form";
?>
</div>
<?php require('bottom.php');?>
</div>
</body>
</html>
Activate.php
<?php $title = "Activate Your Account"; ?>
<?php require('top.php');?>
<div id="full">
<?php
$getcode =$_GET['code'];
$form = "<form action='activate.php' method='post'>
<table>
<tr>
<td>Activate Code:</td>
<td><input type='text' name='code' value='$getcode' size='30' </td>
</tr>
<tr>
<td>Username:</td>
<td><input type='text' name='username' </td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password' </td>
</tr>
<tr>
<td></td>
<td><input type='submit' name='submitbtn' value='Activate'</td>
</tr>
</table>
</form>";
if ($_POST['submitbtn']) {
$code = strip_tags($_POST['code']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
if ($code && $username && $password) {
if (strlen($code) == 25) {
$pass = md5(md5($password));
require('connect.php');
$query = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$pass'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$row = mysql_fetch_assoc($query);
$dbcode = $row['code'];
if ($code == $dbcode) {
mysql_query("UPDATE users SET active='1' WHERE username='$username'");
echo "Your account has been activated. You may now login. Click<a href='login.php'>here</a> to login.";
}
else
echo"Your activation code was incorrect. $form";
}
else
echo "Your username or password are invalid. $form";
}
else
echo "You have not supplied a valid code. $form";
}
else
echo "You did not fill out the entire form. $form";
}
else
echo "$form";
?>
</div>
<?php require('bottom.php');?>
connect.php
<?php
$server = "";
$dbuser = "";
$dbpass = "";
$database = "";
mysql_connect($server, $dbuser, $dbpass) or die("Unable to connect to $server");
mysql_select_db($database) or die( "Unable to select $database" );
?>
There is typo mistake in your code.
First we have to check if submit request is set or not, so => if($_POST['submitbtn']) should be,
if( isset($_POST['submitbtn']) ) {
...
}
Make change in code and check.
EDIT
You can reformat your code. Check for all variables not empty, use mysql escape instead of strip tags and don't use any escapes on password, only hash(md5).
if (isset($_POST['submitbtn'])) {
$code = mysql_real_escape_string($_POST['code']);
$username = mysql_real_escape_string($_POST['username']);
$password = md5($_POST['password']);
$errors = array();
if (empty($code) || empty($username) || empty($password)) {
$errors[] = "You did not fill out the entire form." . $form;
} elseif(strlen($code) !== 25) {
$errors[] = "You have not supplied a valid code." . $form;
} else {
// further code...
}
} else {
echo $form;
}
In register.php, change:
<form action='register.php' method='post'>
To:
<form action='register.php' method='post' enctype="multipart/form-data">
This is required to upload files using <input type="file" ...>.
You should not use $pass = md5(md5($password)); - It is just way to easy to crack. Instead look into crypt() - http://php.net/crypt
As this is new code, please consider changing from mysql_* functions to mysqli_* or PDO as PHP is depreciating mysql_* and this will save you time later.

Categories