Trouble inserting a new user into a mysql database - php

I have a form that allows me to enter a user into my database. However, whenever I click on submit I receive the query failed error message. Below is my the form I have built:
register-admin.php
<form id="resgisterform" name="registerform" method="post" action="register-admin-exec.php">
<table width="300" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<th>Username </th>
<td><input name="username" type="text" class="textfield" id="username" /></td>
</tr>
<tr>
<th>First Name </th>
<td><input name="first_name" type="text" class="textfield" id="first_name" /></td>
</tr>
<tr>
<th>Last Name </th>
<td><input name="last_name" type="text" class="textfield" id="last_name" /></td>
</tr>
<tr>
<th>Muvdigital Email </th>
<td><input name="muvdigital_email" type="text" class="textfield" id="muvdigital_email" /></td>
</tr>
<tr>
<th>Personal Email </th>
<td><input name="personal_email" type="text" class="textfield" id="personal_email" /></td>
</tr>
<tr>
<th>Title </th>
<td><input name="title" type="text" class="textfield" id="title" /></td>
</tr>
<tr>
<th>Address 1 </th>
<td><input name="address_1" type="text" class="textfield" id="address_1" /></td>
</tr>
<tr>
<th>Address 2 </th>
<td><input name="address_2" type="text" class="textfield" id="address_2" /></td>
</tr>
<tr>
<th>City </th>
<td><input name="city" type="text" class="textfield" id="city" /></td>
</tr>
<tr>
<th>State </th>
<td><input name="state" type="text" class="textfield" id="state" /></td>
</tr>
<tr>
<th>Zip Code </th>
<td><input name="zip" type="text" class="textfield" id="zip" /></td>
</tr>
<tr>
<th>Phone </th>
<td><input name="phone" type="text" class="textfield" id="phone" /></td>
</tr>
<tr>
<th>Password </th>
<td><input name="password" type="password" class="textfield" id="password" /></td>
</tr>
<tr>
<th>Confirm Password </th>
<td><input name="cpassword" type="password" class="textfield" id="cpassword" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Register" /></td>
</tr>
</table>
</form>
The values from this form are then brought over to the register-admin-exec.php page which is below
<?php
//Start session
session_start();
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//define and validate the post values
/*if (isset ($_POST['admin_id']) && !empty ($_POST['admin_id'])) {
$admin_id = $_POST['admin_id'];
} else {
echo 'Error: admin id not provided!';
}*/
if (isset ($_POST['username']) && !empty ($_POST['username'])) {
$username = clean($_POST['username']);
} else {
echo 'Error: username not provided!';
}
if (isset ($_POST['first_name']) && !empty ($_POST['first_name'])) {
$first_name = clean($_POST['first_name']);
} else {
echo 'Error: first name not provided!';
}
if (isset ($_POST['last_name']) && !empty ($_POST['last_name'])) {
$last_name = clean($_POST['last_name']);
} else {
echo 'Error: last name not provided!';
}
if (isset ($_POST['muvdigital_email']) && !empty ($_POST['muvdigital_email'])) {
$muvdigital_email = clean($_POST['muvdigital_email']);
} else {
echo 'Error: muvdigital email not provided!';
}
if (isset ($_POST['personal_email']) && !empty ($_POST['personal_email'])) {
$personal_email = clean($_POST['personal_email']);
} else {
echo 'Error: personal email not provided!';
}
if (isset ($_POST['title']) && !empty ($_POST['title'])) {
$title = clean($_POST['title']);
} else {
echo 'Error: title not provided!';
}
if (isset ($_POST['phone']) && !empty ($_POST['phone'])) {
$phone = clean($_POST['phone']);
} else {
echo 'Error: phone not provided!';
}
if (isset ($_POST['address_1']) && !empty ($_POST['address_1'])) {
$address_1 = clean($_POST['address_1']);
} else {
echo 'Error: address 1 not provided!';
}
$address_2 = clean($_POST['address_2']);
if (isset ($_POST['city']) && !empty ($_POST['city'])) {
$city = clean($_POST['city']);
} else {
echo 'Error: city not provided!';
}
if (isset ($_POST['state']) && !empty ($_POST['state'])) {
$state = clean($_POST['state']);
} else {
echo 'Error: state not provided!';
}
if (isset ($_POST['zip']) && !empty ($_POST['zip'])) {
$zip = clean($_POST['zip']);
} else {
echo 'Error: zip not provided!';
}
if (isset ($_POST['password']) && !empty ($_POST['password'])) {
$password = clean($_POST['password']);
} else {
echo 'Error: password not provided!';
}
if (isset ($_POST['cpassword']) && !empty ($_POST['cpassword'])) {
$cpassword = clean($_POST['cpassword']);
} else {
echo 'Error: confirm password not provided!';
}
//encrypt the password
$salt = sha1($username);
$password = sha1($salt.$password);
//Check for duplicate login ID
if($username != '') {
$qry = "SELECT * FROM members WHERE username='".$username."'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
$errmsg_arr[] = 'Login ID already in use';
$errflag = true;
}
#mysql_free_result($result);
}
else {
die("Query failed");
}
}
//If there are input validations, redirect back to the registration form
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: register-admin.php");
exit();
}
//Create INSERT query
$qry = "INSERT INTO admins (
'username',
'password',
'first_name',
'last_name',
'muvdigital_email',
'personal_email',
'titles',
'phone',
'address_1',
'address_2',
'city',
'state',
'zip')
VALUES (
'$username',
'$password',
'$first_name',
'$last_name',
'$muvdigital_email',
'$personal_email',
'$title',
'$phone',
'$address_1',
'$address_2',
'$city',
'$state',
'$zip')";
$result = mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: register-success.php");
exit();
}else {
die("Query failed $qry");
}
?>
I know it is failing at my insert statement because I have tried commenting out the previous validation check for duplicate login ids and it still fails. I cannot figure out why my insert statement isn't working. After echoing the $qry, i get
INSERT INTO admins ( 'username', 'password', 'first_name', 'last_name', 'muvdigital_email', 'personal_email', 'titles', 'phone', 'address_1', 'address_2', 'city', 'state', 'zip') VALUES ( 'johndoe', '7afbb2186cf26d85bdfe948d367fb6baa6739283', 'john', 'doe', 'john.doe#muvdigital.com', 'jdoe#gmail.com', 'intern', '6024013776', '18b main st', 'apt 12', 'Hooksett', 'NH', '03106')
so the $_POST function is working. I have tried manually entering the insert statement at the command line and i receive ERROR 1054 (42S22): Unknown column 'johndoe' in 'field list'.
The admin_id is an auto_increment field which is why I have commented it out (and I have tried uncommenting it and manually creating an admin_id, which stil does not work)
Anyone have an idea as to why this is happening?

You have quoted all your column names with single quotes, which is incorrect. They should be unquoted, except if you have used a MySQL reserved keyword (which you have not)
// Column names are unquoted, but VALUES() should be quoted.
$qry = "INSERT INTO admins (
username,
password,
first_name,
last_name,
muvdigital_email,
personal_email,
titles,
phone,
address_1,
address_2,
city,
state,
zip)
VALUES (
'$username',
'$password',
'$first_name',
'$last_name',
'$muvdigital_email',
'$personal_email',
'$title',
'$phone',
'$address_1',
'$address_2',
'$city',
'$state',
'$zip')";
$result = mysql_query($qry);

Related

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.

Registration error messages

In my registration page when you forget to fill your username you receives this message: "Please insert a username", when you forget to fill the password then you receives this message: "Please insert a password" or when you forget to fill the email then you receives this message: "Please insert a email" as you can see in the code bellow.
<?php
include"header"
if(isset($_POST["register"])){
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(($username) == ""){
?><p><?php echo "Please insert a username"; ?></p><?php
}
if(($password) == ""){
?><p><?php echo "Please insert a password"; ?></p><?php
}
if(($email) == ""){
?><p><?php echo "Please insert a email"; ?></p><?php
}
else{
$checkusername = mysql_query("SELECT `id` FROM `user` WHERE `username` = '".$username."'") or die(mysql_error());
$checkemail = mysql_query("SELECT `id` FROM `user` WHERE `email` = '".$email."'") or die(mysql_error());
if(mysql_num_rows($checkusername) == 1){
?><p><?php echo "Username already exists"; ?></p><?php
}
if(mysql_num_rows($checkemail) == 1){
?><p><?php echo "Email already exists"; ?></p><?php
}
else{
mysql_query("INSERT INTO `database`.`user`(`username`,`password`,`email`) VALUES ('".$username."','".$password."','".$email."')") or die(mysql_error());
?><p><?php echo "You are Registered"; ?></p><?php
}
}
}
?>
<div id="loginform">
<form name="loginform" method="post">
<table cellpadding="0" id="tb">
<tr>
<td colspan="2"><div class="loginheader"><h2>Register</h2></div></td>
</tr>
</table>
<table cellpadding="0" id="REGOPTIONS">
<tr>
<td class="field">Username:</td>
<td><input type="text" class="text" name="username"></td>
</tr>
<tr>
<td class="field">Password:</td>
<td><input type="password" class="text" name="password"></td>
</tr>
<tr>
<td class="field">Email:</td>
<td><input type="email" class="text" name="email"></td>
</tr>
</table>
<table cellpadding="0">
<tr>
<td class="field"></td>
<td><input type="submit" class="submitbutton" name="register" value="Register" /></td>
</tr>
</table>
</form>
</div>
But my registration page can only display one error message at a time. I need my page to display all of them at once if you forget to fill your informations (username, password and email) at the same time like that:
"Please insert a username"
"Please insert a password"
"Please insert a email"
Transformed into an array. Try:
<?php
if(isset($_POST["register"])){
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if (!empty($username) && !empty($password) && !empty($email)){
$checkusername = mysql_query("SELECT `id` FROM `user` WHERE `username` = '".$username."'") or die(mysql_error());
$checkemail = mysql_query("SELECT `id` FROM `user` WHERE `email` = '".$email."'") or die(mysql_error());
if(mysql_num_rows($checkusername) == 1){
?><p><?php echo "Username already exists"; ?></p><?php
}
if(mysql_num_rows($checkemail) == 1){
?><p><?php echo "Email already exists"; ?></p><?php
}
else{
mysql_query("INSERT INTO `database`.`user`(`username`,`password`,`email`) VALUES ('".$username."','".$password."','".$email."')") or die(mysql_error());
?><p><?php echo "You are Registered"; ?></p><?php
}
} else{
if(empty($username)){
$error[] = "Please insert a username";
}
if(empty($password)){
$error[] = "Please insert a password";
}
if(empty($email)){
$error[] = "Please insert a email";
}
foreach ($error as $value) {
echo "Erros: $value<br />\n";
}
}
}
?>
<div id="loginform">
<form name="loginform" method="post">
<table cellpadding="0" id="tb">
<tr>
<td colspan="2"><div class="loginheader"><h2>Register</h2></div></td>
</tr>
</table>
<table cellpadding="0" id="REGOPTIONS">
<tr>
<td class="field">Username:</td>
<td><input type="text" class="text" name="username"></td>
</tr>
<tr>
<td class="field">Password:</td>
<td><input type="password" class="text" name="password"></td>
</tr>
<tr>
<td class="field">Email:</td>
<td><input type="email" class="text" name="email"></td>
</tr>
</table>
<table cellpadding="0">
<tr>
<td class="field"></td>
<td><input type="submit" class="submitbutton" name="register" value="Register" /></td>
</tr>
</table>
</form>
</div>
What I normally do is run through my form validation, and save each error (is there is one) to an array.
ie
$la_errors = array();
if(($username) == ""){
$la_errors[] = "Please insert username";
}
//etc. Then
if(!empty($la_errors)) {
break;
}
When you need to display the errors, explode the array, and display in a format (like or whatever) of your choice

PHP not writing in MySQL database

I have an HTML page with input fields where I'm using PHP to validate and eventually write into my MySQL Database called 'fantasymock'. If validation is successful, the user is directed to an empty page called thankyou.php (using for testing purposes), which I am being directed to. But unfortunately, the data is not being written into the database.
I've looked on the web and previous SO posts and don't see a similar situation likes mines. Can someone look at it and possibly find the issue? Code is somewhat long and apologize. Thank you.
<?php
// define variables and set to empty values
$emailErr = $userErr = $passwordErr = $cpasswordErr = $firstErr = $lastErr = $teamErr = "";
$userid = $email = $username = $password = $cpassword = $firstname = $lastname = $teamname = "";
// The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//Validates email
if (empty($_POST["email"])) {
$email = NULL;
$emailErr = "You Forgot to Enter Your Email!";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
$email = NULL;
$emailErr = "You Entered An Invalid Email Format";
}
}
//Validates Username
if (empty($_POST["username"])) {
$username = NULL;
$userErr = "You Forgot to Enter Your Username!";
} else {
$username = test_input($_POST["username"]);
}
//Validates password & confirm passwords.
if (empty($_POST["cpassword"])) {
$password = NULL;
$cpassword = NULL;
$passwordErr = "You Forgot To Enter Your Password!";
}
if(!empty($_POST["password"]) && ($_POST["password"] == $_POST["cpassword"])) {
$password = test_input($_POST["password"]);
$cpassword = test_input($_POST["cpassword"]);
if (strlen($_POST["password"]) < '7') {
$password = NULL;
$passwordErr = "Your Password Must Contain At Least 8 Characters!";
}
elseif(!preg_match("#[0-9]+#",$password)) {
$password = NULL;
$passwordErr = "Your Password Must Contain At Least 1 Number!";
}
elseif(!preg_match("#[A-Z]+#",$password)) {
$password = NULL;
$passwordErr = "Your Password Must Contain At Least 1 Capital Letter!";
}
elseif(!preg_match("#[a-z]+#",$password)) {
$password = NULL;
$passwordErr = "Your Password Must Contain At Least 1 Lowercase Letter!";
}
}
elseif(!empty($_POST["password"])) {
$password = NULL;
$cpassword = NULL;
$passwordErr = "Please Check You've Entered Or Confirmed Your Password Correctly!";
}
//Validates firstname
if (empty($_POST["firstname"])) {
$firstname = NULL;
$firstErr = "You Forgot to Enter Your First Name!";
} else {
$firstname = test_input($_POST["firstname"]);
//Checks if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
$firstname = NULL;
$firstErr = "You Can Only Use Letters And Whitespaces!";
}
}
if (empty($_POST["lastname"])) {
$lastname = NULL;
$lastErr = "You Forgot to Enter Your Last Name!";
} else {
$lastname = test_input($_POST["lastname"]);
//Checks if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
$lastname = NULL;
$lastErr = "You Can Only Use Letters And Whitespaces!";
}
}
if (empty($_POST["teamname"])) {
$teamname = NULL;
$teamErr = "You Forgot to Enter Your Team Name!";
} else {
$teamname = test_input($_POST["teamname"]);
}
if ($email && $username && $password && $cpassword && $firstname && $lastname && $teamname) {
mysql_connect("localhost", "root", "");
#mysql_select_db("fantasymock") or die("Unable To Connect To the Database");
//Variable used for the primary key in User Table in Database.
$userid = $_POST['userid'];
$email = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$teamname = $_POST['teamname'];
$query = "INSERT INTO user VALUES ('$userid', '$email', '$password', '$cpassword', '$firstname', '$lastname', '$teamname')";
mysql_query($query);
mysql_close();
header("Location: thankyou.php");
die();
} else {
echo '<p align="center"><strong>Errors on page</strong><br><br></p>';
}
}
/*Each $_POST variable with be checked by the function*/
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!--The htmlspecial() function prevents from hackers inserting specific characters in fields with malicious intent-->
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table align="center" border="1" bordercolor="black" bgcolor="white" cellpadding="5" cellspacing="0" width="50%">
<tr>
<td>
<table align="center" bordercolor="white" border="0" cellpadding="5" cellspacing="0">
<tr>
<td align="center" colspan="2"><strong>Registration</strong></b></td>
</tr>
<tr>
<td colspan="2"><br></td>
</tr>
<tr>
<td align="right" width="20%">E-mail:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="email" maxlength="50" size="30" placeholder=" email" value="<?php echo $email;?>"</td>
</tr>
<tr>
<td colspan="2" align="center"><span class="error"><?php echo $emailErr;?></td>
</tr>
<tr>
<td align="right" width="20%">Username:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="username" maxlength="50" size="30" placeholder=" username" value="<?php echo $username;?>"></td>
</tr>
<tr>
<td colspan="2" align="center"><span class="error"><?php echo $userErr;?></td>
</tr>
<tr>
<td align="right" width="20%">Password:</td>
<td align="left" width="30%"><input class="largeTextBox" type="password" name="password" maxlength="50" size="30" placeholder=" password" value="<?php echo $password;?>"></td>
</tr>
<tr>
<td colspan="2" align="center"><span class="error"><?php echo $passwordErr;?></td>
</tr>
<tr>
<td align="right" width="20%">Confirm Password:</td>
<td align="left" width="30%"><input class="largeTextBox" type="password" name="cpassword" maxlength="50" size="30" placeholder=" confirm password" value="<?php echo $cpassword;?>"></td>
</tr>
<tr>
<td colspan="2" align="center"><span class="error"><?php echo $cpasswordErr;?></td>
</tr>
<tr>
<td align="right" width="20%">First Name:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="firstname" maxlength="50" size="30" placeholder=" first name" value="<?php echo $firstname;?>"></td>
</tr>
<tr>
<td colspan="2" align="center"><span class="error"><?php echo $firstErr;?></td>
</tr>
<tr>
<td align="right" width="20%">Last Name:</td>
<td align="left"><input class="largeTextBox" type="text" name="lastname" maxlength="50" size="30" placeholder=" last name" value="<?php echo $lastname;?>"></td>
</tr>
<tr>
<td colspan="2" align="center"><span class="error"><?php echo $lastErr;?></td>
</tr>
<tr>
<td align="right" width="20%">Team Name:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="teamname" maxlength="50" size="30" placeholder=" team name" value="<?php echo $teamname;?>"></td>
</tr>
<tr>
<td colspan="2" align="center"><span class="error"><?php echo $teamErr;?></td>
</tr>
<tr>
<td colspan="2" align="center"><hr/></td>
</tr>
<tr>
<td colspan="2" align="center"><input class="bigButton" type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</td>
</tr>
</table>
</form>
You should check if your query was succesfull or not. if not show the error.
if (!mysql_query($query))
{
die('Invalid query: ' . mysql_error());
}
And in your database, are all the columns strings(varchar) or are there also integers because if so you wont succeed .
like this
$userid = $_POST['userid'];
i assume userid is a integer but you just assign it from post to var this var will be a string.
in order to get a integer you should something like this
$userid = $_POST['userid'];
$userid+=0;
And if your primary key is set to auto-increment you should not insert anything to that column. It will be done automaticlally
This probably won't solve the problem you're having but hopefully it helps.
try the query as
"INSERT INTO user (`email`,`password`,`cpassword`,`firstname`,`lastname`,`teamname`)VALUES
('$email', '$password', '$cpassword', '$firstname', '$lastname', '$teamname')"
let the db driver handle assigning the id using auto increment.
You should also be aware you have some nasty sql injection vulnerabilities
I noticed you aren't handling MySQL errors. After you call a query, you should always have some kind of error checking. For mysql you should use mysql_error. For example:
$query = "INSERT INTO user VALUES ('$userid', '$email', '$password', '$cpassword', '$firstname', '$lastname', '$teamname')";
mysql_query($query);
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
That should tell you your error.

Connect form to my SQL database?

I am trying to have this form submit to a database but I am having no luck. I am a complete newbie and based this code off another form that is already in use. Can anyone spot errors that would make it not work properly? Any help would be huge.
<?php
include("includes/captcha.php");
if (!empty($_POST['submitcontestant'])) {
$addcontestantsql = "INSERT INTO ".$config['db_dbpaper'].".contest (company, name, address, phone)";
$company = mysql_real_escape_string($_POST['company']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
$captcha = mysql_real_escape_string($_POST['captcha']);
<?php
include("includes/captcha.php");
if (!empty($_POST['submitcontestant'])) {
$addcontestantsql = "INSERT INTO ".$config['db_dbpaper'].".contest (company, name, address, phone)";
$company = mysql_real_escape_string($_POST['company']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
$captcha = mysql_real_escape_string($_POST['captcha']);
$addcontestantsql .= " VALUES('$company', '$name', '$email', '$phone')";
$allowed = false;
if (empty($company) && empty($name) && empty($address) && empty ($email) && empty($phone)) {
echo '<strong>Please go back and fill out all the fields!</strong>';
}
elseif ($captcha != $captchaans) {
echo '<strong>CAPTCHA incorrect!</strong>';
}
else {
$allowed = true;
echo '<strong>You are in the contest!</strong>';
}
if ($allowed) {
db_exec($addcontestantql);
}
}
?>
<?php
$companysql = "SELECT DISTINCT company FROM ".$config['db_dbpaper'].".contest ";
$mainsql = "SELECT * FROM ".$config['db_dbpaper'].".contest ";
if (!empty($_POST['submit'])) {
$companyname = mysql_real_escape_string($_POST['company']);
$mainsql .= "WHERE company like '$companyname'";
}
$company = db_list($companysql);
$contest = db_list($mainsql);
?>
<div id="fullwidthpage">
<h2>Contest</h2>
<p>Please fill the out form and then click submit. Thank you.</p>
<form method="post">
<table width="491" border="0">
<tr>
<td width="107">Company:</td>
<td width="374"><input name="company" type="text" /></td>
</tr>
<tr>
<td>Name:</td>
<td><input name="name" type="text" /></td>
</tr>
<tr>
<td>Email:</td>
<td><input name="address" type="text" /></td>
</tr>
<tr>
<td>Phone:</td>
<td><input name="phone" type="text" /></td>
</tr>
</table>
<p><?php echo '<img src="'.BASE_URL.'images/captcha/'.date('n').'.jpg">'; ?><br />
What color is this?:<br />
<input name="captcha" size="25" style="text-transform: lowercase;"/>
<input name="submitcontestant" type="submit" value="Submit" />
</p>
</form>
id suggest you to start here : http://se2.php.net/manual/en/intro.mysqli.php
you're way off track at the moment and basically asking someone to code it for you.
after your posts update : it seems that the problem is you're not connecting to sql at all try using $link = mysql_connect('host', 'mysql_user', 'mysql_password');
All set, I was creating my data table in the wrong database, new table was added in the appropriate database and all better :). Thanks to everyone who gave me input!

get PHP POST from dynamically loaded page

I have a page that gets updated dynamically using ajax, I have a form loaded dynamically and when the submit button is clicked it dynamically loads another page. How would I access my POST variables when doing this? I've tried the $_POST['variable'] with no luck.
ajaxloader.js
register-form.php
<?php
session_start();
if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
echo '<ul class="err">';
foreach($_SESSION['ERRMSG_ARR'] as $msg) {
echo '<li>',$msg,'</li>';
}
echo '</ul>';
unset($_SESSION['ERRMSG_ARR']);
}
?>
<form id="loginForm" name="loginForm" method="post" action="javascript:ajaxpage('account/register-exec.php', 'content');">
<table width="300" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<th>First Name </th>
<td><input name="firstName" type="text" class="textfield" id="firstName" /></td>
</tr>
<tr>
<th>Last Name </th>
<td><input name="lastName" type="text" class="textfield" id="lastName" /></td>
</tr>
<tr>
<th>Username</th>
<td><input name="username" type="text" class="textfield" id="username" /></td>
</tr>
<tr>
<th>Password</th>
<td><input name="password" type="password" class="textfield" id="password" /></td>
</tr>
<tr>
<th>Confirm Password </th>
<td><input name="cpassword" type="password" class="textfield" id="cpassword" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Register" /></td>
</tr>
</table>
</form>
register-exec.php
<?php
//Start session
session_start();
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$firstName = clean($_POST['firstName']);
$lastName = clean($_POST['lastName']);
$username = clean($_POST['username']);
$password = clean($_POST['password']);
$cpassword = clean($_POST['cpassword']);
//Input Validations
if($firstName == '') {
$errmsg_arr[] = 'First name missing';
$errflag = true;
}
if($lastName == '') {
$errmsg_arr[] = 'Last name missing';
$errflag = true;
}
if($username == '') {
$errmsg_arr[] = 'Username missing';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
if($cpassword == '') {
$errmsg_arr[] = 'Confirm password missing';
$errflag = true;
}
if( strcmp($password, $cpassword) != 0 ) {
$errmsg_arr[] = 'Passwords do not match';
$errflag = true;
}
//Check for duplicate username
if($username != '') {
$qry = "SELECT * FROM member WHERE username='$username'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
$errmsg_arr[] = 'Username already in use';
$errflag = true;
}
#mysql_free_result($result);
}
else {
die("Query failed");
}
}
//If there are input validations, redirect back to the registration form
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: register-form.php");
exit();
}
//Create INSERT query
$qry = "INSERT INTO member(firstName, lastName, username, password) VALUES('$firstName','$lastName','$username','".md5($_POST['password'])."')";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: register-success.php");
exit();
}else {
die("Query failed");
}
?>
You can see my full form by clicking the "Join" button at tri-peoria.org and clicking on the 2nd link.
Your javascript is not sending any data and is using a GET request, not a POST. You will need to extract the data from your form into a variable to send. Replace the parameter names and elementIDs below with your form element IDs.
formData = buildData();
page_request.open('POST', url, true);
page_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
page_request.send(formData);
function buildData() {
//build a variable to store the form data, use encodeURI to encode any chars that require encoding
var postFormVars = "addressLine1=" + encodeURI( document.getElementById("addressLine1").value ) +
"&addressLine2=" + encodeURI( document.getElementById("addressLine2").value ) +
"&addressLine3=" + encodeURI( document.getElementById("addressLine3").value ) +
"&town=" + encodeURI( document.getElementById("town").value ) +
"&postcode=" + encodeURI( document.getElementById("postcode").value );
return postFormVars;
}
Your Javascript is sending a GET request and as per your statement you are checking $_POST
page_request.open('GET', url, true)
So update those to match then try again

Categories