Inserting E-mail Into DB - php

Trying to build an email list in a database. I made this code, but it's not working and i'm not getting any errors. Am I on the right track?
HTML:
<div id="signup">
<h1>Sign-Up For Our Newsletter!</h1>
<form method="post" action="scripts/php/addSubscription.php">
<label for="email">E-mail: </label><input type="email" name="email" size="75"> <input type="submit">
</form>
</div>
PHP:
require('settings/globalVariables.php');
require('settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ($email)";
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo 'Sorry, An error occured. Please try again.';
}
mysqli_close($conn);
$conn is a variable in mysqli_connect.php
Adding contents of mysqli_connect.php just for reference:
<?php
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS);
?>
I use this on several databases and it connects each time.
EDIT:
Updated code per answers/comments and still nothing is happening.
require('settings/globalVariables.php');
require('settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo "Error: ".mysqli_error($conn);
}
mysqli_close($conn);
SOLVED:
require('/home/jollyrogerpcs/public_html/settings/globalVariables.php');
require('/home/jollyrogerpcs/public_html/settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo "Error: ".mysqli_error($conn);
}
mysqli_close($conn);

You are currently getting an error but your code doesn't show you. Print the error for a start:
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo "Error: ".mysqli_error($conn);
}
The real error you are getting is a syntax error. This is how your generated SQL looks like:
INSERT INTO newsletterusers (email) VALUES (hello#email.com)
Note that there are no quotes around it, you can fix it by surrounding $email with quotes:
$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";

Related

My PhP script doesn't write on my MySql database

I started to learn PHP and I need your help because I'm trying to write on my MySQL database. The script seems fine (for me :D) and it doesn't give me errors. But when I submit the query the data doesn't appear inside my MySQL database. Could you help me, please?
This is my HTML/PHP code:
<?php
session_start();
$_SESSION['message'] = '';
//connection variables
$host = '127.0.0.1';
$user = 'root';
$password = 'MyPassword';
$database= 'test';
$port= '3306';
//create mysql connection
$mysqli = new mysqli($host, $user, $password,$database,$port);
if ($mysqli->connect_errno) {
printf("Connection failed: %s\n", $mysqli->connect_error);
die();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $mysqli->real_escape_string($_POST['name']);
$email = $mysqli->real_escape_string($_POST['email']);
if ($mysqli->query("INSERT INTO 'contatti' ('name', 'email') VALUES ('$name','$email')") == true) {
$_SESSION['message'] = "registration succesfull! Added $name to the database";
} else {
$_SESSION['message'] = "User can't be added to the database";
}
}
?>
<!DOCTYPE html>
<html>
<center>
<h1>Inputs</h1>
<form class="form" action="welcome.php" method="post" autocomplete="off">
<div class="alert alert-error"><?= $_SESSION['message'] ?></div>
<input type="text" name="name" placeholder="Insert your name" /> <br>
<input type="email" name="email" placeholder="Insert your email"/><br>
<input type="submit" name="submit" placeholder="Submit"/>
</form>
</center>
</html>
This is the database:
[Table structure]
[]1
[Database info]
Please use preapared statements and bind parameters instead: http://php.net/manual/en/mysqli-stmt.bind-param.php
You can also debug your mysql server response with error_list:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$stmt = $mysqli->prepare("INSERT INTO `contatti` (`name`, `email`) VALUES (?,?)");
$stmt->bind_param('ss', $name, $email);
if ($stmt->execute()) {
/* ... */
}
else {
$errors = $stmt->error_list;
/* ... */
}
}
You should use prepared statements for MYSQL and PHP, if possible, at least to protect yourself from SQL injection (SO Ref).
That said, when you read this line :
if ($mysqli->query("INSERT INTO 'contatti' ('name', 'email') VALUES ($name,$email)") == true)
You are concatening strings into your SQL query without quotes, and the query string look like (with $name = 'test', $email = 'test#test' :
INSERT INTO 'contatti' ('name', 'email') VALUES (test,test#test) : incorrect syntax
You must escape strings on SQL :
if ($mysqli->query("INSERT INTO 'contatti' ('name', 'email') VALUES ('$name', '$email' )") == true)
The resulting query should look like : INSERT INTO 'contatti' ('name', 'email') VALUES ('test','test#test')
Edit : please note that the table (contatti) and the fields name (name, email) are supposed to be surrounded by backticks, not single quotes (I cannot escape backticks in a quote), and variables $name and $email by single quotes
You have a syntax error in your query, try to change the INSERT query inside the if condition here:
if ($mysqli->query("INSERT INTO 'contatti' ('name', 'email') VALUES ('$name','$email')") == true) {
$_SESSION['message'] = "registration succesfull! Added $name to the database";
} else {
$_SESSION['message'] = "User can't be added to the database";
}
To be like this:
if ($mysqli->query("INSERT INTO contatti (name, email)
VALUES('$name', '$email')") == true) {
$_SESSION['message'] = "registration succesfull! Added $name to the database";
} else {
$_SESSION['message'] = "User can't be added to the database";
}

SQLSTATE[42000]: Syntax error or access violation: 1064 sign in form

I am getting into PHP/MySQL code and I've searched all over for a solution to this problem but no answers match my issue.
My code is very simple but I can't find whats causing this error
<?php
$servername = "localhost";
$username = "langalungalangalunga";
$password = "langalungalangalunga";
$dbname = "user_main";
$client_username = $client_password = $client_email = "";
$usernameErr = $passwordErr = $emailErr = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!empty($_POST['username'])) {
$client_username = test_input($_POST['username']);
} else {
$usernameErr = "No input on UserName";
}
if (!empty($_POST['password'])) {
$client_password = test_input($_POST['password']);
} else {
$passwordErr = "No input on Password";
}
if (!empty($_POST['email'])) {
$client_email = test_input($_POST['email']);
} else {
$emailErr = "No input on Email";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO user_main (UserName, Password, Email)
VALUES ($client_username, $client_password, $client_email)";
// use exec() because no results are returned
$conn->exec($sql);
echo "<script> alert('Success!');</script>";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
The error points at line 2 of the email part
check the manual that corresponds to your MySQL server version for the right syntax to use near ' , email#email.com)' at line 2
<form class="" action='<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>' method="post">
<label for="username">Username</label>
<input type="text" name="username" value="<?php echo htmlspecialchars($_SERVER['username']) ?>">
<label for="password">Password</label>
<input type="password" name="password" value="">
<label for="email">Email</label>
<input type="email" name="email" value="">
<button type="submit" name="button">Register</button>
</form>
I am sorry if it's my mistake somewhere but I am new to PHP all together so I dont really have a feel for the syntax
$sql = "INSERT INTO user_main (`UserName`, `Password`, `Email`)
VALUES ('$client_username', '$client_password', '$client_email')";
$conn->query($sql);
The above code is vulnerable to SQL injection. Use prepared statements as
$stmt = $conn->prepare("INSERT INTO user_main (`UserName`, `Password`, `Email`)
VALUES (:UserName, :Password, :Email)");//placeholders
$stmt->bindParam(':UserName', $client_username);//you do not need to escape inputs
$stmt->bindParam(':Password', $client_password);
$stmt->bindParam(':Email', $client_email);
if($stmt->execute() == true){
//all good
echo'Data successfully saved Securely!';
} else {
print_r($stmt->errorInfo());
exit;
}
An extra tip. Do not store your passwords in plain text. Use password_hash
$hashedPassword = password_hash($client_password, PASSWORD_DEFAULT);
On checking if the password matches the hash, use password_verify
if(password_verify($client_password, $hashedPassword)){// do this when logging in or during some other authentication
//all good
echo 'Password is Correct';
} else {
echo 'Password is InCorrect.Sorry';
}
change you insert sql code like below:
Try this:
$sql = "INSERT INTO user_main (UserName, Password, Email)
VALUES ('".$client_username."', '".$client_password."', '".$client_email."')";

Generic error message works with registration form, but need specific message for duplicate names

I created a registration form using PHP, html, and Bootstrap. This code works on a basic level, and if a duplicate username is entered it shows a generic error message since 'username' and 'email' are unique in my database. The problem with that is I want the user to understand what went wrong, so they don't repeatedly try to enter the same username or email over and over again. I didn't think about it until I finished the page. Doh!
This is the working php script for the generic message:
//FROM REGISTER.PHP
<?php
require_once('connect.php'); //<--MY DATABASE FILE
if(isset($_POST) & !empty($_POST)) {
$username = mysqli_real_escape_string($connection, $_POST['username']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password = sha1($_POST['password']);
$sql = "INSERT INTO `users` (username, email, password) VALUES ('$username', '$email', '$password')";
$result = mysqli_query($connection, $sql);
if($result) {
$successMessage = "User Registration Successful! Please Login.";
}
else { //GENERIC MESSAGE FOR ALL ERRORS, INCLUDING DUPLICATES
$failMessage = "Something went wrong. User Registration failed.";
}
}
?>
Here is my snippet of html, php, and Bootstrap:
<div class="container">
<!-- HERE ARE THE ALERT DIVS THAT POP UP -->
<?php if(isset($successMessage)){ ?><div class="alert alert-success text-center" role="alert"><?php echo $successMessage; ?> </div><?php } ?>
<?php if(isset($failMessage)){ ?><div class="alert alert-danger text-center" role="alert"><strong>Error: </strong> <?php echo $failMessage; ?> </div><?php } ?>
<form class="form-signin" method="POST">
The alerts pop up directly above the form, as seen in these snapshots:
I have tried so many things before coming here to no avail. For example, I tried:
$duplicate = mysqli_query("SELECT username FROM users WHERE username='".$_POST['username']."'");
//ALSO TRIED
//$duplicate = mysqli_query("SELECT username FROM users WHERE username = 'username');
if(mysqli_num_rows($duplicate) > 0) {
$failMessage = "Username already exists";
}
However, it completely skips over that and gives me the generic Error message. I've seen so many examples/answers on how to prevent duplicates, none of which are helping me figure this out.
I've read about creating separate indexes for username and email, but I would have to do more reading on databases to understand what that entails.
Use the below code:
Require to add $connection->errno == 1062
<?php
require_once('connect.php'); //<--MY DATABASE FILE
if(isset($_POST) & !empty($_POST)) {
$username = mysqli_real_escape_string($connection, $_POST['username']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password = sha1($_POST['password']);
$sql = "INSERT INTO `users` (username, email, password) VALUES ('$username', '$email', '$password')";
$result = mysqli_query($connection, $sql);
if($result) {
$successMessage = "User Registration Successful! Please Login.";
}else{
if ($connection->errno == 1062) {
$failMessage = "User already exists";
}else{
$failMessage = "Something went wrong. User Registration failed.";
}
}
?>
//FROM REGISTER.PHP
require_once('connect.php'); //<--MY DATABASE FILE
if(isset($_POST) & !empty($_POST)) {
$username = mysqli_real_escape_string($connection, $_POST['username']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password = sha1($_POST['password']);
// checking if username already exists
$duplicate = mysqli_query("SELECT username FROM users WHERE username='".$username."'");
if(mysqli_num_rows($duplicate) > 0) {
$failMessage = "Username already exists";
}else{
$sql = "INSERT INTO `users` (username, email, password) VALUES ('$username', '$email', '$password')";
$result = mysqli_query($connection, $sql);
if($result) {
$successMessage = "User Registration Successful! Please Login.";
} else { //GENERIC MESSAGE FOR ALL ERRORS, INCLUDING DUPLICATES
$failMessage = "Something went wrong. User Registration failed.";
}
}
}
?>
there is mistake in your condition "if(isset($_POST) & !empty($_POST))" it is not correctly working.try with this "if(isset($_POST['save']) & !empty($_POST['save']))" where 'save' is your submit button's name

Can't enter data in to the database using mysql

This is the php file that going to enter data into the mysql database. When I run it, browser shows "connected successfully selected successfully Executing inside fileNot Inserted". but it's not going to show any errors. And data is not insert in to the database. What's wrong with this code.
*dbConnection.php
<?php
$dbhost="localhost";
$dbuser="root";
$dbPassword="123";
$database="medicalcenter";
$connection = mysqli_connect($dbhost,$dbuser,$dbPassword) or die("unable to connect");
if($connection){
echo 'connected successfully ';
}else{
echo 'not connected';
}
$dbSelect=mysqli_select_db($connection,$database);
if($dbSelect){
echo 'selected successfully';
}else{
echo 'not selected';
}
?>
*insert.php
<?php
include 'dbConnection.php';
echo "Executing inside file";
$firstName = filter_input(INPUT_POST,'firstname');
$secondName = filter_input(INPUT_POST,'lastname');
$address1 =filter_input(INPUT_POST,'address1');
$address2 =filter_input(INPUT_POST,'address2');
$city =filter_input(INPUT_POST,'city');
$email =filter_input(INPUT_POST,'email');
$age =filter_input(INPUT_POST,'age');
$gender =filter_input(INPUT_POST,'gender');
$sql= "INSERT INTO patient(FirstName,LastName,AddressLine1,AddressLine2,City,Email,Age,Gender) VALUES ('$firstName','$secondName','$address1','$address2','$city',$email','$age','$gender')";
if(mysqli_query($connection,$sql)){
echo 'Inserted successfully';
}else{
echo 'Not Inserted';
}
mysqli_close($connection);
?>
$sql= "INSERT INTO patient(FirstName,LastName,AddressLine1,AddressLine2,City,Email,Age,Gender) VALUES ('$firstName','$secondName','$address1','$address2','$city',$email','$age','$gender')";
check your above line you have forgot ' before email please check with below line. may it helps you.
$sql= "INSERT INTO patient(FirstName,LastName,AddressLine1,AddressLine2,City,Email,Age,Gender) VALUES ('$firstName','$secondName','$address1','$address2','$city','$email','$age','$gender')";

MySQL Insert occurs twice on one submit

I have this PHP file that handle's users input to signup using mysql... I have a problem with it that makes the users input be entered twice... So, this was only one input into the signup form. Below is about half of my signup form (the most useful part)...
if ($_SERVER["REQUEST_METHOD"] == "POST") {
require("db-settings.php");
// Security
if (empty($_POST['name'])) {
echo "Sorry, fullname input was empty, please retry if you like.";
die();
} else {
$fullname = $_POST['name'];
}
if (empty($_POST['email'])) {
echo "Sorry, email input was emty, please retry if you like.";
die();
} else {
$email = $_POST['email'];
}
if (empty($_POST['password'])) {
echo "Sorry, password was empty, please retry if you like.";
die();
} else {
$password = $_POST['password'];
// If password variable is success to set, let's encrypt it now!
$password = password_hash($password, PASSWORD_DEFAULT)."\n";
}
// Log users IP and store in variable
$ip = $_SERVER["REMOTE_ADDR"];
// Create connection
$conn = new mysqli($servername, $username, $db_password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `table-ex` (fullname, email, password, ip) VALUES ('$fullname', '$email', '$password', '$ip')";
$stmt = $conn->prepare($sql);
//$stmt->bind_param('sss', $fullname, $email, $password, $ip);
$stmt->execute();
if ($conn->query($sql) === TRUE) {
echo "New user was created successfully, please wait for activation...";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
So, with all this here. I will also give the entire form section in the html code below...
<form action="signup.php" method="post">
<h1>Sign up</h1><br/>
<span class="input"></span>
<input type="text" name="name" placeholder="Full name" title="Format: Xx[space]Xx (e.g. John Doe)" autofocus autocomplete="off" required pattern="^\w+\s\w+$" />
<span class="input"></span>
<input type="email" name="email" placeholder="Email address" required />
<span id="passwordMeter"></span>
<input type="password" name="password" id="password" placeholder="Password" title="Password min 10 characters. At least one UPPERCASE and one lowercase letter" required pattern="(?=^.{10,}$)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$"/>
<button type="submit" value="Sign Up" title="Submit form" class="icon-arrow-right"><span>Sign up</span></button>
</form>
So, there must be something in the code that makes it enter in twice... Plus, how do I reset the id numbers? Cause every time I make a new user, and this happens (which is every time) then I just delete the users and it still counts as though they still exist.
It's because of this line. You don't need to put an if else statement.
if ($conn->query($sql) === TRUE) {
echo "New user was created successfully, please wait for activation...";
}
Simply do this-
$sql = "INSERT INTO `table-ex` (fullname, email, password, ip) VALUES ('$fullname', '$email', '$password', '$ip')";
$stmt = $conn->prepare($sql);
//$stmt->bind_param('sss', $fullname, $email, $password, $ip);
//Set the variables here for $fullname, $email, $password and $ip
if($stmt->execute())
{
echo "New user was created successfully, please wait for activation...";
}
else { echo "There was a problem";}
$stmt->close();
$conn->close();
UPDATE
For the id part, I assume you are using auto increment but I would suggest you to insert them manually instead of relying on it. I would suggest you to use a unique key derivation function and encoding them (in case you would prefer them to be plaintext and using them as IDs).
If you want to track how many entries are in there, you can always count the number of rows with mysqli_num_rows().
You used both execute() and query(), thus executing twice.
Firstly, it inserted 1 row at $stmt->execute();. Then it inserted another row at $conn->query($sql).
$stmt->execute();
if ($conn->query($sql) === TRUE) {
echo "New user was created successfully, please wait for activation...";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You should only $stmt->execute();:
if ($stmt->execute()) {
echo "New user was created successfully, please wait for activation...";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Note:
It's a better practice is to stick with prepared statements and use execute() for increased security rather than using $conn->query($sql). More information of the difference at PDO's query vs execute.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
require("db-settings.php");
// Security
if (empty($_POST['name'])) {
echo "Sorry, fullname input was empty, please retry if you like.";
die();
} else {
$fullname = $_POST['name'];
}
if (empty($_POST['email'])) {
echo "Sorry, email input was emty, please retry if you like.";
die();
} else {
$email = $_POST['email'];
}
if (empty($_POST['password'])) {
echo "Sorry, password was empty, please retry if you like.";
die();
} else {
$password = $_POST['password'];
// If password variable is success to set, let's encrypt it now!
$password = password_hash($password, PASSWORD_DEFAULT)."\n";
}
// Log users IP and store in variable
$ip = $_SERVER["REMOTE_ADDR"];
// Create connection
$conn = new mysqli($servername, $username, $db_password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `table-ex` (fullname, email, password, ip) VALUES ('$fullname', '$email', '$password', '$ip')";
$stmt = $conn->prepare($sql);
//$stmt->bind_param('sss', $fullname, $email, $password, $ip);
if ($stmt->execute()) {
echo "New user was created successfully, please wait for activation...";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$stmt->close();
$conn->close();

Categories