I am having an issue with my php not writing the values it is getting from my ajax script into my MySQL database. I know that the php script is getting the values because they are being echoed in my browser. but when i check my database, only two out of the five values are being inputted. I am sure this isn't a nuance, but I can't seem to crack this.
==============EDIT=============
The values that aren't being written are first name, last name, and job. ($fname, $lname, and $job respectively)
==============EDIT=============
PHP
<?php
//db connecting variables
$hostname = "foobase";
$username = "foobase";
$dbname = "contactformbase";
$password = "password";
$con = new mysqli($hostname, $username, $password, $dbname);
$tbl_name = "client_base";
//Connecting to your database
if ($con->connect_error) {
die('Connect error (' . mysqli_connect_errno() . ')' . mysqli_connect_errno());
}
echo 'success!...' . $con->host_info . "\n";
print_r($_POST);
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$address = $_POST['address'];
$job = $_POST['job'];
$message = $_POST['message'];
//adding values into the database.
$sql="INSERT INTO $tbl_name (First Name, Last Name, Email, Address, Job)VALUES('POST_['first_name']', '$lname', '$address', '$email')";
$result = mysqli_query($con, $sql);
if($result){
echo "success";
}
else {
echo "error";
}
Javascript
<script type="text/javascript">
$("#submit").click(function(e) {
e.preventDefault();
var data_string = $("form#contact").serializeArray();
alert(data_string);
$.ajax({
type: "POST",
url: "database.php",
data: data_string,
success: function(){
alert(data_string);
}
});
return false;
</script>
HTML
<form action="" method="POST" id="contact">
<table>
<tbody>
<tr>
<td><h2>First Name: </h2></td>
<td><h2>Last Name: </td>
<td><h2>Email Address: </td>
</tr>
<tr>
<td><input type="text" name="first_name" placeholder="Johnny"></td>
<td><input type="text" name="last_name" placeholder="Appleseed"></td>
<td><input type="text" name="email" placeholder="johnny#email.com"></td>
</tr>
<tr>
<td><h2>Street Address:</h2></td>
<td><h2>What's Dirty?</h2></td>
</tr>
<tr>
<td><input type="text" name="address" placeholder="123 Applegrove Rd. Appletown, VA 12345"></td>
<td>
<select name="job" form="contact">
<option value="house">House</option>
<option value="roof">Roof</option>
<option value="garage-shed">Garage/shed</option>
<option value="other">Other</option>
</select>
</td>
</tr>
<tr>
<td><h2>Message: </h2></td>
</tr>
</tbody>
</table>
<textarea name="message">
</form>
You have the wrong field names in your PHP.
Change...
$fname = $_POST['fname'];
$lname = $_POST['lname'];
to
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
Also check the insert statement. It has wrong values against the fields - Address for Email, Eamil for Address.
$sql="INSERT INTO". $tbl_name ."(First Name, Last Name, Email, Address, Job) VALUES('". $_POST['first_name'] ."', '". $_POST['last_name'] ."', '". $_POST['adress'] ."', '". $_POST['email'] ."')";
You are using strange variables POST_['first_name'].
Try this query:
(Note: you have to use the quotes (' ') for the fields because you have a space in field names or use PDO to prepare and execute query.)
$sql="INSERT INTO $tbl_name (First Name, Last Name, Email, Address, Job)
VALUES('$fname', '$lname', '$address', '$email')";
Other issue is the POST array, you send first_name instead of fname and last_name instead of lname:
<tr>
<td><input type="text" name="first_name" placeholder="Johnny"></td>
<td><input type="text" name="last_name" placeholder="Appleseed"></td>
<td><input type="text" name="email" placeholder="johnny#email.com"></td>
</tr>
This will return:
$_POST = array(
"first_name" => "Johnny",
"last_name" => "Appleseed",
"email" => "johnny#email.com"
);
As you see you don't have $_POST['fname'] and $_POST['lname']
so you have to change:
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
About job, you just didn't add it in INSERT statement:
$sql="INSERT INTO $tbl_name (First Name, Last Name, Email, Address, Job)
VALUES('$fname', '$lname', '$address', '$email', '$job')";
Related
I really can not find what am I doing wrong in my registration form, unfortunately the page is just reloading instead of inserting values from form to my DB table.
Register.php
<?php
require_once("./Connection.php");
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
$sql = "insert into agents (firstName, lastName, email, phone, password) value ('".$firstName."', '".$lastName."', '".$email."','".$phone."','".$hashPassword."')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Registration successfully";
}
}
?>
Connection.php
<?php
$conn = mysqli_connect("localhost","root","","KBHestate");
if(!$conn){
die("Connection error: " . mysqli_connect_error());
}
Register Form
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="text" name="firstName" value="" placeholder="First Name">
<input type="text" name="lastName" value="" placeholder="Surname">
<input type="text" name="email" value="" placeholder="Email">
<input type="text" name="phone" value="" placeholder="Phone">
<input type="password" name="password" value="" placeholder="Password">
<button type="submit" name="submit">Submit</button>
</form>
Please make sure the following line has no problem when it is interpreted by the PHP:
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
On the other hand, please make sure that the password field is wide enough to store the $hasPassword data
Your code looks fine, it should work. I am hoping you are having Register form in the same file Register.php
But as you mentioned it's just reload the page that means there must be a exception/error from mysql query that is not handled in your code.
You have not shared your table structure. So, I am answering you based on the common mistake.
Like one of your table column width is varchar(10) and you are trying to pass data of length 20 char.
So, i suggest you to add below code in your Register.php as the else condition for if($result). So, it will display the error if any.
else {
echo("Error description: " . $conn->error);
}
Now your Register.php code will be look like below:
<?php
require_once("./Connection.php");
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
$sql = "insert into agents (firstName, lastName, email, phone, password) value ('".$firstName."', '".$lastName."', '".$email."','".$phone."','".$hashPassword."')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Registration successfully";
}else {
echo("Error description: " . $conn->error);
}
}
?>
im new to HTML and PHP. I am trying to create a form which loads my new users details into a database hosted by my web hosting company.
my form code (HTML) is :
<h1>Create Your GoSense Account</h1>
<form method:"POST" action:"newuserform.php" >
<div class="namef">
Name: <input type="text" style="width:200px" name="Name"
placeholder="First Name"><br></br> </div>
<div class="surnamef">
Surname: <input type="text" style="width:178px" name="Surname"
placeholder="Last Name"><br></br></div>
<div class="emailf">
Email: <input type="text" style="width:202px" name="Email"
placeholder="Email"><br></br> </div>
<div class="passwordf">
Password: <input type="text" style="width:170px" name="Password"
placeholder="Password"><br></br></div>
<input type="submit" style="font-size: 300px" name=""
value="Submit">
</form>
my PHP code stored in newuserform.php is:
<?php
define('DB_NAME','gosensec_useraccounts');
define('DB_USER','MyUsername');
define('DB_PASSWORD','myPassword');
define('DB_HOST','***.**.**.**');
$Name = filter_input(INPUT_POST,'Name');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
$db_selected = mysql_select_db (DB_NAME, $link) ;
$VALUE = $_POST['Name'];
$VALUE = $_POST['Surname'];
$VALUE = $_POST['Email'];
$VALUE = $_POST['Password'];
$sql = " INSERT INTO Users (Name) VALUES ('$VALUE')";
$sql = " INSERT INTO Users (Surname) VALUES ('$VALUE')";
$sql = " INSERT INTO Users (Email) VALUES ('$VALUE')";
$sql = " INSERT INTO Users (Password) VALUES ('$VALUE')";
mysql_close()
?>
I have doubled checked the connection parameters with my db host company and they advised that it is correct so my next step is to question my code ? Can anyone pick any errors that could be causing the data to insert into my DB ?
Many Thanks
There are multiple mistakes.
1- Assign each variable to a specific name:
$Name = $_POST['Name'];
$Surname = $_POST['Surname'];
$Email = $_POST['Email'];
$Password = $_POST['Password'];
2- insert all values into a single row not multiple rows.Also concatnate the variables as variables not as strings inside quotes!
$sql = "INSERT INTO Users (Name,Surname,Email,Password) VALUES ('" .$Name. "','". $Surname ."','". $Email ."','" .$Password. "')";
3- Do not forget to execute sql command:
$link->query($sql)
4- To close the connection use mysql_close($link)
finally: Do not forget to prevent SQL INJECTION by filtering values. Also try mysqli instead of the discontinued mysql API.
Error:
The screen goes blank when submitting the form and there is no new record in the database. Any ideas?
My files:
Conn.php
<?php
$connect =mysqli_connect ("localhost", "root", "", "gym");
if(mysqli_connect_errno($connect))
{
echo "Error Connecting to Database!";
}
?>
Form.php
<html>
<head>
<title>Gym Form</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="Proccess.php" method="post">
<span>Gym Membership Registration</span><br><br>
<Span>Title: </Span><input type ="text" Value =" " name ="Title" /><br>
<Span>First Name: </Span><input type ="text" Value =" " name ="Fname" /><br>
<Span>Last Name: </Span><input type ="text" Value =" " name ="Lname" /><br><br>
<Span>Gender: </Span><select name ="Gender">
<option value ="Junior">Male</option>
<option value ="Adult">Female</option>
<option value ="Senior">Private</option>
</select><br>
<Span>DOB: </Span><input type ="date" name ="DOB" /><br><br>
<Span>MembershipExpiry: </Span> <input type ="date" name ="MemX" /><br>
<Span>MembershipType: </Span><select name = "MemType">
<option value ="Junior">Junior</option>
<option value ="Adult">Adult</option>
<option value ="Senior">Senior</option>
</select><br><br>
<Span>Email Address: </Span><input type ="email" name ="Email" /><br><br>
<input type="Submit" name="submit" value ="Submit Form">
An Proccess.php (where the error seems to be):
<?php
include 'Connect.php';?>
<?php
//variables
$title = $_POST['Title'];
$fname = $_POST['Fname'];
$lname = $_POST['Lname'];
$gender = $_POST['Gender'];
$dob = $_POST['DOB'];
$memx = $_POST['MemX'];
$memtype = $_POST['MemType'];
$email = $_POST['Email'];
//query
mysqli_query($connect, "INSERT INTO records(Title,Fname,Lname,Gender,DOB,MemX,MemType,Email)
values ('$title', '$fname', '$lname', '$gender', '$dob', '$memx', '$memtype', '$email')");
Error:
The screen goes blank when submitting the form and there is no new record in the database. Any ideas?
Database table is called records and has columns:
Title
First Name
Last Name
Gender
etc
Please help me connect and upload the forms data to db.
Try to add ',' after $connect like this:
mysqli_query($connect, "INSERT INTO records(Title,Fname,Lname,Gender,DOB,MemX,MemType,Email)
values ('$title', '$fname', '$lname', '$gender', '$dob', '$memx', '$memtype', '$email')");
connection.php
<?php
$connect = mysqli_connect ("localhost", "root", "", "gym") or die('Error Connecting to Database!');
?>
process.php
<?php
//variables
$title = $_POST['Title'];
$fname = $_POST['Fname'];
$lname = $_POST['Lname'];
$gender = $_POST['Gender'];
$dob = $_POST['DOB'];
$memx = $_POST['MemX'];
$memtype = $_POST['MemType'];
$email = $_POST['Email'];
//query
$sql = 'INSERT INTO records (Title, Fname, Lname, Gender, DOB, MemX, MemType, Email) VALUES ( ?,?,?,?,?,?)';
if (! $stmt = mysqli_prepare($connection, $sql)) {
trigger_error('Error: ' . mysqli_error($connection), E_USER_WARNING);
}
mysqli_stmt_bind_param($stmt, 'ssssssss', $title, $fname, $lname, $gender, $dob, $memx, $memtype, $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($db);
redirect('Form.php');
Check this out http://php.net/manual/en/book.mysqli.php
I am trying to create two different tables based upon a radio selection in the HTML file. This is the HTML form I have created so far:
<form action="connect.php" method=POST>
First Name: <input type="text" name="firstname"><br><br>
Last Name: <input type="text" name="lastname"><br><br>
Email: <input type="text" name="email"><br><br>
Desired Password: <input type="password" name="password"><br><br>
Re-type Password: <input type="password" name="password"><br><br>
I am a: <input type="radio" name="role" value="student">Student
<input type="radio" name="role" value="alumni">Alumni<br><br>
<div class="stud">
Major: <input type="text" name="studmajor"><br><br>
Emphasis: <input type="text" name="studemphasis"><br><br>
Expected Graduation Year: <input type="text" name="studgradyear"><br><br>
Hobbies: <input type="text" name="studhobbies">
</div>
<div class="alum">
Gradutation Year: <input type="text" name="alumgradyear"><br><br>
Major: <input type="text" name="alummajor"><br><br>
Emphasis: <input type="text" name="alumemphasis"><br><br>
Company: <input type="text" name="alumcompany"><br><br>
Hobbies: <input type="text" name="alumhobbies">
</div>
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
$('input:radio[name=role]').change(function(){
var role = $(this).val();
if(role=='student'){
$('.stud').show();
$('.alum').hide();
}
else if(role=='alumni'){
$('.alum').show();
$('.stud').hide();
}
});
So in this HTML code, I am trying to create a database. One for Alumni and one for Students. Depending on the radio box checked, different options are shown. The following is my php code I wrote (and borrowed) to INSERT INTO the two different tables I have created. I am using c9.io as this is just a mock up to get my idea for the site up and running.
<?php
$servername = getenv('IP');
$username = getenv('C9_USER');
$password = "";
$database = "c9";
$dbport = 3306;
$db = mysqli_connect($servername, $username, $password, $database, $dbport);
if($db === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$first_name = mysqli_real_escape_string($db, $_POST['firstname']);
$last_name = mysqli_real_escape_string($db, $_POST['lastname']);
$email_address = mysqli_real_escape_string($db, $_POST['email']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$studmajor = mysqli_real_escape_string($db, $_POST['studmajor']);
$studemphasis = mysqli_real_escape_string($db, $_POST['studemphasis']);
$studgradyear = mysqli_real_escape_string($db, $_POST['studgradyear']);
$studhobbies = mysqli_real_escape_string($db, $_POST['studhobbies']);
$alumgradyear = mysqli_real_escape_string($db, $_POST['alumgradyear']);
$alummajor = mysqli_real_escape_string($db, $_POST['alummajor']);
$alumemphasis = mysqli_real_escape_string($db, $_POST['alumemphasis']);
$alumcompany = mysqli_real_escape_string($db, $_POST['alumcompany']);
$alumhobbies = mysqli_real_escape_string($db, $_POST['alumhobbies']);
$role = mysqli_real_escape_string($db, $_POST['role']);
// Post to Student
if($role == "student"){
$sql = "INSERT INTO Student (FirstName, LastName, Email, Password, Major, Emphasis, GradYear, Hobbies)
VALUES ('$first_name', '$last_name', '$email_address', '$password', '$studmajor', '$studemphasis', '$studgradyear', '$studhobbies');";
}
// Post to Alumni
else if($role == "alumni"){
$sql = "INSERT INTO Alumni (FirstName, LastName, Email, Password, GradYear, Major, Emphasis, Company, Hobbies)
VALUES ('$firstname', '$lastname', '$email', '$password', '$alumgradyear', '$alummajor', '$alumemphasis', '$alumcompany', '$alumhobbies');";
}
mysqli_close($db);
?>
Any help would be greatly appreciated. I'm pretty new to SQL and PHP so this is a little confusing.
Sorry for not being very specific. Whenever I fill out the form and click submit, I'm redirected and it displays:
Cannot POST /username/project/connect.php
My guess is that the if/elseif statement in the php file is what's causing the issue but I can't accurately say for sure.
You should name your form, pull data from HTML in connect.php and then use php to insert.
Here is a quick demo to show you how it is done!
PHP MYSQL Database Manipulation
Hope this Helps!
I have a form in my handler:
<form action="../submitcomment.php" method="post">
<input maxlength=100 size=60 type="text" name="IP" value="' . $ip . '" readonly="readonly" hidden="hidden">
<input maxlength=100 size=60 type="text" name="BlogId" value="' . $blogId . '" readonly="readonly" hidden="hidden">
<input maxlength=100 size=60 type="text" name="Date" value="' . $date . '" readonly="readonly" hidden="hidden">
<input maxlength=100 size=60 type="text" name="Name" placeholder="Enter Your Name">
<input maxlength=100 size=60 type="text" name="Email" placeholder="Enter Your Email">
<input maxlength=100 size=60 type="text" name="Comment" placeholder="Enter Your Comment">
<br>
<input type="submit" name="Submit" value="Submit Your Comment">
</form>
The action is submitcomment.php:
$ip = $_POST['IP'];
$BlogId = $_POST['BlogId'];
$Date = $_POST['Date'];
$Name = $_POST['Name'];
$Email = $_POST['Email'];
$Comment = $_POST['Comment'];
$blog = new Blogs();
if (isset($_POST['Submit']))
{
$addComment = $blog->insertComment($ip, $BlogId, $Date, $Name, $Email, $Comment);
header('Location: http://www.ryan.archi.dev.netsite.co.uk/Blog?success=1');
}else{
header('Location: http://www.ryan.archi.dev.netsite.co.uk/Blog?fail=1');
}
which reference a function in my class:
function insertComment($ip, $BlogId, $Date, $Name, $Email, $Comment)
{
$query = "INSERT INTO BlogComments (Name, Comment, IPAddress, Email, BlogId, Date) VALUES ('$Name', '$Comment', '$ip', '$Email', '$BlogId', '$Date')";
$oDatabase = new database;
$connection = $oDatabase->Connect();
$result = mysql_query ($query, $connection);
return $result;
}
The attempt to insert does not return or raise any errors.
As far as I'm aware this should be working, Can you spot what I am doing wrong?
Problem is with the column named Date - date is a reserved word (I guess of all known RDBMS).
You have to escape this word in Your query:
INSERT INTO BlogComments (Name, Comment, IPAddress, Email, BlogId, `Date`) VALUES ('$Name', '$Comment', '$ip', '$Email', '$BlogId', '$Date')
Also Your code gives anybody a chance to do a SQL injection attack therefore You should at least escape any user input or better use MySQLi or PDO.
You can do the escaping by php function http://php.net/mysql_real_escape_string :
$ip = mysql_real_escape_string($_POST['IP']);
$BlogId = mysql_real_escape_string($_POST['BlogId']);
$Date = mysql_real_escape_string($_POST['Date']);
$Name = mysql_real_escape_string($_POST['Name']);
$Email = mysql_real_escape_string($_POST['Email']);
$Comment = mysql_real_escape_string($_POST['Comment']);
Did you debug it? Is the connection to the database established successfully? You did no mysql escaping maybe the insert query fails.