PHP Post Echo Two Sql Entries - php

I need help figuring out why I receive two entries into my database with the following code. At this time it is inputting the complete record and a blank record into the database. Not sure why. Can anyone point me in the right direction of where I am going wrong? Thanks.
Form and PHP Code
<form method="post" action="cu.php">
<input type="text" name="name" value size="35"
placeholder="Name">&nbsp&nbsp
<input type="text" name="email" value size="35" placeholder="Email">
<br><br>
<select name="dropdown">
<option value="0">Comment Type</option>
<option value="A">Accounting</option>
<option value="FAQ">FAQ</option>
<option value="GQ">General Question</option>
<option value="TS">Technical Support</option>
</select>
<br><br>
<textarea name="comments" rows="10" cols="60" style"border: 3px solid #555"
placeholder="Comments"></textarea>
<br><br>
<input type="submit" value="Submit" id="btn">
<input type="reset" value="Reset" id="btn">
</form>
</one>
</div>
<?php
if ($_POST) {
$name = $_POST['name'];
echo "User Has submitted the form and entered this name : <b>$name</b>";
echo "<br>You can use the following form again to enter a new name.";
}
$con = mysql_connect("mysql", "username", "pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
/* Prevent duplicate submissions */
if (isset($_COOKIE['FormSubmitted'])) {
show_error('You may only submit this form once per session!');
}
mysql_select_db("communication", $con);
$sql = "INSERT INTO contact (name, email, cusno, dropdown, comments)
VALUES
('$_POST[name]', '$_POST[email]', '$_POST[cusno]', '$_POST[dropdown]',
'$_POST[comments]')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
}
mysql_close($con);

That is because, everytime the page load, php will run your sql insert code. This happen because you don't check if the form is submitted, then run the sql query.
Do like this:
add name to your submit button:
<input type="submit" value="Submit" id="btn" name="submit">
then in php, wrap the sql insert in if statement
// check if submit button is POST, then run query
if(isset($_POST['submit']))
{
$sql = "INSERT INTO contact (name, email, cusno, dropdown, comments)
VALUES
('$_POST[name]', '$_POST[email]', '$_POST[cusno]', '$_POST[dropdown]',
'$_POST[comments]')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
}
}

Update this lines
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
}
to
if (!empty($_POST) && !mysql_query($sql, $con) ) {
die('Error: ' . mysql_error());
}
Also i suppose that you browser requesting favicon file and the fore your code can be executed twice

Related

PHP - INSERT Query failing, returns no error. Beginner

<form action="" method="post">
<input type="text" id="title" name="title" />
<input type="text" id="link" name="link" />
<input type="submit" value="Add resource" />
<?php
if(isset($_POST['title']) && $_POST['link']) {
$t = $_POST['title'];
$l = $_POST['link'];
$con = mysqli_connect("localhost","root","","rman");
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL:" . mysqli_connect_error());
}
mysqli_query($con, "INSERT INTO tutorials (id, title, link, section) VALUES ('','$t','$l','')");
}
?>
</form>
How can this not work? I have removed every single part that might have caused this. Nothing is going in the database, no errors returning whatsoever.
For everyone wondering:
DB name: rman
Table name: tutorials
colums: id (INT11, Auto increment), title (Text), link (Text), section(INT11)
Am I being blind here? I'm sorry if thats the situation. Hope someone can see what I am doing wrong and help me out.
This should work.
<?php
if(isset($_POST['title']) && $_POST['link']) {
$t = $_POST['title'];
$l = $_POST['link'];
$con = mysqli_connect("localhost","root","","rman");
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL:" . mysqli_connect_error());
}
mysqli_query($con, "INSERT INTO tutorials (id, title, link, section) VALUES ('', '$t', '$l', '1')");
}
?>
<form action="" method="post">
<input type="text" id="title" name="title" />
<input type="text" id="link" name="link" />
<input type="submit" name="submit" value="Add resource" />
</form>
use mysqli_error() to check error code, as well as don't insert blank id if it's AI
Thusly:
if (!mysqli_query($con, "INSERT INTO tutorials (id, title, link, section) VALUES ('','$t','$l','')"))
{
echo mysqli_error($con);
}

Not enter data in mysql database with wordpress and php

Im trying to add a new user name to mysql table throw wordpress. But everytime I try to do it, I have no error message, but there are no lines added to the data base.
This is the wordpress page with the php inside:
<table>
<form name="form1" method="post" action="">
<strong>Please enter your information in order to download the Macs Cabs
App</strong>
<tr><td>
Name:</td><td><input name="Name" type="text" id="sName"></td></tr>
Email Address:</td><td><input name="Email" type="text" id="sEmail"></td> </tr>
<tr><td>
<input type="submit" name="Submit" value="Submit"></td></tr>
</form></table>
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("foundint_Sababa", $con);
$sql="INSERT INTO `Users` (`sName`, `sEmail`)
VALUES ('{$_POST['sName']}','{$_POST['sEmail']}')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
$info = mysql_info(); echo $info;
mysql_close($con);
?>
I can't see whats wrong. I think it may be something wrong with the connection. Any ideas?
Thank you!
Edit
As suggested, Im trying to use $wpdb so I've created a php file in a folder call my-codes (at the same level of wp-admin, wp-content and wp-includes) and I added the following code to a file call insertUser.php:
<?php
global $wpdb;
$wpdb->insert("wp_submitted_form", array(
"sName" => $sName,
"sEmail" => $sEmail));
?>
Now in my page Im trying to call this function and Im doing this:
<table>
<form name="form1" method="post" action="">
<strong>Please enter your information in order to download the Macs Cabs
App</strong>
<tr><td>
Name:</td><td><input name="Name" type="text" id="sName"></td></tr>
Email Address:</td><td><input name="Email" type="text" id="sEmail"></td> </tr>
<tr><td>
<input type="submit" name="Submit" value="Submit"></td></tr>
</form></table>
<?php
if(isset($_POST['Submit']))
{
include("./my-codes/insertUsers.php");
}
?>
And im still not being able to insert any row in the database. Any suggestions?
EDIT
I needed a pluggin to actually connect my sql database with wordpress. The code is correct.
Replace your code with the code that i have provided.
<table>
<form name="form1" method="post" action="">
<strong>Please enter your information in order to download the Macs Cabs
App</strong>
<tr><td>
Name:</td><td><input name="Name" type="text" id="sName"></td></tr>
Email Address:</td><td><input name="Email" type="text" id="sEmail"></td> </tr>
<tr><td>
<input type="submit" name="Submit" value="Submit"></td></tr>
</form></table>
<?php
$con = mysql_connect("localhost","root","root"); // ensure that your password in empty or root in your localhost
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("foundint_Sababa", $con);
if(isset($_POST['Submit']))
{
// Previous Insert Query which has discrepency in form input names and Insert Values
//$sql="INSERT INTO `Users` (`sName`, `sEmail`) VALUES ('{$_POST['sName']}','{$_POST['sEmail']}')";
// My new Query with corrected form input names for Input Values during POST.
$sql = "INSERT INTO `Users`(`sName`, `sEmail`) VALUES ('".$_POST['Name']."','".$_POST['Email']."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
$info = mysql_info(); echo $info;
mysql_close($con);
}
Finally have a check at the table field Names and my code works fine hope it will serve you to.
use the query like this one to make thing happen,
$sql="INSERT INTO `Users` (`sName`, `sEmail`) VALUES ('".$_POST['sName']."','".$_POST['sEmail']."')";
for preventing from injection you can use this way to build query.
$name=addslashes($_POST['sName']);
$email=addslashes($_POST['sEmail']);
$sql="INSERT INTO `Users` (`sName`, `sEmail`) VALUES ('$name','$email')";
using prepared statement
$mysqli = new mysqli("example.com", "user", "password", "database");
$name=addslashes($_POST['sName']);
$email=addslashes($_POST['sEmail']);
$stmt=$mysqli->prepare("INSERT INTO `Users` (`sName`, `sEmail`) VALUES (?,?)");
$stmt->bind_param("ss", $name,$email);
$stmt->execute();
for detailed on prepared statement got to http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

Submitting html data and staying on same page

I have a form page
<html>
<body>
<form action="insert.php" method="post">
App Name: <input type="text" name="fname" /><br><br>
App ID: <input type="text" name="lname" /><br><br>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
And this is the php page:
<html>
<body>
<?php
$con = mysql_connect("xxx","xxx","xxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$sql="INSERT INTO app (fname, lname) VALUES('$_POST[fname]','$_POST[lname]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
</body>
</html>
Now, I want it to display 1 record added on the same page as the form and not have the form send me to a new insert.php page with it. Basically, I want the submit form to stay in the same page with maybe a a new message popping up to show that it has worked.
I have already looked through some answers on stackoverflow like using
if(isset($_POST['SubmitButton']))
but it doesn't work. Maybe I placed it wrong or used it incorrectly but could someone help me figure it out?
Just make it an action to itself, and set an if $_POST['submit'] to add the records, and you can have both in the same file. If you wish to do so without refreshing the page, you'll need to use AJAX.
<html>
<body>
<?php
if (isset($_POST['SubmitButton'])) {
$con = mysql_connect("xxx","xxx","xxx");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$sql="INSERT INTO app (fname, lname)
VALUES
('$_POST[fname]','$_POST[lname]')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
}
?>
<form action="" method="post">
App Name: <input type="text" name="fname" /><br><br>
App ID: <input type="text" name="lname" /><br><br>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
Also, mysql_* is deprecated, so you should consider converting to PDO or MySQLi to avoid SQL injection!

PHP Form - Return to original page after submission

I have a very simple html page that calls a php script to submit data from a form to a database. Once the user has submitted their data it would be great if they could get a message that says they've been added successfully and then redirect them to the page with the form. The code i'm using is as follows:
HTML file
<html>
<body>
<form action="insertcustomer.php" method="post" >
<p>First Name: <input type="text" name="firstname">
Last Name: <input type="text" name="lastname">
<P>Phone: <input type="text" name="phone"> Email: <input type="text" name="email"></P>
Address1: <input type="text"name="address1"> Address2: <input type="text" name="address2"> City:<input type="text" name="city">
<select name="Gender" id="Gender">
<option value="">Select One</option>
<option value = "1">Female</option>
<option value = "2">Male</option>
</select> <input value="Add" type="submit"> </form> </body>
</html>
PHP file:
<?php
$con=mysqli_connect("centos-db.local","customerinfo","password","customerinfo");
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO `customers` (`firstname`, `lastname`, `email`,
`phone`, `address1`, `address2`, `city`, `gender`) VALUES
('$_POST[firstname]','$_POST[lastname]',
'$_POST[email]','$_POST[phone]', '$_POST[address1]' ,'$_POST[address2]'
,'$_POST[city]' , '$_POST[gender]' )"; if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Customer Added"; mysqli_close($con);
?>
Any help you can give would be greatly appreciated!
Cheers
Just add a redirect to your homepage, like:
<?php
header('Location: http://www.example.com/');
exit;
?>
header reference page
You should also consider to escape the user input, for security purposes.
You could either use javaScript: document.location.href="myFile.php";
Or you could post your original form to the same page the form is in and handle the message there. That would also facilitate the displaying of error messages, if any.
use PHP's Header() function
header("Location: {$_SERVER['HTTP_REFERER']}");
exit;
Try this it will work :
you can show the successfully submit message on the same page.It will reduce load time of page and increase user experience.
index.php :
<?php
if(isset($_POST['submit']))
{
$con=mysqli_connect("centos-db.local","customerinfo","password","customerinfo");
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO `customers` (`firstname`, `lastname`, `email`,
`phone`, `address1`, `address2`, `city`, `gender`) VALUES
('$_POST[firstname]','$_POST[lastname]',
'$_POST[email]','$_POST[phone]', '$_POST[address1]' ,'$_POST[address2]'
,'$_POST[city]' , '$_POST[gender]' )"; if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Customer Added"; mysqli_close($con);
}
?>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<p>First Name: <input type="text" name="firstname">
Last Name: <input type="text" name="lastname">
<P>Phone: <input type="text" name="phone"> Email: <input type="text" name="email"></P>
Address1: <input type="text"name="address1"> Address2: <input type="text" name="address2"> City:<input type="text" name="city">
<select name="Gender" id="Gender">
<option value="">Select One</option>
<option value = "1">Female</option>
<option value = "2">Male</option>
</select> <input value="Add" type="submit" name="submit"> </form> </body>
</html>
Here, <?php echo $_SERVER['PHP_SELF']?> redirect you on the same page from where you submit the form.
You can make use of PHP's Header() function
give this a try. Im afraid Im not able to test it as I dont have Apache installed on my machine.
$con=mysqli_connect("centos-db.wireddog.local","customerinfo","password","customerinfo");
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO `customers` (`firstname`, `lastname`, `email`,
`phone`, `address1`, `address2`, `city`, `gender`) VALUES
('$_POST[firstname]','$_POST[lastname]',
'$_POST[email]','$_POST[phone]', '$_POST[address1]' ,'$_POST[address2]'
,'$_POST[city]' , '$_POST[gender]' )"; if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Customer Added"; mysqli_close($con);
header('Location: '.$_SERVER['PHP_SELF']); //Redirect to the same page
die;
p.s I had to remove the php opening and closing tags as SO does not seem to like rendering the tag in editor.
You can use another action.
<form action="/" method="post" >
Set a post route/check if the post variables are set and if so give the message.
A common problem here is that if you reload the page the post data will be sent again. That is why you normally use Post-Redirect-Get. You could use something like this at the end of yoour php script.
header("Location: {$_SERVER['HTTP_REFERER']}");
exit;
Notice: If you redirect from another Script the only possibility to display a message is to send a param in the url or to save it to a database and request the latest message on the originial page.

Trying to write to a MySQL database with a PHP form

I'm trying to do a simple write to database with an HTML form, using PHP.
I've run the SQL query in the database and it works perfectly. However, using the form doesn't work. I'm not sure why. Any help? The user/pass/db name are all correct.
<?php
if(isset($_POST['submit']))
{
$con = mysql_connect("localhost","delives0_ideas","ideas");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("delives0_ideas", $con);
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES ('$_POST['firstName']','$_POST['lastName']', '$_POST['email']', '$_POST['idea']')");
//also email it to us besides writing it into the database
mysql_close($con);
?>
<form method="post">
<strong>First name:</strong> <input type="text" name="firstName"/>
<br/>
<strong>Last name:</strong> <input type="text" name="lastName"/>
<br/>
<strong>Email:</strong> <input type="text" name="email"/> #####Put a javascript checker for valid emails, like name#site.com format
<br/>
<br/>
<strong>Idea:</strong>
<br/>
<textarea rows="10" cols="30" name="idea">
Hit us with your best shot.
</textarea>
<br/>
<input name="submit" type="submit" value="Submit"/>
</form>
You forgot the "action = nameofyourpage.php" inside the form markup. And I would add a "or die (mysql_error())" at the end of your query to check the syntax of the request.
you've got a few errors in your script - please check the following
http://pastie.org/1056569
<?php
if(isset($_POST['submit']))
{
$con = mysql_connect("localhost","delives0_ideas","ideas");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("delives0_ideas", $con);
$sqlCmd = sprintf("INSERT INTO data (firstName, lastName, email, idea)
VALUES ('%s','%s','%s','%s')",
mysql_real_escape_string($_POST["firstName"]),
mysql_real_escape_string($_POST["lastName"]),
mysql_real_escape_string($_POST["email"]),
mysql_real_escape_string($_POST["idea"]));
mysql_query($sqlCmd);
mysql_close($con);
}
?>
<form method="post">
<strong>First name:</strong> <input type="text" name="firstName"/><br/>
<strong>Last name:</strong> <input type="text" name="lastName"/><br/>
<strong>Email:</strong> <input type="text" name="email"/>
<strong>Idea:</strong><br/>
<textarea rows="10" cols="30" name="idea">Hit us with your best shot.</textarea><br/>
<input name="submit" type="submit" value="Submit"/>
</form>
You already have the answer to your question as to why it was not working, but please check this article about SQL injection attacks before putting this code into production.
you have error
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES
('$_POST['firstName']','$_POST['lastName']', '$_POST['email']', '$_POST['idea']')");
Error = '$_POST['firstName']' you have chatter ' in post field
and you can change
$firstname = $_POST['firstName'];
$lastname = $_POST['lastName'];
$email = $_POST['email'];
$idea = $_POST['idea'];
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES ('{$firstname}','{$lastname}', '{$email}', '{$idea}')");
or with mysql query
mysql_query("INSERT INTO data SET firstName='{$firstname}', lastName='{$lastname}',
email='{$email}', idea='{$idea}'");

Categories