I have a html document with a form page that is debugged and is correct. The problem is the DB, Im hosted on strato, but I think its more of a code problem rather than a serverside problem. The html document is a form that feeds in the Super globals POST, so First, Lastname, Email, Subject, Address, PLZ and message. However the message is not going into the db, its gonna get mailed to my support email. I havent setupp the mail function because I wanted to debug the sql db part first. All the if statements filter the input, for valid email and patterns, so you are not allowed to put in numbers in the form of the html form. I know you can make the pattern in html but I want 100% safety. After the inputs have passed all the filters the connection to my db is going to connect, I want to insert first, lastname and email address and subject as well as plz.
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$subject = $_POST['thema'];
$address = $_POST['address'];
$plz = $_POST['plz'];
$text = $_POST['text'];
$pattern = "/^([a-zA-Z' äöü ÄÖÜ]+)$/";
$pattern_plz = "/[0-9]$/";
//VALID INPUT//
if(preg_match($pattern, $fname)){
if(preg_match($pattern, $lname)){
if($email == TRUE){
if(preg_match($pattern_plz, $plz)){
if(is_numeric($plz)){
$con = new mysqli($host, $db, $user, $passwd) or die ("Keine Verbindung konnte aufgebaut werden");
if($con){
$sql="INSERT INTO contact (fname, lname, email, thema, address, plz)
VALUES ($fname, $lname, $email, $subject, $address, $plz)";
if($con->mysqli_query($sql) == TRUE){
echo "success";
}else{mysqli_close($con); exit("Keine Verbindung konnte aufgebaut werden");}
}else{mysqli_close($con); exit("Keine Verbindung konnte aufgebaut werden");}
}else{exit("Inavlid PLZ");}
}else{exit("Inavlid PLZ");}
}else{exit("Inavlid email");}
}else{exit("Inavlid email");}
}else{exit("Inavlid lastname");}
as you are using it on live hosting, displaying error might be turned off from your directadmin or cpanel, you can find php options in hosting and turn on, or else you can use try catch for example
//trigger exception in a "try" block
try {
//Your code
}
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage(); // display error
}
Related
Verification mail in getting sent but values are not going in the database, I have created a user lavvish and it has all the priviledges. Here's my code -
$dbc=mysqli_connect('localhost','lavvish','lavvish','lavvish_users');
$q="INSERT INTO temp_users(first,last,email,otp,countrycode,mobile,password)VALUES ('$first','$last','$email','$otp','$cc','$mobile','$EncPwd')";
mysqli_query($dbc,$q);
$_SESSION['email']=$_POST['email'];
header('Location:index.php?login=newuser');
//send verification mail
$to = $email; // Send email to our user
$subject = 'Verification link'; // Give the email a subject
$message='Your account has been created, activate your account by entering the following otp:'.$otp.'';
$headers = 'From:goLavvish#golavvish.com' . "\r\n"; // Set from headers
mail($to, $subject, $message, $headers); // Send our email
//Email sent
I would recommend you to use PDO. An email will only be sent if the INSERT command is successful, else it will return an error with the error message. To learn about PDO please visit this page http://www.w3schools.com/php/php_mysql_insert_multiple.asp.
Hope it will be helpful.
<?php
$servername = "localhost";
$username = "lavvish";
$password = "lavvish";
$dbname = "lavvish_users";
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 temp_users (first, last, email, otp, countrycode, mobile, password)
VALUES ($first, $last, $email, $otp, $cc, $mobile, $EncPwd)";
// use exec() because no results are returned
$conn->exec($sql);
// Save sessions when INSERT is successful
$_SESSION['email']=$_POST['email'];
header('Location:index.php?login=newuser');
$to = $email; // Send email to our user
$subject = 'Verification link';
// Give the email a subject
$message='Your account has been created, activate your account by entering the following otp:'.$otp.'';
$headers = 'From:goLavvish#golavvish.com' . "\r\n";
// Set from headers
mail($to, $subject, $message, $headers);
// Send our email
//Email sent
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Try to debug your query.
For example:
if (mysqli_query($link, "your query") === TRUE) {
printf("Table myCity successfully created.\n");
}
Apart for an apparent lack of security, which you ought to think about.[1] I think your issue lies in your SQL statement.
I'd change the line below from:
$q="INSERT INTO temp_users(first,last,email,otp,countrycode,mobile,password)VALUES ('$first','$last','$email','$otp','$cc','$mobile','$EncPwd')";
so that it now reads:
$q="INSERT INTO temp_users (first, last, email, otp, countrycode, mobile, password) VALUES ('$first', '$last', '$email', '$otp', '$cc', '$mobile', '$EncPwd')";
As you can see, I've added spaces between the elements. This works for me. If that hasn't helped, try MySQL Checker, it's a good resource to check your MySQL syntax.
EDIT: If that hasn't worked, I'd check your user priveleges. Make sure that the user has database-specific rights to that database (or table-specific rights if you're going to lock down your db)
EDIT2: See kikuyu1's comments in the previous answer:
#ShubhamKhetan, can you try renaming to this $sql = "INSERT INTO temp_users (first_n, last_n, email_n, otp_n, countrycode_n, mobile_n, password_n) VALUES ($first, $last, $email, $otp, $cc, $mobile, $EncPwd)"; – kikuyu1 11 mins ago
Please check this page to check the researved words in MYSQL dev.mysql.com/doc/refman/5.7/en/keywords.html. Do not use reserved words in your sql – kikuyu1 6 mins ago
[1]: At least do some sanitization on the inputs, otherwise some unscrupulous hacker will try SQL Injection.
Hi I am working on a simple php registration. But everytime I am submitting the registration page, i am getting a blank screen, no error, no display.
The code in my php file is :
<?php
if($_SERVER['REQUEST_METHOD']=="POST"){
$IP = //my hostname
$dbuser = "my user id";
$conn = new mysqli_connect($IP, $dbuser, "","my databse name");
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
$address = $_POST['address'];
$query = "SELECT email FROM user where email='".$email."'";
$result = mysqli_query($conn,$query);
$numResults = mysqli_num_rows($result);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // Validate email address
{
$message = "Invalid email address please type a valid email!!";
}
elseif($numResults>=1)
{
$message = $email." Email already exist!!";
}
else
{
mysqli_query("(insert into user(name,phone_number, email,pass1, pass2, address) values
('".$name."','".$phone."', '".$email."', '".$pass1."','".$pass2."','".$address."')");
echo $message = "Signup Sucessfully!!";
}
mysqli_close($conn);
}
print_r(error_get_last());
?>
there is no issue in establishing connection as i am using this connection method in other pages and they are working fine. Also i should specify that currently i am working on cloud 9 and my mysql database is on cloud9 itself.
please help me in undersstanding the trouble.
You say your line 42 has the insert query. I suppose you mean this query:
mysqli_query("(insert into user(name,phone_number, email,pass1, pass2, address) values
('".$name."','".$phone."', '".$email."', '".$pass1."','".$pass2."','".$address."')");
As your error says "2 parameters expected", you are missing here your connection parameter. You should have this:
mysqli_query($conn, "(insert into user(name,phone_number, email,pass1, pass2, address) values
('".$name."','".$phone."', '".$email."', '".$pass1."','".$pass2."','".$address."')");
Put this in on the first line of your script
ini_set('display_errors', '1');
This will then display the errors on the page and you will be able to see what is going wrong.
Also rather than the IP address try "localhost"
$conn = new mysqli_connect("localhost", $dbuser, "","my databse name");
If the database is on the same machine this may solve your problem.
Also your code is incredibly unsafe and will suffer from SQL injection. Please consider the following lines:
$email = $_POST['email'];
$query = "SELECT email FROM user where email='".$email."'";
Basically you put whatever the user is passing into your SQL statement. What if he enters "' OR 1; DROP TABLE user". You would lose all your data.
Please read about SQL injection and use PDO:
http://en.wikipedia.org/wiki/SQL_injection
http://php.net/manual/fr/book.pdo.php
I am a bit confused about how to use foreach. I read some internet things on it and I kind of understand how it works, but I don't fully understand it. I think I could use foreach to create a PHP mass emailer that sends blank carbon copy to email addresses and adresses the customer by name in the subject (Dear, Michael Here is your email). I've figured out how to retrieve the names and emails from my database into variables and I know how to email, but I don't know how to send multiple emails at once and to associate the name and email address.
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "MichaelBerna.db.10339998.hostedresource.com";
$username = "MichaelBerna";
$dbname = "MichaelBerna";
//These variable values need to be changed by you before deploying
$password = "********";
$usertable = "subscribers";
$yourfield = "name";
$yourfield1 = "email";
//Connecting to your database
$link = mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database! Please try again later.");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result)
{
while($row = mysql_fetch_array($result))
{
$name = $row["$yourfield"];
$email = $row["$yourfield1"];
echo "Name: $name<br>";
echo "Email: $email<br>";
//mysqli_free_result($result);
//mysqli_close($link);
}
}
?>
Here is my email code:
<?php
require_once '../PHPMailer_5.2.2/class.phpmailer.php';
$name = $_POST['name'] ;
$email = $_POST['email'] ;
//$file = $_POST['file'] ; // I'm going to later add a file later to be attached in email from database
$body = "Hey $name thank you for continuing to be a valued customer! This month's story is included in this email asa an attachment.";
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
try
{
$mail->AddAddress($email, $name);
$mail->SetFrom('admins_email#yahoo.com', 'Site Admin');
$mail->AddReplyTo('admins_email#yahoo.com', 'Site Admin');
$mail->Subject = "Dear $name Your monthly subscription has arrived!";
$mail->Body = $body;
if ($_FILES['file']['size'])
{
$mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);// attachment
}
$mail->Send();
echo "Email Sent Successfully</p>\n";
}
catch (phpmailerException $e)
{
echo $e->errorMessage(); //Pretty error messages from PHPMailer
}
catch (Exception $e)
{
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
Basically, I need a way to combine these two scripts and link them together and that's what I'm unsure of how to do.
Put the mailing code in a function, e.g. send_mail(), so that it can be called from different places. Then change your database query loop to:
while ($row = mysql_fetch_assoc($result)) {
send_mail($row['name'], $row['email'), "Text of the email");
}
Edit: I solved the problem! It was an issue unrelated to the code that I posted - I had an exit command in the script - but all of your advice still helped in other ways.
I'm trying to automatically send an e-mail to a user when they fill out their picks on a sports website. The early part of the script works: Their picks are correctly inserted or updated in the database. The script breaks when I try to pull the user's e-mail address from a table in the MySQL database and use it to send them a message. But what is very strange about this bug is that it doesn't result in any error messages, and for some reason prevents certain echo statements from running while allowing others.
Here's the relevant code:
...
//set variable for the userID, grabbed from the session array
$userID = $_SESSION['identifier'];
...
//write query to get user's e-mail from the database
$getEmail = "SELECT `email` FROM `useraccounts` WHERE `userID` = '".$userID."'";
//execute query
$result = $db->query($getEmail);
//check if query failed
try
{
if (!$result)
{
throw new customexception("Some kind of database problem occurred when trying to find your e-mail address.");
}
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
//get the info from the row
$row = $result->fetch_assoc();
//check if function ran, catch exception if it failed
try
{
if ($row === false)
{
throw new customexception("Some kind of database problem occurred when trying to get your e-mail address from your user record in the database.");
}
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
//set e-mail variable
$email = $row['email'];
//set up e-mail information to send a record of their picks to the user
$toAddress = "$email";
$subject = "Your Picks";
$fromAddress = "From: picks#mysite.com";
//take the info the user submitted, format it for the e-mail, and assign to variable $mailContent
//the $winner1, $spread1, etc. variables are defined earlier in the function, and were successfully submitted into the database
$mailContent = "You picked $winner1 to win by $spread1 points, $winner2 to win by $spread2 points, $winner3 to win by $spread3 points, $winner4 to win by $spread4 points, and $winner5 to win by $spread5 points. \n".
"You can change your picks at any time before 1:00pm EST, February 27, 2011. Just go back to the form on the game page and enter your new picks. Good luck!";
//use wordwrap to limit lines of $mailContent to 70 characters
$mailContent = wordwrap($mailContent, 70);
//send the e-mail
$isMailed = mail($toAddress, $subject, $mailContent, $fromAddress);
//debug: check if mail failed
if (!$isMailed)
{
echo "Mail failed.";
}
//debug: echo $email to see if there's anything in there
echo "<p>E-mail: $email</p>";
//debug: echo $toAddress to see if there's anything in there
echo "<p>To address: $toAddress</p>";
//if everything succeeded, write reply and close database
echo $reply;
$db->close();
?>
Just to be clear, $userID is set correctly, because their picks enter the database like they're supposed to. None of the exceptions listed in the code come up, meaning the query seems to have run successfully. I checked the query again by copying it from the PHP code and running it directly on the MySQL database. When it ran directly, it found the correct e-mail address for every userID value I entered.
But the mail never gets delivered, and when I try to echo the $email and $toAddress variables to see if they're empty:
//debug: echo $email to see if there's anything in there
echo "<p>E-mail: $email</p>";
//debug: echo $toAddress to see if there's anything in there
echo "<p>To address: $toAddress</p>";
...nothing shows up. Not even an error message. And that doesn't necessarily mean that the variables are empty: Not even the labels are echoed.
I also tried the code with my personal e-mail hardcoded instead of $toAddress, and no mail was sent. So the mail function isn't working.
I should also note that the script still successfully echoes $reply (which is a string defined much earlier) at the end.
What's really strange is that the login script for my website uses an almost identical piece of code and works perfectly:
$getuserID = "SELECT `userID` FROM `useraccounts` WHERE `u_name` = '".$login."' AND `p_word` = SHA1('".$password."')";
$result = $db->query($getuserID);
//check if query ran, catch exception if it failed
try
{
if ($result === false)
{
throw new customexception("Some kind of database problem occurred when trying to find your user ID.");
}
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
//get the info from the row
$row = $result->fetch_assoc();
//check if function ran, catch exception if it failed
try
{
if ($row === false)
{
throw new customexception("Some kind of database problem occurred when trying to get info from your user record in the database.");
}
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
//set userID variable
$userID = $row['userID'];
//assign the session identifier and include successfullogin.html if all is well
$_SESSION['identifier'] = $userID;
And I used to have the signup script send me an e-mail every time I got a new user, so I know that mail() works in general with my hosting provider:
//set up static e-mail information
$toAddress = "myemail#mysite.com";
$subject = "Advance Sign-Up";
$mailContent = "Name: $firstName $lastName \n".
"Username: $username \n".
"Password: $password \n".
"E-mail: $email \n".
"Country: $country \n".
"State: $state \n".
"City: $city \n".
"ZIP: $zip \n";
$fromAddress = "From: $email";
...
mail($toAddress, $subject, $mailContent, $fromAddress);
This bug is completely mystifying to me. I wish I had some sort of error message to work with, at least. Can anyone see what's wrong?
It should be a comment but for the sake of formatting.
Your way of error handling is quite unusual.
If you really want to use exceptions, it should be done different way: one try block and multiple throws:
try
{
$getEmail = "SELECT `email` FROM `useraccounts` WHERE `userID` = '".$userID."'";
$result = $db->query($getEmail);
if (!$result)
{
throw new customexception("Some kind of database problem occurred when trying to find your e-mail address.");
}
$row = $result->fetch_assoc();
if ($row === false)
{
throw new customexception("Some kind of database problem occurred when trying to get your e-mail address from your user record in the database.");
}
$email = $row['email'];
$toAddress = "$email";
$subject = "Your Picks";
$fromAddress = "From: picks#mysite.com";
$mailContent = "yadda yadda yadda";
$mailContent = wordwrap($mailContent, 70);
mail($toAddress, $subject, $mailContent, $fromAddress);
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
?>
Are you positive the database variables have contents? I use echo (or print) to quickly make sure the variables aren't empty. Are you positive your email code works? Try it with set values (such as your own personal e-mail) to make sure it works.
The best way out to ignore such notices is to ensure that the variables exist or in plain PHP, use isset(),if !isset() throw an exception/error and handle it properly.
i have a PHP contact form that submits data, and an email...:
<?php
$dbh=mysql_connect ("localhost", "username", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("guest");
if (isset($_POST['submit'])) {
if (!$_POST['name'] | !$_POST['email'])
{
echo"<div class='error'>Error<br />Please provide your Name and Email Address so we may properly contact you.</div>";
}
else
{
$age = $_POST['age'];
$name = $_POST['name'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
$query = "INSERT INTO contact_us (age,name,gender,email,phone,comments)
VALUES ('$age','$name','$gender','$email','$phone','$comments')";
mysql_query($query);
mysql_close();
$yoursite = "Mysite ";
$youremail = $email;
$subject = "Website Guest Contact Us Form";
$message = "$name would like you to contact them
Contact PH: $phone
Email: $email
Age: $age
Gender: $gender
Comments: $comments";
$email2 = "my#email.com";
mail($email2, $subject, $message, "From: $email");
echo"<div class='thankyou'>Thank you for contacting us,<br /> we will respond as soon as we can.</div>";
}
}
?>
The email is coming through fine, but the data is not storing the dbase... am i missing something?
Its the same script as i use on another contact us page, only difference is instead of parsing the data on teh same page, i now send this data to a "thankyou.php" page... i tried changing $_POST to $_GET but that killed the page... what am i doing wrong?
First of all, you must escape your data before injecting them in your SQL query.
This can be done using the mysql_real_escape_string function, like this :
$name = mysql_real_escape_string($_POST['name']);
// ... same for other fields that contain strings
$comments = mysql_real_escape_string($_POST['comments']);
This will ensure that quotes in your data are escaped, and don't mess with the ones that are arround the fields' data in the SQL query, first.
And, second, this will help you prevent SQL Injections.
Also, in case of an error during the execution of a query, mysql_query will return false -- which means you should test the value returned by that function -- to possibly log the cause of the error :
$result = mysql_query($query);
if ($result === false) {
// An error has occured...
echo mysql_error();
}
Note : here, I just displayed the error message -- but you should instead log the error somewhere (to a file, for instance), before putting your application to production : your users don't need (nor want) to see any technical error message !
Check the result from mysql_query(...) to see if it failed or not. If it didn't fail, MySQL should definitely have stored the information for you.