PHP won't post form to database - php

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.

Related

Why can't I enter the data into the database even though the codes are correct and no error appear?

There is no change and no response in the form or in the database. I believe
the code is okay as no error appears and I included the connect database pdo. The connection is okay, and I changed the position of code to be above the form and under form but still no response. I connected correctly.
I separated the php page but it did not help.
Where is the problem in this code ?
Summary of the problem:
1-no response or error message
2- data not inserted into database
connection database:
<?php
$dsn ='mysql:host=localhost;dbname=person';
$user ='root';
$pass = "";
$option = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8",);
try{
$pdo = new PDO($dsn, $user , $pass, $option);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}
catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage()); }
and form of html:
<div class="container">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method=" POST">
<label for="fname"> الاسم </label><br>
<input type=" text" id="fname" name="username" placeholder=" الاسم"><br>
<label for="email"> البريد الالكتروني </label><br>
<input type="email" id="email" name="email" placeholder="البريد الالكتروني "><br>
<label for="valley"> اسم الحي </label><br>
<input type="text" id="valley" name="valley" placeholder="اسم الحي "><br>
<label for="phone"> رقم الجوال</label><br>
<input type="text" id="phone" name="mobile" placeholder="رقم الجوال "><br>
<label for="subject">الطلب</label><br>
<textarea id="subject" name="subj" placeholder="اكتب الطلب " style="height:200px">
</textarea><br>
<input type="submit" name="submit" value="ارسل">
</form>
</div>
<br>
php and query insertion to database
<?php
include('connect_pdo.php');
if (isset($_post['submit'])) {
$name = $_POST['username'];
$email = $_POST['email'];
$valley = $_POST['valley'];
$phone = $_POST['mobile'];
$subject = $_POST['subj'];
$stmt = $pdo->prepare("INSERT INTO emails (username,email,valley,mobile,subj)
VALUES('$name','$email','$valley','$phone' ,'$subject')");
if ($stmt->execute()) {
echo "تم الارسال بنجاح";}
else {
echo "تم الارسال" } }

How to fix MySQL and PHP in WAMP not inserting data?

I’m using WAMP as my php server, I’m using PHP-AdminPage for my databse (usin MySql), Everything is working, my database is connected . except for when I want to display the data, rows are created but they’re EMPTY! even tho I didn’t leave them empty. I don’t understand, I’m so confused.
PHP Code:
<html>
<body>
<?php
$conn = new mysqli('localhost','root','');
//check connection
if ($conn-> connect_error) {
die("Connection failed: ".$conn->connect_error);
}
echo "Database Connected successfully";
//choose db
mysqli_select_db($conn,"catcafe");
//insert query
$sql="INSERT INTO customer(FName,LName,Email,PhNum,Time) VALUES('$_POST[firstname]',
'$_POST[lastname]','$_POST[Email]','$_POST[Mobile]','$_Post[Time]')";
if($conn->query($sql) === true) {
echo "New record created";
}
else{
echo "Error, check values".$sql."<br>".$conn->error;
}
mysqli_close($conn);
?>
</body>
</html>
//insert query
$sql="INSERT INTO customer(FName,LName,Email,PhNum,Time) VALUES('$_POST[firstname]',
'$_POST[lastname]','$_POST[Email]','$_POST[Mobile]','$_Post[Time]')";
MySQL keeps telling me that the error is here! but I dont know what it is, the columns have the exact same name as the ones in the database.
MY FORM /HTML CODE:
<form action="InsertReservation.php">
<label for="fname">First Name </label><br>
<input type="text" id="fname" name="firstname" placeholder="Your name.." style="width:600px; font-size: 30px;">
<br>
<label for="lname">Last Name </label><br>
<input type="text" id="lname" name="lastname" placeholder="Your last name.."style="width:600px; font-size: 30px;">
<br>
<label for="Email">Email </label><br>
<input type="text" id="Email" name="Email" placeholder="Your Email is.."style="width:600px; font-size: 30px;">
<br>
<label for="Mobile">Mobile Number </label><br>
<input type="text" id="Mobile" name="Mobile" placeholder="Your Mobile Number is.." style="width:600px; font-size: 30px;">
<br>
<label for="Time">Time </label><br>
<input type="time" id="Time" name="Time" min="8:00" required style="width:600px; font-size: 30px;">
<br>
<input type="submit" value="Submit" onclick="alert ('Thank you. Your Reservation Is Confirmed!')">
<button type="reset" value="Reset" onclick="alert ('Reset is complete')"> Reset </button> <br>
</form>
MySQL Code
SELECT * FROM `customer` ORDER BY `customer`.`FName` ASC
I want it to insert the data, but it keeps inserting empty data.
Validate your input data all the time.
Use prepared statments for user input
Time is a mysql reserved word so use backticks `` around it.
$conn = new mysqli('localhost', 'root', '');
//check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Database Connected successfully";
//choose db
mysqli_select_db($conn, "catcafe");
//insert query
$sql = "INSERT INTO customer(FName,LName,Email,PhNum,`Time`) VALUES(?,?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssss", $_POST['firstname'], $_POST['lastname'], $_POST['Email'], $_POST['Mobile'], $_POST['Time']);
if ($stmt->execute()) {
echo "New record created";
} else {
echo "Error, check values " . $stmt->error;
}
mysqli_close($conn);
?>
Hello Please use this code on a single file it's working fine.
Thanks
$conn = new mysqli('localhost', 'root', '');
//check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Database Connected successfully";
//choose db
mysqli_select_db($conn, "catcafe");
if($conn){
//insert query
if(isset($_POST['submit']) && $_POST['submit'] == 'Submit'){
$sql = "INSERT INTO customer(FName,LName,Email,PhNum,Time)
VALUES('".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['Email']."','".$_POST['Mobile']."','".$_POST['Time']."')";
if($conn->query($sql) === true) {
echo "New record created";
}
else{
echo "Error, check values".$sql."<br>".$conn->error;
}
}
mysqli_close($conn);
}
<form method="post">
<label for="fname">First Name </label><br>
<input type="text" id="fname" name="firstname" placeholder="Your name.." style="width:600px; font-size: 30px;">
<br>
<label for="lname">Last Name </label><br>
<input type="text" id="lname" name="lastname" placeholder="Your last name.."style="width:600px; font-size: 30px;">
<br>
<label for="Email">Email </label><br>
<input type="text" id="Email" name="Email" placeholder="Your Email is.."style="width:600px; font-size: 30px;">
<br>
<label for="Mobile">Mobile Number </label><br>
<input type="text" id="Mobile" name="Mobile" placeholder="Your Mobile Number is.." style="width:600px; font-size: 30px;">
<br>
<label for="Time">Time </label><br>
<input type="time" id="Time" name="Time" min="8:00" style="width:600px; font-size: 30px;">
<br>
<input type="submit" name="submit" value="Submit" onclick="alert ('Thank you. Your Reservation Is Confirmed!')">
<button type="reset" value="Reset" onclick="alert ('Reset is complete')"> Reset </button> <br>
</form>

PHP action insert form not working

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..

Cannot store radio button value in table

I am trying to save the value of the radio buttons in my database table choice. I get the message Data saved successfully but no value is stored in the table.
Form:
<form id="myForm" method="post" action="">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<center<legend>Choose in which category you'd like to be included</legend></center>
<p><input type="radio" name="choice[]" value="player" id="player" class="custom" />
<label for="player">Player</label>
<input type="radio" name="choice[]" value="coach" id="coach" class="custom" />
<label for="coach">Coach</label>
<input type="radio" name="choice[]" value="supporter" id="supporter" class="custom" />
<label for="supporter">Supporter</label>
<input type="radio" name="choice[]" value="sponsor" id="sponsor" class="custom" />
<label for="sponsor">Sponsor</label>
<input type="radio" name="choice[]" value="alumni" id="alumni" class="custom" />
<label for="alumni">Alumni</label>
<input type="radio" name="choice[]" value="other" id="o" class="custom" />
<label for="o">Other</label>
</fieldset>
</div>
<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>
</body>
</html>
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']);
$choice = $mysqli->real_escape_string($_POST['choice']);
$query = "INSERT INTO Players (`name`,`email`,`phone`,`other`,`choice`) VALUES ('".$name."','".$email."','".$phone."','".$other."','".$choice."')";
if($mysqli->query($query))
{
echo 'Data Saved Successfully.';
}
else
{
echo 'Cannot save data.';
}
}
?>
var_dump($_POST) to sere what data flooding in.
One thing more to check if its save or submit ? in $_POST['save']
EDIT
After getting your full form - the error lies in your center tag
Change <center<legend> TO <center><legend>
The error - ↑ in this tag

jquery mobile form does not submit

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.

Categories