I am simply trying to add form data(email, date) to mysql database. Below is my code. It looks fine but for some reason, every time I submit the form, it doesn't do anything. I don't get any error messages. The only change I see after submit is this in the browser url search field at the top. "/localhost/?email=&submit=Notify+Me"
The database is connected and the table/column names match correctly. The form itself simply does not process. Can you take a look and see if there's anything wrong with it?
<?php
if(isset($_POST['submit'])) {
$email = trim($_POST['email']);
if(empty($_POST['email'])) {
$error = 'Please enter your email address.';
} else {
$newEmail = $email;
$date = date('Y-m-d H:i:s');
$insert = $db->prepare("INSERT INTO email_list(email, date) VALUES(:email, :date)");
$insert->bindParam(':email', $newEmail);
$insert->bindParam(':date', $date);
$insert->execute();
$result = $insert->execute();
if($result == false) {
$error = 'There seems to be a problem. Please try again.';
} else {
$success = 'Success.';
}
}
}
?>
<div id="error"><?php echo $error; ?></div>
<div id="success"><?php echo $success; ?></div>
<form action="" method="post">
<input type="text" name="email" placeholder="Enter email address"/>
<input type="submit" name="submit" value="Notify Me"/>
</form>
You need to have method="post" but not type.
This is what you have:
<form action="" type="post" enctype="multipart/form-data">
This is what you need:
<form action="" method="post" enctype="multipart/form-data">
The form is submitting using GET instead of POST because you have type="post" rather than method="post" on the form. Type isn't a valid attribute so id defaults to GET and then is ignored by your script since you are checking for $_POST.
Related
I'm trying to update the user password in this code. I know it is not reliable since it does not has SQL injection prevention feature, I'm just trying to learn here.
anyway, using $_request variable in my code does not work with the database query, it works when I want to display the variable with echo.
PHP code:
$newPassword=$_POST['newPassword'];
$confirmPassword=$_POST['confirmPassword'];
$userID1=$_REQUEST['ID'];
$code=$_GET['$code'];
echo "<h1>Hello " . $userID1 . "</h1>";
if (isset($_GET['submit']))
{
if($newPassword == $confirmPassword ){
mysql_query("UPDATE facultymember SET password='$newPassword' WHERE ID='$userID1'");
$message = "Your password has been updated.";
}
else
{
$message = "New password does not equal Confirm password";
}
}
HTML form:
<form name="frmChange" action='newpass.php' method="GET" onSubmit="return validatePassword()">
<div style="color:red;" "class="message"><?php if(isset($message)) { echo $message; } ?></div>
Enter a new password
<input type="text" name="newPassword">
Re-enter the new password
<input type="text" name="confirmPassword">
<input name="submit" type="submit" value="Save Changes">
</form>
wrong object to get value , when you are submitting GET request method="GET"
$newPassword=$_POST['newPassword'];
$confirmPassword=$_POST['confirmPassword'];
or
$newPassword=$_GET['newPassword'];
$confirmPassword=$_GET['confirmPassword'];
and no ID param also attached
I am trying to do a login with MySQL, but it's not working. Basically I'm trying to check the login and password posted against my DB, but it's not working for some reason. Could someone give me a hint?
login.php
include "conexao.php";
$result = mysql_query("SELECT * FROM usuario WHERE login = '".$_POST['login']."' AND senha = '".$_POST['senha']."'") or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
session_start();
if ($_POST['login'] && $_POST['senha']) {
if ($row['login'] == $_POST['login'] && $row['senha'] == $_POST['senha']) {
$_SESSION['login'] = $row['login'];
$_SESSION['senha'] = $row['senha'];
header("Location: index.php");
} else {
unset ($_SESSION['login']);
unset ($_SESSION['senha']);
header("Location: login2.php?i=n");
}
}
}
HTML form
<form method="post" action="login.php" class="cbp-mc-form" autocomplete="off">
<label for="login">Login</label>
<input type="text" name="login" id="login" /><br />
<label for="senha">Senha</label>
<input type="password" name="senha" id="senha" /><br />
<center><input class="cbp-mc-submit" type="submit" value="Login""/></center>
</form>
Dear Brother try the following code, (I edited your code)
I hope it will work in your case, but if you're using the same code for production, than please take care of the Sanitization.
the code I edited for you is as follows (if it still doesn't work, than there might be some error in your database connection).
The PHP Script:
<?php
session_start(); // better to start the session in the begining,
//in some cases it doesn't work in the mid of the document'
include 'conexao.php';
if (isset($_POST['login']) && isset($_POST['senha'])) // check if both the form fields are set or not
{
// Values coming from the user through FORM
$login_form = $_POST['login'];
$senha_form = $_POST['senha'];
// query the database only when user submit the form with all the fields filled
$result = mysql_query("SELECT * FROM usuario WHERE login='$login_form' AND senha='$senha_form'") or die (mysql_error());
while ($row = mysql_fetch_assoc($result))
{
// values coming from Database
$login_db = $row['login'];
$senha_db = $row['senha'];
}
// compare the values from db to the values from form
if ($login_form == $login_db && $senha_form == $senha_db)
{
// Set the session only if user entered the correct username and password
// it doesn't make sense to set session even if the user entered wrong values
$_SESSION['login'] = $login_db;
$_SESSION['senha'] = $senha_db;
header("Location: index.php");
}
else
{
header("Location: login2.php?i=n");
}
}
?>
The HTML: (exactly your html copied)
<form method="post" action="login.php" class="cbp-mc-form" autocomplete="off">
<label for="login">Login</label>
<input type="text" name="login" id="login" /><br />
<label for="senha">Senha</label>
<input type="password" name="senha" id="senha" /><br />
<center><input class="cbp-mc-submit" type="submit" value="Login""/></center>
</form>
from PHP Header not redirecting
I added ob_start(); on the very first line and it worked.
I am setting up my custom blog's basic submission system.
This is the PHP section of it that I try to submit the inserted data into the database
<?php
session_start();
if(!isset($_SESSION['user_id'])){
header('Location: login.php');
exit();
}
include('../includes/db_connect.php');
if(isset($_POST['submit'])){
$newTitle = $_POST['newTitle'];
$newPost = $_POST['newPost'];
$my_date = date("Y-m-d H:i:s");
if(!empty($newPost))
if(!empty($newTitle)){
$sql="INSERT INTO posts (title, body)
VALUES($newTitle, $newPost)";
$query = $db->query($sql);
if($query){
echo "Post entered to database";
}else{
echo "Error Submitting the data";
}
}
}
?>
Then There is the submission form, I am pretty sure this is the faulty end for some reason, but I cannot find out why.
<form action="<?php echo $_SERVER['PHP_SELF']?>"name="newTitle" method="post">
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<p>Title:</p><br><input type="text" name="newTitle">
<textarea name="newPost" cols="110" rows="25"/></textarea><br>
<label for="newPost">Add New Post</label><input type="submit" name="submit" value="submit"/>
</form>
This is the database's table:
post_id (A_I)
user_id
title
body
category_id
posted(datetime)
Bear in mind that I am a rookie in this area, so don't be too harsh :)
Use single quote for strings:
$sql="INSERT INTO posts (title, body) VALUES ('$newTitle', '$newPost')";
//^ ^ ^ ^
Notice:
Try to use PDO and param binding in your projects to prevent sql injection.
Nice Tutorial about PDO
Use single form tag only:
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<p>Title:</p><br><input type="text" name="newTitle">
<textarea name="newPost" cols="110" rows="25"/></textarea><br>
<label for="newPost">Add New Post</label>
<input type="submit" name="submit" value="submit"/>
</form>
And in your php code, you can check youe data by using isset() function
if(isset($_POST['submit'])){
if(isset($_POST['newTitle']) && ($_POST['newPost']))
$newTitle = $_POST['newTitle'];
$newPost = $_POST['newPost'];
$my_date = date("Y-m-d H:i:s");
$sql="INSERT INTO posts (title, body)
VALUES('$newTitle', '$newPost')"; //use variable in single quote.
$query = $db->query($sql);
if($query){
echo "Post entered to database";
}else{
echo "Error Submitting the data";
}
}
I am having the hardest time of my life for not understanding the basics of the POST REDIRECT GET pattern in forms that submit to themselves.
The main problem is that when the user goes back or refreshes the page, I get duplicate entries in the database
So basically I have a page that contains two forms, each one submits to itself.
I have some code implemented regarding the PRG pattern but it doesn't seem to work.
I'll post a brief example where I'll try to explain what I am doing.
<?php
function saveUser1($UserName_1)
{
include 'db_conn.php';
//MySQL code etc...
if($result) return 1; //registro correcto
else return -2; //error
header('Location: samepage.php' , true, 303);
exit();
}
function saveUser2($UserName_2)
{
include 'db_conn.php';
//MySQL code etc...
if($result) return 1; //registro correcto
else return -2; //error
header('Location: samepage.php' , true, 303);
exit();
}
$error1 = 0;
$error2 = 0;
if(isset($_POST['userForm1']))
{
$error1 = saveUser1(clean_form($_POST['txtUserName_1']);
}
if(isset($_POST['userForm2']))
{
$error2 = saveUser2(clean_form($_POST['txtUserName_2']);
}
?>
Now the HTML
<form action="" name="userForm1" method="POST">
<label for="data">Some Data</label>
<input type="text" value="some test data to post" name="txtUserName_1" id="txtUserName_1" /><br />
<input type="submit" name="userForm1" id="userForm1"/>
</form>
<form action="" name="userForm2" method="POST">
<label for="data">Some Data</label>
<input type="text" value="some test data to post" name="txtUserName_2" id="txtUserName_2" /><br />
<input type="submit" name="userForm2" id="userForm2"/>
</form>
I just created this code in example of what I am trying to accomplish, but I haven't had any luck with the PGR pattern.
Could you guys tell me where the error is? Or redirect me (no kidding) to some good tutorial regarding this subject?
I have been looking to a lot of questions / answers, blogs but I can't find anything really solid (from my point of view).
Thanks in advance.
Below is sample code if you want try.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
Password: <input type="password" name="password">
<input type="submit" value="submit" name="send">
</form>
PHP Code and common.php is database connection file
<?php
require_once "common.php";
if(isset($_REQUEST['send']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$check = "SELECT * FROM user WHERE name = '".$name."' AND email = '".$email."' AND password = '".$password."'";
$check_result = mysql_query($check) or die(mysql_error());
if(mysql_num_rows($check_result) > 0)
{
header('Location : post.php');
}
else
{
$sql = "INSERT INTO user (name,email,password) VALUES ('$name','$email','$password')";
$result = mysql_query($sql) or die(mysql_error());
}
}
?>
Instead of checking for the form name itself check for a unique field within the form. E.g. If(isset($_POST[txtUserName_1'']))
The form name itself won't exist in the post.
To see what gets posted try:
print_r($_POST);
exit;
Maybe you have to set the post action to the same page.
And your form should not have the same name as your submit buttons(not sure about that).
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<label for="data">Some Data</label>
<input type="text" value="some test data to post" name="data" id="data" /><br />
<input type="submit" name="submit1" id="userForm1"/>
</form>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" name="form2" method="POST">
<label for="data">Some Data</label>
<input type="text" value="some test data to post" name="data" id="data" /><br />
<input type="submit" name="submit2" id="userForm2"/>
</form>
For the php:
if(isset($_POST['submit1']))
{
$error1 = saveUser1(clean_form($_POST['txtUserName_1']);
}
if(isset($_POST['submit2']))
{
$error1 = saveUser1(clean_form($_POST['txtUserName_2']);
}
you can add a hidden field for checking if its executed:
<input type="hidden" name="executed" value="0"/>
then you can set it to 0 when you have executed the mysql query
function saveUser1($UserName_1)
{
if($_POST['executed'] == 0)
{
include 'db_conn.php';
//MySQL code etc...
if($result) $_POST['executed'] = 1; //registro correcto
header('Location: samepage.php' , true, 303);
exit();
}
}
I am creating an email subscription form in PHP and want to check for a valid address as well as if the email is already existing in my database.
My code is connecting to my database and inserting but the validation as well as checking for an existing email are not working.
No matter what I type into my form it inserts it into my database even if I don't type anything.
Here is all of my code:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset>
<legend>Subscribe to Our Newsletter </legend>
<?php if ($feedback!='')
echo('<p>'.$feedback.'</p>'); ?>
<label>Name: <input name="name" type="text" value="<?php echo $name; ?>" /></label>
<label>Email: <input name="email" type="text" value="<?php echo $email; ?>" /></label>
<label><input type="submit" value="Sign Up!" /></label>
</fieldset>
</form>
<?php
$feedback='';
if (!$email) {
$feedback .= '<strong>Please enter your email address</strong><br />';
}
if (!$name) {
$feedback .= '<strong>Please enter your name</strong><br />';
}
list($username, $mailDomain) = explode("#", $email);
if (!#checkdnsrr($mailDomain, "MX")) {
$feedback .= '<strong>Invalid email domain</strong><br />';
}
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email)) {
$feedback .= '<strong>Your email address doesn\'t appear to be valid - please check and try again';
}
function cleaninput($value, $DB) {
if (get_magic_quotes_gpc()) {
$value = stripslashes( $value );
}
return mysql_real_escape_string( $value, $DB );
}
$name=$_POST['name'];
$email=$_POST['email'];
include_once "connect.php";
$sql = mysql_query("SELECT * FROM subscribers WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if ($numRows>0) {
$feedback = '<strong>That email address is already subscribed.</strong>';
}
$insertresult = mysql_query("INSERT INTO subscribers (name, email) VALUES('$name', '$email')") or die (mysql_error());
if ($insertresult) {
$completed = true;
}
if($competed=false) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?> method="post">
<fieldset>
<legend>Subscribe to OUr Newsletter </legend>
<?php
if ($feedback!='')
echo('<p>'.$feedback.'</p>'); ?>
<label>Name: <input name="name" type="text" value="<?php echo $name; ?>" /></label>
<label>Email: <input name="email" type="text" value="<?php echo $email; ?>" /></label>
<label><input type="submit" value="Sign Up!" /></label>
</fieldset>
</form>
<?php
}
else {
echo('Thanks - you have subscribed to our newsletter successfully. You can unsubscribe at any time by clicking the link at the bottom of each email we send.');
}
?>
Also the last echo in my script is always there. It is displayed under my my form always. Not sure why that is. Maybe I have it in the wrong place in my code.
else {
echo('Thanks - you have subscribed to our newsletter successfully. You can unsubscribe at any time by clicking the link at the bottom of each email we send.');
}
Thanks!
This code is a bit of a mess, to be honest :) It's slightly difficult to read, but I can see at least two problems: you write $competed rather than $completed in one of your if statements, and you don't actually have the INSERT query in an if block: it'll always execute. Try putting it in an else block after the if block that checks whether the address is already in your database, like this:
$sql = mysql_query("SELECT * FROM subscribers WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if ($numRows>0) {
$feedback = '<strong>That email address is already subscribed.</strong>';
}
else {
$insertresult = mysql_query("INSERT INTO subscribers (name, email) VALUES('$name', '$email')") or die (mysql_error());
}
You also don't need to use both addslashes and mysql_real_escape_string; just the latter will do. And I'm not sure why you have the same form in your code twice. Surely once should do? :)