Send information (from a form) to a database and email - php

I have a form that allows a user to opt in to receive a notification if a new product comes out. Currently, a users' information is validated and sent to a database. However, I also need it to be sent to an email address.
Both of the scripts work separately; getting them to work together is proving difficult, though.
<?php
//CHECK CAPTCHA IMAGE
session_start();
if( isset($_POST['submit'])) {
if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'])) {
// IF CAPTCHA CHECKS OUT, CONTINUE TO VALIDATE DATA.
if( !isset($_POST['fname']) ||
!isset($_POST['lname']) ||
!isset($_POST['email']))
{
echo '<script type="text/javascript">';
echo 'alert("Please go back and fill out the entire form.");';
echo '</script>';
}
// CONNECT TO DATABASE
$dbhost = 'DATABASE NAME';
$dbuser = 'DATABASE USER';
$dbpass = 'PASSWORD';
$dbname = 'DATABASE NAME';
$dbtable = 'TABLE NAME';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn)
{
die('Could not connect: ' . mysql_error() . '<br />');
} else {
//echo 'Connected successfully. <br />';
}
$selected = mysql_select_db($dbname,$conn);
if(! $selected)
{
die('Could not connect: ' . mysql_error() . '<br />');
} else {
//echo 'Connected successfully. <br />';
}
$fname = mysql_real_escape_string(stripslashes($_POST['fname']));
$lname = mysql_real_escape_string(stripslashes($_POST['lname']));
$email = mysql_real_escape_string(stripslashes($_POST['email']));
$today = date("Y-m-d H-i-s");
if (mysql_query("INSERT INTO $dbtable(fname, lname, email, date) VALUES('$fname', '$lname', '$email', '$today')") != true)
{
echo ("ERROR: " . mysql_error() . "<br />");
} else {
//echo 'Thank you, your information has been entered into our database. <br />';
}
mysql_close($conn); // CLOSE DATABASE
include('../thankyou.html');
unset($_SESSION['security_code']); //END SESSION
} else // IF CAPTCHA DOESN'T CHECK OUT, DISPLAY ERROR MESSAGE.
{
echo '<script type="text/javascript">';
echo 'alert("Sorry, you have provided an invalid security code.")';
echo '</script>';
}
}
?>
I've tried including a form-to-email script as an "include" and I've tried integrating the two scripts into one, but neither has worked so far.
Any thoughts would be greatly appreciated.. Thank you!

For the email portion, simply use the mail function or, better yet, use one of the well-tested mailer libraries such as PHPMailer and Swift Mailer.

Try using the PHP mail function after you close the mysql connection. For example...
$my_email = Whatever address you'd like this sent to.
$subject = Subject line of email.
$message = The content of the email, this can contain your variables and html formatting if you wish. Something like:
$message = " $time (Central Time) \n
From: $visitor ($visitormail)\n
Message: $notes
";
$headers = The header info, something like:
$headers = "From: $visitormail \r\n" .
"Reply-To: $visitormail \r\n" .
'X-Mailer: PHP/' . phpversion();
...and send the email with...
mail("$my_email", $subject, $message, $headers);
and then you can redirect to another page with:
header( "Location: http://example.com/thankyou.html");

<?php
$dbhost = '';
$dbuser = '';
$dbpass = '';
$dbname = '';
$dbtable = 'webagents';
//$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
//$conn = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if(!$conn)
{
die('Could not connect: ' . mysqli_error() . '<br />');
} else {
//echo 'Connected successfully. <br />';
}
$selected = mysqli_select_db($conn,$dbname);
if(! $selected)
{
die('Could not connect: ' . mysqli_error() . '<br />');
} else {
//echo 'Connected successfully. <br />';
}
$cname = mysqli_real_escape_string($conn, $_POST['compname']);
$cperson = mysqli_real_escape_string($conn, $_POST['contperson']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$phone = mysqli_real_escape_string($conn, $_POST['phone']);
$country = mysqli_real_escape_string($conn, $_POST['country']);
if (mysqli_query($conn,"INSERT INTO $dbtable(compname, contperson, email, phone, country) VALUES('".$cname."','".$cperson."', '".$email."', '".$phone."', '".$country."')") != true)
{
echo ("ERROR: " . mysqli_error($conn) . "<br />");
//die (mysqli_error($myConnection));
} else {
echo 'Thank you, your information has been entered into our database. <br />';
}
mysqli_close($conn); // CLOSE DATABASE
?>

Related

Form Not Redirecting After Submit Header Location in PHP Not Working

My PHP header redirection isn't working and I can't seem to figure out why. I've read through a lot of questions and nothing I've tried seems to work.
<?php
define('DBHOST','shareddb1d.hosting.stackcp.net');
define('DBUSER','JoplinLeftHand-3231135a');
define('DBPASS','Banoodle1!');
define('DBNAME','JoplinLeftHand-3231135a');
$link = mysql_connect(DBHOST, DBUSER, DBPASS);
if (!link) {
die('Could Not Connect: ' . mysql_error());
} else {
echo "You Are Connected<br>";
}
$db_selected = mysql_select_db(DBNAME, $link);
if (!$db_selected) {
die('Can\'t Use ' . DBNAME . ': ' . mysql_error());
} else {
echo "Database Selected";
}
$tid = $_POST['tid'];
$first = $_POST['first'];
$last = $_POST['last'];
$zip = $_POST['zip'];
$descrip = $_POST['descrip'];
$sql = "INSERT INTO tracking (tracking_id, tracking_first, tracking_last, tracking_zip, tracking_descrip) VALUES ('$tid', '$first', '$last', '$zip', '$descrip')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
} else {
header("Location:/?p5");
}
header('Location: ...'); has to be the first output of the script, otherwise it will not work. You are using echo twice before performing the redirect, here:
echo "You Are Connected<br>";
and here:
echo "Database Selected";
Also, SOME clients require the URL passed in the Location header to be absolute URLs, and not relative, for example:
header("Location: http://example.com/?p5");

i have created this table from database.Now if anyone updates the value in table how can it be reflected back in database?

I am making a simple page to test a database connection. When I tried accessing it from my browser, it says:
Server error
The website encountered an error while retrieving http://localhost:8888/blah/blah/test.php. It may be down for maintenance or configured incorrectly.
Here are some suggestions:
Reload this webpage later. HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.
All I am doing is connecting to a database and displaying the tables. Here is what I have so far as the PHP code:
<?php
// Get Variables
$dbname = $_GET["dbname"];
$dbusername = $_GET["dbusername"];
$dbpass = $_GET["dbpass"];
$dbhost = $_GET["dbhost"];
$connection = mysql_connect("$dbhost","$dbusername","$dbpass");
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
else
{
echo "Connected";
$dbcheck = mysql_select_db("$dbname");
if (!$dbcheck) {
echo mysql_error();
}else{
echo "<p>Successfully connected to the database '" . $database . "'</p>\n";
// Check tables
$sql = "SHOW TABLES FROM `$database`";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0) {
echo "<p>Available tables:</p>\n";
echo "<pre>\n";
while ($row = mysql_fetch_row($result)) {
echo "{$row[0]}\n";
}
echo "</pre>\n";
} else {
echo "<p>The database '" . $database . "' contains no tables.</p>\n";
echo mysql_error();
}
}
// some code
mysql_close($con);
?>
My error in the WAMP Apache logs is:
[03-Feb-2013 22:47:37 UTC] PHP Parse error: syntax error, unexpected end of file in /Applications/MAMP/htdocs/coursemanager/default/verify1.php on line 52
What would a unexpected end of file be?
It means you forgot to close the last }
<?php
// Get Variables
$dbname = $_GET["dbname"];
$dbusername = $_GET["dbusername"];
$dbpass = $_GET["dbpass"];
$dbhost = $_GET["dbhost"];
$connection = mysql_connect("$dbhost","$dbusername","$dbpass");
if (!$connection) {
die('Could not connect: ' . mysql_error());
} else {
echo "Connected";
$dbcheck = mysql_select_db("$dbname");
if (!$dbcheck) {
echo mysql_error();
} else {
echo "<p>Successfully connected to the database '" . $database . "'</p>\n";
// Check tables
$sql = "SHOW TABLES FROM `$database`";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0) {
echo "<p>Available tables:</p>\n";
echo "<pre>\n";
while ($row = mysql_fetch_row($result)) {
echo "{$row[0]}\n";
}
echo "</pre>\n";
} else {
echo "<p>The database '" . $database . "' contains no tables.</p>\n";
echo mysql_error();
}
}
// some code
mysql_close($con);
}

Insert multiple results into database PHP

This part is for gathering my data through an API.
foreach($result['List'] as $feedback)
{
$date = date_create();
$date_entered = $feedback['DateEntered'];
$time = preg_replace('/[^0-9]/','',$date_entered);
//$comment = $feedback['Text'];
$ListingId = $feedback['ListingId'];
$BuyNowPrice = $feedback['BuyNowPrice'];
$max_bid = $feedback['MaximumBidAmount'];
$SellerId = $feedback['SellerId'];
echo '<div>' . "Seller ID: $SellerId" . " has sold one $ListingId for " . '$' . "$BuyNowPrice" . '</div>';
echo "<div>Feedback created at " . $time . "</div>";
echo '<br>';
}
This part is the code that I used to insert into my results directly after retrieving them.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO tmfeedback '.
'(SellerId,ListingId,BuyNowPrice) '.
'VALUES ('.$SellerId.', '.$ListingId.', '.$BuyNowPrice.'))';
mysql_select_db('dctdb3');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
Only one data is being inserted into the database and it is the last data displayed.
I was wondering how I can change my code so that I can insert all the data at the same time and not repetitive?
Thank you for your help.
Put the insertion inside the loop. Otherwise, the variables just have the last values that were set in the last iteration of the loop.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('dctdb3');
foreach($result['List'] as $feedback) {
$date = date_create();
$date_entered = $feedback['DateEntered'];
$time = preg_replace('/[^0-9]/','',$date_entered);
//$comment = $feedback['Text'];
$ListingId = $feedback['ListingId'];
$BuyNowPrice = $feedback['BuyNowPrice'];
$max_bid = $feedback['MaximumBidAmount'];
$SellerId = $feedback['SellerId'];
echo '<div>' . "Seller ID: $SellerId" . " has sold one $ListingId for " . '$' . "$BuyNowPrice" . '</div>';
echo "<div>Feedback created at " . $time . "</div>";
echo '<br>';
$sql = 'INSERT INTO tmfeedback '.
'(SellerId,ListingId,BuyNowPrice) '.
'VALUES ('.$SellerId.', '.$ListingId.', '.$BuyNowPrice.'))';
$retval = mysql_query($sql);
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
}
echo "Entered data successfully<br>";
mysql_close($conn);
Make sure your second block of code is inside your first block of code (place your second block above the right-curly-brace). Then it will occur for each iteration of the foreach loop (each result) and insert a record for each one.
You cannot insert array into database hence place the query inside a loop. This thread may help you alot.

Sending password to mobile

I am using the below code to send password to mobile and the code doesn't seems to work.
Really appreciate any help on this.
if (isset($_REQUEST['submit'])) {
$phone = "select mobno from registration where username='" . $_GET['id'] . "' ";
$mailto = "select regemail from registration where username='" . $_GET['id'] . "' ";
$subject = "passcode";
mail($mailto, $subject, $);
echo '<script type="text/javascript">alert("Code Sent Successfully");</script>';
echo '<meta http-equiv="refresh" content=",log.php">';
}
Try editing your code like this:
if (isset($_REQUEST['submit'])) {
$phone = mysql_query("SELECT mobno FROM registration WHERE username='" . $_GET['id'] . "' ; ");
$mailto = mysql_query("SELECT regemail FROM registration WHERE username='" . $_GET['id'] . "' ; ");
$subject = "passcode";
mail($mailto, $subject, $phone);
echo '<script type="text/javascript">alert("Code Sent Successfully");</script>';
echo '<meta http-equiv="refresh" content="0,log.php">';
}
Don't forget to connect to your mySQL-Database at the beginning!
Hope this helps.
/* DB connection */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
if (isset($_REQUEST['submit'])) {
$sql = 'SELECT mobno,regemail FROM registration WHERE username=:user'; // I suspect this should be id=:user due to $_GET['id'] and not $_GET['username']
$sth = $dbh->prepare($sql);
$sth->execute(array(':user' => $_GET['id']));
$data = $sth->fetch(PDO::FETCH_ASSOC);
$phone = $data['mobno'];
$mailto = $data['regemail'];
$subject = "passcode";
mail($mailto, $subject, $phone);
echo '<script type="text/javascript">alert("Code Sent Successfully");</script>';
echo '<meta http-equiv="refresh" content=",log.php">';
}
You may find the php manual on PDO helpful http://www.php.net/manual/en/class.pdo.php

PHP Delete comments button

I am very new to PHP (currently doing a university project). My website is an admin site, with about 3 admin users who can log in and change the site etc. Currently, I have a delete function on my comments (comments which users can post to the site) but anybody who comes onto the site can see the delete function and can delete anybodies comments?
I want it so that only my admin's when logged in, can see the delete function, and subsequently be the only ones who can delete the comments. I have a users database with name, password, username and email columns. I was wondering if somebody could please take a look at my code and tell me how I can change this so that only when admins log in they can see the button and delete the comments.
$str_message = "";
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
}else{
//if ($_SESSION['admin'] == 'yes') {
if(isset($_GET['delete'])){
$deleteq="DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";
$deleter=mysqli_query($db_server, $deleteq);
IF($deleter){
echo"<p>That message was deleted!</p>";}}
//}
//Test whether form has been submitted
if(trim($_POST['submit']) == "Submit"){
//Handle submission
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it
again.
(reCAPTCHA said: " . $resp->error . ")";
} else {
// Your code here to handle a successful verification
$comment = $_POST['comment'];
if($comment != ""){
$query = "INSERT INTO comments (comment) VALUES ('$comment')";
mysqli_query($db_server, $query) or die("Comment insert failed: " .
mysqli_error($db_server) );
$str_message = "Thanks for your comment!";
}else{
$str_message = "Invalid form submission";
}
}
}
//Create page with or without submission
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) );
{
while($row = mysqli_fetch_array($result)){
$ID= $row['ID'];
$str_result .= "<p><em>Comment $j (" . $row['commDate'] .
")</em><br /> " .$row['comment'] . "</p>
<a href ='commentnow.php?delete=$ID
'>Delete</a><hr />";
}
mysqli_free_result($result);
} }
?>
If we assume that your commented out statement to check if the user is an admin (if ($_SESSION['admin'] == 'yes')) works, then the following code should give you a good idea of how to do it. There are two places where you need to add the if statement. I haven't been able to test this but look in this code for where you see // ADMIN IF STATEMENT and I hope you understand what changes to your code need to be made for it to work properly.
<?
$str_message = "";
if (!$db_server) {
die("Unable to connect to MySQL: " . mysqli_connect_error());
} else {
if ($_SESSION['admin'] == 'yes') { // ADMIN IF STATEMENT
if (isset($_GET['delete'])) {
$deleteq = "DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";
$deleter = mysqli_query($db_server, $deleteq);
if ($deleter) {
echo "<p>That message was deleted!</p>";
}
}
}
//Test whether form has been submitted
if (trim($_POST['submit']) == "Submit") {
//Handle submission
$resp = recaptcha_check_answer(
$privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]
);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it again. (reCAPTCHA said: " . $resp->error . ")";
} else {
// Your code here to handle a successful verification
$comment = $_POST['comment'];
if ($comment != "") {
$query = "INSERT INTO comments (comment) VALUES ('$comment')";
mysqli_query($db_server, $query) or die("Comment insert failed: " . mysqli_error($db_server) );
$str_message = "Thanks for your comment!";
} else {
$str_message = "Invalid form submission";
}
}
}
//Create page with or without submission
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) ); {
while ($row = mysqli_fetch_array($result)) {
$ID = $row['ID'];
if ($_SESSION['admin'] == 'yes') { // ADMIN IF STATEMENT
$str_result .= "<p><em>Comment $j (" . $row['commDate'] . ")</em><br /> " .$row['comment'] . "</p><a href ='commentnow.php?delete=$ID'>Delete</a><hr />";
} else {
$str_result .= "<p><em>Comment $j (" . $row['commDate'] . ")</em><br /> " .$row['comment'] . "</p>";
}
}
mysqli_free_result($result);
}
}
?>
if ($_SESSION['admin'] == 'yes') {
<insert code to generate a delete button here>
}
First you need to change in your log in page. When an user login then check if he is an admin user. if yes the set a session variable ($_SESSION['admin']) to yes or set it to no. try like this:
//login.php
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
}else{
session_start();
$sql="Select * FROM users WHERE user_name = 'your_username' and LIMIT 1";
$result=mysqli_query($db_server, $sql);
$objUser = $result->fetch_object();
if($objUser->user_type =="admin")
$_SESSION['admin'] = 'yes';
else
$_SESSION['admin'] = 'no';
//rest of your code for login the user
}
Then in your delete page check if current user is admin or not. If yes then execute query else echo a message. like this:
session_start();
$str_message = "";
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
}else{
if(isset($_GET['delete'])){
if ($_SESSION['admin'] == 'yes') {
$deleteq="DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";
$deleter=mysqli_query($db_server, $deleteq);
if($deleter){
echo"<p>That message was deleted!</p>";}
}
else
{
echo "you are not admin";
}
}
//Test whether form has been submitted
if(trim($_POST['submit']) == "Submit"){
//Handle submission
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it
again.
(reCAPTCHA said: " . $resp->error . ")";
} else {
// Your code here to handle a successful verification
$comment = $_POST['comment'];
if($comment != ""){
$query = "INSERT INTO comments (comment) VALUES ('$comment')";
mysqli_query($db_server, $query) or die("Comment insert failed: " .
mysqli_error($db_server) );
$str_message = "Thanks for your comment!";
}else{
$str_message = "Invalid form submission";
}
}
}
//Create page with or without submission
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) );
{
while($row = mysqli_fetch_array($result)){
$ID= $row['ID'];
$str_result .= "<p><em>Comment $j (" . $row['commDate'] .
")</em><br /> " .$row['comment'] . "</p>
<a href ='commentnow.php?delete=$ID
'>Delete</a><hr />";
}
mysqli_free_result($result);
} }
?>
I think it makes sense !

Categories