I am wondering which one are errors. I've tried to check mysql and nothing inserted into my database.
First of all, my HTML code are like this
<form action="registerAction" method="POST">
<p class="titleRegister"> Login Details </p>
<!-- login details -->
<p> <label for="emailAddress" class="inputField" > Email Address : </label> </p>
<p> <input id="emailAddress" class="registerField" name="ename" required="required" type="text" placeholder="Your email address"/> </p>
<p> <label for="password" class="inputField" > Password : </label> </p>
<p> <input id="password" class="registerField" name="pwd" required="required" type="password" placeholder="Your password"/> </p>
<p> <label for="password" class="inputField" > Confirmation Password : </label> </p>
<p> <input id="password" class="registerField" name="mpwd" required="required" type="password" placeholder="Confirmation password" onBlur="pwdCompare()"/> </p>
<!-- personal details -->
<p class="titleRegister"> Personal Details </p>
<!-- hidden to insert db -->
<input name="registerID" type="hidden"/>
<input name="pic" type="hidden"/>
<p>
<label for="socialTitle" class="inputField" > Title : </label>
<div class="radio">
<input type="radio" name="sTitle" value="mr"> Mr
<input type="radio" name="sTitle" value="mrs"> Mrs
<input type="radio" name="sTitle" value="ms"> Ms
</div>
</p>
<p> <label for="firstName" class="inputField" > First Name : </label> </p>
<p> <input id="firstName" class="registerField" name="fname" required="required" type="text" placeholder="Your first name"/> </p>
<p> <label for="lastName" class="inputField" > Last Name : </label> </p>
<p> <input id="lastName" class="registerField" name="lname" required="required" type="text" placeholder="Your last name"/></p>
<p> <label for="mainAddress" class="inputField" > Main Address : </label> </p>
<p> <input id="mainAddress" class="registerField" name="address" required="required" type="text" placeholder="Your main address"/> </p>
<p> <label for="countryName" class="inputField" > Country : </label> </p>
<?php
include 'dbconnect.php';
echo "<select class=\"selectCSS\" name=\"country\">";
$country = "SELECT DISTINCT * FROM geo_country ORDER BY country";
$showCountry = mysqli_query($mysqli, $country);
while($countryRow = mysqli_fetch_assoc($showCountry))
{
$country = htmlspecialchars ($countryRow['country']);
$countryCode = $countryRow['countryCode'];
echo "<option value=\"$country\">$country</option>\n";
}
echo "</select>";
?>
<p> <label for="cityName" class="inputField" > City : </label> </p>
<?php
include 'dbconnect.php';
echo "<select class=\"selectCSS\" name=\"city\">";
$city = "SELECT DISTINCT * FROM geo_country INNER JOIN geo_city ORDER BY city WHERE geo_country.countryCode = geo_city.countryCode";
$showCities = mysqli_query($mysqli, $city);
while($cityRow = mysqli_fetch_assoc($showCities))
{
$city = htmlspecialchars ($cityRow['city']);
$countryCode = $cityRow['countryCode'];
echo "<option value=\"$city\">$city</option>\n";
}
echo "</select>";
?>
<p> <label for="postalCode" class="inputField" > Postal Code : </label> </p>
<p> <input id="postalCode" class="registerField" name="pcode" required="required" type="text" placeholder="Your postal code"/> </p>
<p> <input class="registerButton" type="submit" value="REGISTER"> </p>
</form>
and my php action come here:
<?php
include 'dbconnect.php';
if ($_POST['pwd']!= $_POST['mpwd']) {
echo("Oops! Password did not match! Try again. ");
}
$register_ID = $_POST['registerID'];
$socialTitle = $_POST['sTitle'];
$firstName = ucfirst(strtoupper($_POST['fname']));
$lastName = ucfirst(strtoupper($_POST['lname']));
$emailAddress = htmlspecialchars($_POST['ename']);
$mainAddress = htmlspecialchars($_POST['address']);
$registerCity = $_POST['city'];
$registerCountry = $_POST['country'];
$postalCode = htmlspecialchars($_POST['pcode']);
$profilePic = $_POST['pic'];
$registerPassword = $_POST['pwd'];
$check = "SELECT * FROM register_user where emailAddress = '$emailAddress'";
$checkTitle = mysqli_query($mysqli,$check);
if (mysqli_num_rows($checkTitle) > 0) {
header("Location: register?error=The name of email has already been taken");
} else {
$insertSQL =
"INSERT INTO register_user ('registerID', 'socialTitle', 'firstName', 'lastName', 'emailAddress', 'mainAddress', 'registerCity', 'registerCountry', 'postalCode', 'profilePic', 'registerPassword')
VALUES ('$register_ID', '$socialTitle', '$firstName', '$lastName', '$emailAddress', '$mainAddress', '$registerCity', '$registerCountry', '$postalCode', '$profilePic', '$registerPassword')";
$queryResult = mysqli_query($mysqli,$insertSQL);
if($queryResult) {
echo "SUCCESS";
echo "<p> Name : $emailAddress </p>";
echo "<p> Detail : $fname </p>";
echo "<p> BACK </p>";
}
}
?>
The results are nothing come out on the new html page and neither in DB. Can you check it out please? Thanks.
You're using the wrong identifiers for your columns, being (single) quotes '.
('registerID', 'socialTitle', 'firstName', 'lastName', 'emailAddress', 'mainAddress', 'registerCity', 'registerCountry', 'postalCode', 'profilePic', 'registerPassword')
change that to:
(registerID, socialTitle, firstName, lastName, emailAddress, mainAddress, registerCity, registerCountry, postalCode, profilePic, registerPassword)
or use backticks.
(`registerID`, `socialTitle`, `firstName`, `lastName`, `emailAddress`, `mainAddress`, `registerCity`, `registerCountry`, `postalCode`, `profilePic`, `registerPassword`)
Using or die(mysqli_error($mysqli)) to mysqli_query() would have shown you the error.
Plus, unless the form action is an index file in a folder called registerAction or a mod rewrite:
it would need to be
<form action="registerAction.php" method="POST">
so, check that. Just an insight.
I would also like to note that your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements, they are much safer.
Not 100% sure about it, but try changing your html.
This:
<form action="registerAction" method="POST">
To:
<form action="registerAction.php" method="POST">
Assuming registerAction is the name of you php file..
Related
I have a member page that lands after user signs in. From there I need to populate that page with all their data in a form format (same as the one they filled out initially) so they can edit and update/save.
<form>
<fieldset>
<legend>Edit My Account
</legend>
<div>
<label class="label" for="username">Username</label>
<input class="user" type="text" name="username" id="username" value="<?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="2" required />
</div>
<div>
<label class="label" for="email">Email</label>
<input class="email" type="email" name="email" id="email" value="<?php if(isset($error)){ echo $_POST['email']; } ?>" tabindex="3" required />
</div>
<div>
<label class="label" for="password">Password</label>
<input class="password" type="password" name="password" id="password" tabindex="4" required />
</div>
<div>
<label class="label" for="passwordConfirm">Confirm Password</label>
<input class="password" type="password" name="passwordConfirm" id="passwordConfirm" tabindex="5" required />
</div>
<div>
<input class="showbox" type="checkbox" name="terms" id="terms" tabindex="6" onFocus="this.tabIndex=1;"onBlur="this.tabIndex=6;"required />
<label for="terms">I agree to the Terms</label>
</div>
</fieldset>
<fieldset>
<div>
<input name="submit" type="submit" value="Update" />
</div>
</fieldset>
</form>
Secondly I want them to be able to delete their entire account with a "Delete My Account" button via a input type 'submit' that would appear on same member page.
<fieldset>
<form action="delete.php?" method="post">
<input type="hidden" name="id" value="<?php echo $members['memberID']; ?>">
<input type="submit" name="submit" value="Delete My Account">
</form>
</filedset>
I've been searching for days now... mostly this platform and have not found any sound solution(s).
I'm using MySQL db using PDO $stmt = $db->prepare('INSERT INTO... to create insert for new users and that all works fine.
I include a separate connection config file for db connection as well.
I created a delete.php file for the statement.
<?php require('config.php');
$id=$_SESSION['memberID'];
$stmt = $db->prepare('DELETE FROM members where memberID = $id');
?>
I'm not able to find a solution to populate the member page with logged in user data then edit and update it and/or capture the users logged in memberID to submit the delete account request using that memberID.
Some guidance would be appreciated, Thanks!
Here is my login.php code
<?php
//include config
require_once('config.php');
//check if already logged in move to home page
if( $user->is_logged_in() ){ header('Location: memberpage.php'); }
//process login form if submitted
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($user->login($username,$password)){
$_SESSION['username'] = $username;
header('Location: memberpage.php');
exit;
} else {
$error[] = '<h2 class="red ctr thanks">Wrong username or password or your account has not been activated.</h2>';
}
}//end if submit
?>
At first you must set id user.after login user in admin page
and next you can use of that
<?php
$userId= $_GET['id'];//get user id you can use session also
if (isset($_POST['submit'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$terms = $_POST['terms'];
if (($password===$passwordConfirm) and ($terms===1)){
$query = "UPDATE members SET username = :username ,email = :email,"
."password = :password WHERE id = :id";
$stmt = $db->prepare($query);
$stmt->bindParam(':username',$username, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':id',$userId, PDO::PARAM_INT);
}
}
$query = "SELECT * FROM `members` WHERE id = `$userId`"; //Get user info
$sth = $db->prepare($query);
$sth ->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
if ($result) {
// output data of each row
foreach($result as $row){
$username = $row['username'];
$email = $row['email'];
$password = $row['password'];
}
}
?>
<form method="post" class="form-horizontal" action="<?php filter_input(INPUT_SERVER, 'PHP_SELF', FILTER_SANITIZE_FULL_SPECIAL_CHARS); ?>">
<fieldset>
<legend>Edit My Account
</legend>
<div>
<label class="label" for="username">Username</label>
<input class="user" type="text" name="username" id="username" value="<?php echo $username ?>" tabindex="2" required />
</div>
<div>
<label class="label" for="email">Email</label>
<input class="email" type="email" name="email" id="email" value="<?php echo $email?>" tabindex="3" required />
</div>
<div>
<label class="label" for="password">Password</label>
<input class="password" type="password" name="password" value="<?php echo $password ?>" id="password" tabindex="4" required />
</div>
<div>
<label class="label" for="passwordConfirm">Confirm Password</label>
<input class="password" type="password" name="passwordConfirm" id="passwordConfirm" tabindex="5" required />
</div>
<div>
<input class="showbox" type="checkbox" name="terms" id="terms" tabindex="6" onFocus="this.tabIndex=1;"onBlur="this.tabIndex=6;"required />
<label for="terms">I agree to the Terms</label>
</div>
</fieldset>
<fieldset>
<div>
<input name="submit" type="submit" value="Update" />
</div>
</fieldset>
</form>
I'm attempting to insert the data collected on the form into a mysql database. I'm able to make a successful connection but the data is not inserted. I've read many similar questions but have been unsuccessful so far.
sqldatabase.php
<?php
$servername = "localhost";
$username = "USER";
$password = "PASS";
$dbname = "DATABASE";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$first_spouse = $_POST['first_spouse'];
$last_spouse = $_POST['last_spouse'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$phonehome = $_POST['phonehome'];
$phonecell = $_POST['phonecell'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$occupation = $_POST['occupation'];
$shirt_size = $_POST['shirt_size'];
$cap_size = $_POST['cap_size'];
$shirtnum1 = $_POST['shirtnum1'];
$shirtnum2 = $_POST['shirtnum2'];
$desc = $_POST['desc'];
$bylaws_rules = $_POST['bylaws_rules'];
$umpires = $_POST['umpires'];
$alcohol = $_POST['alcohol'];
$waiver = $_POST['waiver'];
$sql="INSERT INTO 'softball_reg_2016' (first_name, last_name, first_spouse, last_spouse,
address, city, state, zip, phonehome, phonecell, email, dob, occupation, shirt_size,
cap_size, shirtnum1, shirtnum2, desc, bylaws_rules, umpires, alcohol, waiver)
VALUES ('$_POST[first_name]', '$_POST[last_name]', '$_POST[first_spouse]', '$_POST[last_spouse]',
'$_POST[address]', '$_POST[city]', '$_POST[city]', '$_POST[state]', '$_POST[zip]',
'$_POST[phonehome]', '$_POST[phonecell]', '$_POST[email]', '$_POST[dob]', '$_POST[occupation]',
'$_POST[shirt_size]', '$_POST[cap_size]', '$_POST[shirtnum1]', '$_POST[shirtnum2]',
'$_POST[desc]', '$_POST[bylaws_rules]', '$_POST[umpires]', '$_POST[alcohol]', '$_POST[waiver]')";
echo "Connected successfully";
mysqli_close($conn);
?>
My html
<form action="/php/sqldatabase.php" method="POST" id="registration">
<h2>Registration for 2016 Summer Season (April-September)</h2>
<p>
<label for="name">Name:</label>
<input type="text" id="first_name" name="first_name" placeholder="First Name" autofocus="" />
<input type="text" id="last_name" name="last_name" placeholder="Last Name" />
</p>
<p>
<label for="spouse">Name of Spouse<i>(Optional)</i>:</label>
<input type="text" id="first_spouse" name="first_spouse" placeholder="First Name" />
<input type="text" id="last_spouse" name="last_spouse" placeholder="Last Name" />
</p>
<p>
<label for="address1">Address:</label>
<input type="text" id="address" name="address" placeholder="Street Address" />
<input type="text" id="city" name="city" placeholder="City" />
</p>
<p>
<label for="address2"></label>
<input type="text" id="state" name="state" placeholder="State" />
<input type="number" id="zip" name="zip" placeholder="Zip Code" />
</p>
<p>
<label for="phone">Phone:</label>
<input type="tel" id="phonehome" name="phone" placeholder="Home Phone" />
<input type="tel" id="phonecell" name="phone" placeholder="Work/Cell Phone" />
</p>
<p>
<label for="phone">Email:</label>
<input type="email" id="email" name="email" />
</p>
<p>
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" />
</p>
<p>
<label for="occupation">Occupation (Former, if retired):</label>
<input type="text" id="occupation" name="occupation" />
</p>
<div id="shirt">
<p>
<label for="size">Uniform:</label>
<select name="shirt_size" id="shirt_size">
<option value="">Shirt Size</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
<option value="XL">XL</option>
<option value="2XL">2XL</option>
<option value="3XL">3XL</option>
</select>
<select name"cap_size" id="cap_size">
<option value="">Cap Size</option>
<option value="XS/S">XS/S</option>
<option value="S/M">S/M</option>
<option value="M/L">M/L</option>
<option value="L/XL">L/XL</option>
</select>
</p>
<p>
<label for="shirtnum">Shirt Number:</label>
<input type="number" id="shirtnum1" name="shirtnum1" placeholder="1st Choice" min="0" max="99" />
<input type="number" id="shirtnum2" name="shirtnum2" placeholder="2nd Choice" min="0" max="99" />
</p>
</div>
<div id="describe">
<p>
<span class="describe1">
<b>Describe any information you deem important regarding your ability and/or availability or any other information you deem important to the season.</b>
<textarea name="description" id="desc" cols="30" rows="10"></textarea>
</span>
</p>
</div>
<div id="ethics">
<h2>Code of Ethics</h2>
<p>
<span class="ethics1">
<input type="checkbox" id="bylaws_rules" name="bylaws_rules" />
I agree to abide by the Bylaws and decisions of the Club and Club Officials.
</span>
</p>
<p>
<span class="ethics1">
<input type="checkbox" id="umpires" name="umpires" />
I agree to accept the decisions of the Umpires and Team Managers.
</span>
</p>
<p>
<span class="ethics1">
<input type="checkbox" id="alcohol" name="alcohol" />
I agree to abstain from alcoholic beverages prior to a game.
</span>
</p>
</div>
<div id="waiver">
<h2>Release of Liability</h2>
<p>
<b>I agree to hold harmless the club.</b>
</p>
<input type="checkbox" id="waiver" name="waiver" />
</div>
<ol class="requires">
<li>Dues are $95 and should be received by April 6, 2016</li>
<li>If you decline to play after being drafted, your registration fee will not be refunded.</li>
<li>All members must be at least 50 years old by December 31, 2016</li>
<li>The deadline for receipt of registrations is April 6, 2016. Registrations received after this date will
not be processed for the player drat. Assignments to teams will then be made according to League guidelines
regarding late registering players.</li>
<li>Registrations received without the correct fee will not be considered as received and will not be valid until the correct fee is received.</li>
</ol>
<p> </p>
<p> </p>
<p> </p>
<p>
<button type="submit" id="register">Register!</button>
</p>
</form>
Thank you for any help!
Posting as a community wiki.
There are a few things wrong here.
First, you never executed the query.
You never check for empty() fields, which might insert empty rows on the table.
Consult the manual:
http://php.net/manual/en/mysqli.query.php
Object oriented style
mixed mysqli::query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
Procedural style
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
Then you're using the wrong identifier qualifiers for your table:
INSERT INTO 'softball_reg_2016'
^ ^
being regular single quotes, where it should be ticks or no quotes at all:
INSERT INTO `softball_reg_2016`
and that alone would have thrown you a syntax error.
Read up on identifier qualifiers:
http://dev.mysql.com/doc/en/identifier-qualifiers.html
Then you're using desc as a column name which is a MySQL reserved word. That also would have thrown you an error about it. So, either you rename it to something else, or wrap it in ticks.
`desc`
Reference:
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
Also check for errors:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
Plus, your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
Also, since you already declared variables to your POST arrays, why put the POST arrays in the query? Just used the variables. You're using more code for nothing really.
And as noted in comments:
"You also have two input fields with same name: phone. Is that intended or just the copy/paste usual problem? – FirstOne"
You need to execute the query. You have just taken the string.
Here is what you are missing. Put
mysqli_query($conn,$sql);
before the success message.
You didn't excute the query
you have to do
mysqli_query($conn,$query);
before closing the connection
My PHP form will not post into the database. I understand php and mysql connections fairly well but I'm stumped on this one. When I hit submit on my form it doesn't echo the values that I(the user) put in. The date shows up as 1969-12-31, not the date the user submits. If anyone could help that would be great. My code is as follows
The form code is:
<form method="POST" action="add_event.php" id="create_event">
<label for="event_name">Event Name:</label>
<input type="text" id="event_name"><br />
<label for="date">Date:</label>
<input class="datepicker" type="date" id="date"><br />
<label for="zip_code">Zip Code:</label>
<input type="text" id="zip_code" maxlength="5"><br />
<label for="description">Description</label>
<textarea id="description" rows="5" columns="10"></textarea>
<br>
<input type="submit" name="submit">
</form>
The add_event.php insert code is:
<?php
require_once '../app_config.php';
require_once '../database_connection.php';
require_once '../authorize.php';
session_start();
// Authorize any user, as long as they're logged in
authorize_user();
//Get the user ID of the user to show
$user_id = $_SESSION['user_id'];
$select_query = "SELECT first_name, last_name FROM users WHERE user_id = " . $user_id;
// Run the query
$result = mysql_query($select_query);
if ($result) {
$row = mysql_fetch_array($result);
$first_name = $row['first_name'];
$last_name = $row['last_name'];
}
$name = $first_name . ' ' . $last_name;
$event_name = trim($_POST['event_name']);
$date = trim($_POST['date']);
$zip_code = trim($_POST['zip_code']);
$description = trim($_POST['description']);
// $date = "2012-08-22";
$newdate = date("Y-m-d", strtotime($date));
// $event_name = "test";
// $zip_code = "22153";
// $description = "test";
$insert_sql = sprintf("INSERT INTO events " .
"(name, user_profile_id, event_name, date, zip_code, description) " .
"VALUES ('%s', %d, '%s', '%s', '%s', '%s');",
mysql_real_escape_string($name),
mysql_real_escape_string($user_id),
mysql_real_escape_string($event_name),
mysql_real_escape_string($newdate),
mysql_real_escape_string($zip_code),
mysql_real_escape_string($description));
//insert the user into the database
mysql_query($insert_sql);
echo $insert_sql;
?>
Much thanks in advance.
The problem is that you are not naming your input fields. If you add the name property to the input in your html code the value will be stored in the $_POST array in php once the form is submitted. The correct html code should be:
<form method="POST" action="add_event.php" id="create_event">
<label for="event_name">Event Name:</label>
<input type="text" name="event_name"><br />
<label for="date">Date:</label>
<input class="datepicker" type="date" name="date"><br />
<label for="zip_code">Zip Code:</label>
<input type="text" name="zip_code" maxlength="5"><br />
<label for="description">Description</label>
<textarea name="description" rows="5" columns="10"></textarea>
<br>
<input type="submit" name="submit">
</form>
I am not sure if you needed the ids on the inputs for anything else, otherwise you should re-add those. For more information on html forms, visit: http://www.w3schools.com/html/html_forms.asp
You have not included any name attribute in your form. Here is how it should be:
<label for="event_name">Event Name:</label>
<input type="text" id="event_name" name="event_name"><br />
<label for="date">Date:</label>
<input class="datepicker" type="date" id="date" name="date"><br />
<label for="zip_code">Zip Code:</label>
<input type="text" id="zip_code" maxlength="5" name="zip_code"><br />
<label for="description">Description</label>
<textarea id="description" rows="5" columns="10" name="description"></textarea>
Note that only form inputs element that have the name attribute will be sent to the server. ID is only used on the client side.
Don't you need some name attributes in your form?
For example:
<input class="datepicker" type="date" id="date" name="date">
and the value within your POST['your_value'] must be the same as the value for the name attribute.
so:
$my_date = $_POST['date']
You need to give your input elements a name attribute... This is how php uses the $_POST['name attribute'] global to identify the field you are referring to.
so for example...
<form method="POST" action="add_event.php" id="create_event">
<label for="event_name">Event Name:</label>
<input type="text" name="event_name" id="event_name"><br />
<label for="date">Date:</label>
<input class="datepicker" name="date" type="date" id="date"><br />
<label for="zip_code">Zip Code:</label>
<input type="text" id="zip_code" name="zip_code" maxlength="5"><br />
<label for="description">Description</label>
<textarea id="description" name="description" rows="5" columns="10"></textarea>
<br>
<input type="submit" name="submit">
</form>
Trying to post a simple form to my database but can't get it to work. I have PHP and MySQL activated through XAMPP. The database "E-mail list" is set up with the table "Players".
PHP code:
<?php
$mysqli = new mysqli('localhost', 'root', '', 'E-mail list');
if(isset($_POST['save']))
{
$name = $mysqli->real_escape_string($_POST['name']);
$email = $mysqli->real_escape_string($_POST['email']);
$phone = $mysqli->real_escape_string($_POST['phone']);
$other = $mysqli->real_escape_string($_POST['other']);
$query = 'INSERT INTO Players (
name,
email,
phone,
other
)
VALUES ('.$name.', "'.$email.'", "'.$phone.'","'.$other.'")';
if ($mysqli->query($query))
{
echo 'Data Saved Successfully.';
}
else
{
echo 'Cannot save data.';
}}
?>
And the form:
<form id="myForm" method="post">>
<div data-role="fieldcontain">
<label for="name">Please enter your name:</label>
<input type="text" name="name" id="name" class="required" value="" autocomplete="off" />
<label for="email">Please enter your e-mail:</label>
<input type="text" name="email" id="email" value="" class="required" autocomplete="off" />
<label for="phone">Please enter your phone number:</label>
<input type="number" name="phone" id="phone" value="" class="required" autocomplete="off" />
<br><br>
<label for="other">Other comments</label>
<textarea name="other" id="other" autocomplete="off" placeholder="Anything else you'd like to add?">
</textarea>
</form>
<p><strong id="error"></strong></p>
<br><br>
<input type="button" id="save" name="save" value="Submit Form" />
<p id="response"></p>
I did some changes in your codes both PHP and HTML Parts.,
For PHP :
<?php
$mysqli = new mysqli('localhost', 'root', '', 'E-mail list');
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if(isset($_POST['save']))
{
$name = $mysqli->real_escape_string($_POST['name']);
$email = $mysqli->real_escape_string($_POST['email']);
$phone = $mysqli->real_escape_string($_POST['phone']);
$other = $mysqli->real_escape_string($_POST['other']);
$query = "INSERT INTO Players (`name`,`email`,`phone`,`other`) VALUES ('".$name."','".$email."','".$phone."','".$other."')";
if($mysqli->query($query))
{
echo 'Data Saved Successfully.';
}
else
{
echo 'Cannot save data.';
}
}
?>
For HTML :
<form id="myForm" method="post" action="">
<div data-role="fieldcontain">
<label for="name">Please enter your name:</label>
<input type="text" name="name" id="name" class="required" value="" autocomplete="off" /><br />
<label for="email">Please enter your e-mail:</label>
<input type="text" name="email" id="email" value="" class="required" autocomplete="off" /><br />
<label for="phone">Please enter your phone number:</label>
<input type="number" name="phone" id="phone" value="" class="required" autocomplete="off" />
<br><br>
<label for="other">Other comments</label>
<textarea name="other" id="other" autocomplete="off" placeholder="Anything else you'd like to add?">
</textarea>
<p><strong id="error"></strong></p>
<br><br>
<input type="submit" id="save" name="save" value="Submit Form" />
<p id="response"></p>
</form>
I think this may help you to resolve your problem.
Missing double quotes for name value in your SQL.
VALUES ("'.$name.'", "'.$email.'", "'.$phone.'","'.$other.'")';
Use Firefox/firebug to see the parameters and result, and add an echo($query); so you can see it in firebug.
'E-mail list' doesn't seem like convenient database name, though it should be okay.
Anyway, your goal should be to display all possible error that may occur.
So, you have to always check for the errors and report them in more usable form than just 'Cannot save data.'
Always check your connect
$mysqli = new mysqli('localhost', 'root', '', 'E-mail list');
if ($mysqli->connect_error) {
trigger_error($mysqli->connect_error);
}
same for the query
if (!$mysqli->query($query)) {
trigger_error($mysqli->error." ".$query);
}
If you see no error messages - check the logic of your code: if you ever run the code, if you run the code you wrote, if PHP works, typos etc.
I would like to get some user data using a php form and store it in a mysql database , trouble is, the page simply refreshes when I submit the form.
Here is my php form:
<form id="companyform" name="companyform" method="post" action="index3.php" data-ajax="false">
<b>To enlist your business fill in the form below:</b>
<p>
<label for="name">Company Name:</label>
<input type="text" name="companyname" id="companyname" data-mini="true"/>
</p>
<p>
<label for="name">Company Address:</label>
<input type="text" name="companynaddress" id="companynaddress" data-mini="true"/>
</p>
<p>
<label for="textfield">Tel No.:</label>
<input type="text" name="tel" id="tel" data-mini="true"/>
</p>
<p>
<label for="textfield">Fax No.:</label>
<input type="text" name="fax" id="fax" data-mini="true"/>
</p>
<p>
<label for="textfield">Email:</label>
<input type="text" name="email" id="email" data-mini="true"/>
</p>
<p>
<label for="textfield">Website Address:</label>
<input type="text" name="website" id="website" data-mini="true"/>
</p>
<p>
<label for="textfield">Contact Person Name:</label>
<input type="text" name="contactname" id="contactname" data-mini="true"/>
</p>
<p>
<label for="textfield">Contact Person Number:</label>
<input type="text" name="contactnumber" id="contactnumber" data-mini="true"/>
</p>
<p>
<label for="textfield">Contact Person Email:</label>
<input type="text" name="contactemail" id="contactemail" data-mini="true"/>
</p>
<p>
<input name="submit" type="submit" id="submit" value="Submit" />
</p>
</form>
and here is my database connection code:
<?php
if (array_key_exists('submit', $_POST)) {
$con = mysql_connect("host", "user", "pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("botswanasearchdb", $con);
$companyname = $_POST['companyname'];
$companyaddress = $_POST['companyaddress'];
$tel = $_POST['tel'];
$fax = $_POST['fax'];
$emailid = $_POST['emailid'];
$website = $_POST['website'];
$contactname = $_POST['contactname'];
$contactnumber = $_POST['contactnumber'];
$contactemail = $_POST['contactemail'];
// prepare the SQL query
$sql = "INSERT INTO businessuser (companyname, companyaddress, tel, fax, emailid, website, contactname, contactnumber, contactemail) VALUES ('$companyname', '$companyaddress', '$tel', '$fax', '$emailid', '$website', '$contactname', '$contactnumber', '$contactemail')";
mysql_close($con);
}
?>
This is your form tag:
<form id="companyform" name="companyform" method="post" action="index3.php" data-ajax="false">
So you are submitting the form to index3.php (the action attribute). According to your comment index3.php contains your form and that is why the form refreshes when you submit it. You are basically reloading your form on form submit.
You need to submit the form to your php script that contains the php code you posted.
Edit: If everything is on the same page, you can do something like:
if (array_key_exists('submit', $_POST))
{
// your code
// show thank you message
}
else
{
// show form
}
Another edit: As you are using the deprecated mysql_* functions and not escaping the data, you have an sql injection whole and a ' character in your data will break your query. You should switch to PDO / mysqli and prepared statements. And always add error handling.