My form for collecting visitors' mails for newsletter is not sending information to my database, instead just adding spaces with index adding up with no data
this is my html code
<form action="php/newsletter.php" method="post" >
<div class="input-group">
<input class="form-control" type="text" id="email" name="email" placeholder="E-mail ... ">
<span class="input-group-btn">
<button class="btn btn-primary subscribe" type="button" value="insert"><i class="pe-7s-paper-plane pe-2x"></i></button>
</span>
</div>
<!-- /input-group -->
</form>
and this is the php
<?php
$servername = "localhost";
$username = "pridedri_news";
$password = "BBIT/7949/1/1630";
$database = "pridedri_NEWSLETTER";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO subscribers (email)
VALUES ('$email')";
// use exec() because no results are returned
$conn->exec($sql);
echo "Request sent successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
//$conn = null;
?>
<Doctype! html>
<body>
<a href="http://pridedrivetours.co.ke/">Back</>
</body>
</html>
where could my mistake be?
You haven't defined $email in your PHP script. Also, you should use a prepared statement for queries with user inputs, to prevent SQL injection (http://bobby-tables.com) -> This is kinda important, please read about SQL injection. Its one of the biggest security issues with PHP websites and it allows 3rd persons to delete your whole database in a few seconds.
Also, to access data posted from a form, you always access the $_POST array, while the key ["email"] is the name of the input.
Try this code:
<?php
$servername = "localhost";
$username = "pridedri_news";
$password = "BBIT/7949/1/1630";
$database = "pridedri_NEWSLETTER";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $conn->prepare("INSERT INTO subscribers (email) VALUES (:email)");
$sql->bindParam(':email', $_POST["email"]);
// even exec() returnes true or false!!!!
if($conn->exec($sql)) {
echo "Request sent successfully";
}
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
//$conn = null;
?>
<Doctype! html>
<body>
<a href="http://pridedrivetours.co.ke/">Back</>
</body>
</html>
Declare $email before using it in mysql query
$email = $_REQUEST['email'];
I hope it will work for you
Related
Whenever I tried to insert data to the table of database it keeps echoing "Connection successful" from connection.phpThe connection successful in my insert.php file
insert.php code
<?php
include_once("connection.php");
if(isset($_POST['Add'])){
$productCat = $_POST['category'];
$insertQuery = $pdo->prepare("INSERT INTO products_tbl (productCategory) VALUES (:ucategory)");
$insertQuery->bindParam(':ucategory',$productCat);
$insertQuery->execute();
echo "<script>alert('Successfully Register')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
?>
connection code
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "Ecommercedb";
try{
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection success";
} catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
?>
forms
<form action="insert.php" method="post">
<label for="">Product Category</label>
<input type="text" name="category" id="" placeholder="Category">
<input type="submit" value="Submit" class="btn" name="Add">
</form>
I tried removing the echo enter image description heresince it wasn't needed but it only lead to
HTTP:500 error.
I have also checked the connection and it is successful.
I expected there would be an alert saying it is successfully inserted but instead I keep getting the connection success from my connection.php
It looks like your code is working as intended, and the issue is likely related to the way you are submitting your form. The "Connection successful" message is being printed because your connection to the database is working, but the form data is not being passed to the insert.php script.
Make sure that you are correctly specifying the action attribute of the form element, and that the method is set to "post". Also, check that the name attributes of the form elements match the names of the variables in the insert.php script.
Additionally, you can try adding some debugging statements to the insert.php script, such as var_dump($_POST) or echo $productCat to check if the values are being passed to the script correctly.
I'm having an issue with the header("Location: index.php?action=messagesent") it will not redirect after The user presses submit and the php is ran. Normally it will redirect but for some reason it's not working, It just reloads the page after they hit submit. But it does echo "Message Sent" right under the header code. Any ideas on why it is not redirecting? Thank You in advance.
Heres my Code:
<form action="" method="post">
<div class="form-group">
<label for="message">Reply</label>
<textarea class="form-control" id="message" name="message" rows="5"></textarea>
</div>
<button type="submit" name="sendmessage" class="btn btn-purple waves-effect waves-light">Send Message </button>
</form>
</div>
</div>
<?php
$servername = "localhost";
$username = "myusername";
$password = 'password';
$dbname = "database";
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);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO messaging
(fromid, toid, message, tousername,
fromusername,userprofile, sentdate, messagebefore)
VALUES (:fromid, :toid, :message, :tousername,
:fromusername, :userprofile, :sentdate, :messagebefore)");
// insert a row
$toid = $fromid;
$fromid = $_SESSION['user']['id'];
$messagebefore = $message;
$message = $_POST['message'];
$tousername = $row['fromusername'];
$fromusername = $_SESSION['user']['username'];
$userprofile = $row['userprofile'];
$sentdate = $date = date('H:i, jS F Y');
//Bind Inputs
$stmt->bindParam(':fromid', $fromid);
$stmt->bindParam(':toid', $toid);
$stmt->bindParam(':message', $message);
$stmt->bindParam(':tousername', $tousername);
$stmt->bindParam(':fromusername', $fromusername);
$stmt->bindParam(':userprofile', $userprofile);
$stmt->bindParam(':sentdate', $sentdate);
$stmt->bindParam(':messagebefore', $messagebefore);
$stmt->execute();
echo "Message Sent. ";
header("Location: inbox.php?action=messagesent");
}
catch(PDOException $e){
}
$conn = null;
?>
A header(Location: ...) will only work if you have not already sent output to the browser.
Earlier in your script you output the form, hence header() fails with an error message.
If you look in your error log, you will see the error message.
Add error reporting to the
top of your file(s) while testing right after your opening PHP tag for example
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Now you will see the errors on the browser page.
very new to this, i am currently trying to create a log in system for my website. i have created a html log in form which i plan to use for users to create accounts. i have created a php page which has my code to connect to the server which is shown below.
when i fill the form i dont get any output. I'm not sure if the php code is in the wrong place (it is as a separate file) or no output is expected. when a form is submitted, the database doesn't seem to change when i submit it manually while testing.
My end goal is to be able to add users to the table called users in my database.
Here is my code for my log in form:
<body>
<h2>Sign Up</h2>
<p></p>
<form action="Create_User.php" method="post">
<div class="imgcontainer">
<img src="http://fc05.deviantart.net/fs70/f/2012/361/1/6/albert_einstein_by_zuzahin-d5pcbug.jpg" alt="Einstein the lad" class="img" />
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Please Enter your desired Username" name="username" required />
<label><b>Password</b></label>
<input type="password" placeholder="Please Enter Your Desired Password" name="password" required />
<label><b>Email Address</b></label>
<input type="email" placeholder="Please Enter Your Email Address" name="email" required />
<label><b>Date Of Birth</b></label>
<input type="date" name="date_of_birth" required />
<label><b>First Name</b></label>
<input type="text" placeholder="Please Enter your first name" name="first_name" required />
<label><b>Surname</b></label>
<input type="text" placeholder="Please Enter your surname" name="surname" required />
</div>
<div class="container" style="background-color: #f1f1f1">
<button type="submit">Sign Up</button>
<button class="signinbtn" onclick="location.href='/AccountRelatedPages/SignIn.aspx'">Already have an account? Sign in here</button>
</div>
</form>
</body>
here is the code in my php file:
<?php
$servername = "localhost";
$username = "root";
$password = "rootpass";
$dbname = "synther_physics";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users (username, password, email, date_of_birth, first_name, surname)
VALUES ('<?php echo $_POST[$username];', '<?php echo $_POST[$password];', '<?php echo $_POST[$email], <?php echo $_POST[$date_of_birth];, <?php echo $_POST[$first_name], <?php echo $_POST[$surname];')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Again very new to all this so im trying my best to get my head around so please bear that in mind.
Thanks.
Putting all together from the comments, sql injections, password_hash(). for sql injections protection then u need use prepared statements. I won't say much a lot of important things were said in the comments, hope you went through them all, because I did.
This is how your code should look :
<?php
$servername = "localhost";
$username = "root";
$password = "rootpass";
$dbname = "synther_physics";
//Validate user inputs
$username = $_POST['username'];
$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_DEFAULT);
$email = $_POST['email']; //VALIDATE the email
$dob = $_POST['date_of_birth'];
$fname = $_POST['first_name'];
$sname = $_POST['surname'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users (username, password, email, date_of_birth, first_name, surname)
VALUES (?,?,?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssssss", $username, $hash, $email, $dob, $fname, $sname);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error : " . $conn->error; // on dev mode only
// echo "Error, please try again later"; //live environment
}
$conn->close();
?>
Edit :
if your php is on the same file and the html, then to avoid undefined indexes notice, you will need to check if the form was submitted, before processing. what you need to do is to have a name attribute to your form button.
then check if form is submitted.
<?php
$servername = "localhost";
$username = "root";
$password = "rootpass";
$dbname = "synther_physics";
//Validate user inputs
if(isset($_POST['buttonName'])){
$username = $_POST['username'];
$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_DEFAULT);
$email = $_POST['email']; //VALIDATE the email
$dob = $_POST['date_of_birth'];
$fname = $_POST['first_name'];
$sname = $_POST['surname'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users (username, password, email, date_of_birth, first_name, surname)
VALUES ('?,?,?,?,?,?')";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssssss", $username, $hash, $email, $dob, $fname, $sname);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error : " . $conn->error; // on dev mode only
// echo "Error, please try again later"; //live environment
}
$conn->close();
}
?>
Also you need to check if fields are set and not empty.
I have a user input form(HTML) that is supposed to take the information and insert it into a MySQL database via PHP. The PHP apparently executes and echoes "Your registration has completed successfully". A record is created in the database but the columns are blank(I have removed my server, database, and password from the PHP code).
HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<title>User Portal</title>
</head>
<div class="inputContainer">
<header>
User Information Portal
</header>
<form action="php/userPost.php" method="post">
<label for=firstName">First Name</label>
<input type="text" id=firstName" name="fname">
<br><br>
<label for="lastName">Last Name</label>
<input type="text" id="lastName" name="lname">
<br><br>
<label for="eMail">Email</label>
<input type="text" id="eMail" name="email">
<br><br>
<label class="labelRole" for="userRole">Role -</label><br>
<input type="radio" id="userRole" name="role" value="Instructor"> Instructor
<input class="submitButton" type="submit" name="submit" value="Register">
</form>
</div>
</body>
PHP:
<?php
$sname = "server-name";
$uname = "username";
$pword = "password";
$dbname = "web_tech_test";
$conn = new mysqli($sname, $uname, $pword, $dbname);
if ($conn->connect_error) {
die("Connection failure: " . $conn->connect_error);
}
$fname = !empty($_POST['firstName']);
$lname = !empty($_POST['lastName']);
$email = !empty($_POST['eMail']);
$role = isset($_POST['userRole']);
$sql = "INSERT INTO users (first_name, last_name, email, role)
VALUES ('$fname', '$lname', '$email', '$role')";
if ($conn->query($sql) === TRUE) {
echo "Your registration has completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
This creates a new record in the DB but all the columns are blank. Any ideas why this may be happening?
$fname = !empty($_POST['firstName']);
$lname = !empty($_POST['lastName']);
$email = !empty($_POST['eMail']);
$role = isset($_POST['userRole']);
this code returns a boolean, not a string value...
Use !empty() just for validation
example
if(empty($_POST['eMail'])) {
die("Email cannot be empty");
}
You're confusing the id and the name tags on the inputs.
The name tags are the ones which will be submitted as keys to your server.
Try this in your server php script after submitting your form to see which key/values are actually received by the server:
var_dump($_POST);
Also, if you want to check that all fields have been filled out, use something similar as this:
if (empty($_POST['firstName'])) {
die("firstname is empty!");
}
In your current example you're actually saving a boolean to your variables.
And, last but not least, never insert variables from a potentially unsafe source (like a user input) directly into your SQL. Use pdo: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers for this
Full code example to get you started:
//prepare your values
if (empty($_POST['fname']) || empty($_POST['lname']|| empty($_POST['email']|| !isset($_POST['role'])) {
die ("some values were empty or not set");
}
//prepare your database
$db = new PDO('mysql:host=server-name;dbname=web_tech_test;charset=utf8mb4', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //throw an exception if there is an error
//create your query
$stmt = $db->prepare("INSERT INTO users (first_name, last_name, email, role) VALUES (:first_name,:last_name,:email,:role)"); //create a query statement
$stmt->bindValue(":first_name", $firstName); //put your values into your statement
$stmt->bindValue(":last_name", $lastName);
$stmt->bindValue(":email", $email);
$stmt->bindValue(":role", $role);
if ($stmt->execute()) { //execute the query
echo "Your registration has completed successfully";
} else {
echo "Error :(";
}
Okay, I've looked everywhere. To begin with I have a form, a newsletter, that users enter their email into. Once they hit submit it checks a php form that takes that email and inputs it into an SQL database that stores the email. The problem is I get this error when submitting the form
Error: INSERT INTO emails (email) VALUES (random#yahoo.com)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#yahoo.com)' at line 2
No idea why it wont put it into the database. The form code is
<section>
<div class="mockup-content">
<div class="morph-button morph-button-inflow morph-button-inflow-1">
<button type="button"><span>Subscribe to our Newsletter</span></button>
<div class="morph-content">
<div>
<div class="content-style-form content-style-form-4">
<h2 class="morph-clone">Subscribe to our Newsletter</h2>
<form action="scripts/mailer.php" method="post">
<p><input type="text" class="button" id="email" name="email" placeholder="NAME#EXAMPLE.COM">
<div>We promise, we won't send you any spam. Just love.</div>
<input type="submit" class="button" id="submit" value="SIGN UP"></p>
</form>
</div>
</div>
</div>
</div><!-- morph-button -->
</div>
</section>
This is just the html data for the form, the php data is
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mysql";
$email = ($_POST["email"]);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO emails (email)
VALUES ($email)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Can anyone explaine why this is?
You should use a tick (') when binding variables in a query:
$sql = "INSERT INTO emails (email) VALUES ('$email')";
It is okay not to use tick when the value of your variable you are trying to bind is an int.
The email is in varchar datatype . you need to put quotes on it
$sql = "INSERT INTO emails (email) VALUES ('".$email."')";