mySQL not saving data? - php

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.

Related

My php Code doesnt work I cant find the problem

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
}

PHP to SQL and email form submission

I have a working PHP form that is taking data from a form in the backend of the website and inserting it into the SQL database applicable. My issue is, whenever I try and set it up so that it also send the data to an email address ( email captured in form & email defined ) I recieve Error 500.
Code is below:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("#", "#", "#", "#");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$name = mysqli_real_escape_string($link, $_POST['name']);
$initials = mysqli_real_escape_string($link, $_POST['initials']);
$item = mysqli_real_escape_string($link, $_POST['item']);
$issue = mysqli_real_escape_string($link, $_POST['issue']);
$tel = mysqli_real_escape_string($link, $_POST['tel']);
$email = mysqli_real_escape_string($link, $_POST['email']);
$cost = mysqli_real_escape_string($link, $_POST['cost']);
$loggedby = mysqli_real_escape_string($link, $_POST['loggedby']);
$bag = mysqli_real_escape_string($link, $_POST['bag']);
$charger = mysqli_real_escape_string($link, $_POST['charger']);
// attempt insert query execution
$sql = "INSERT INTO `repairs` (`name`,`initials`,`item`, `issue`, `telephone`,`email`, `cost`, `loggedby`, `bag`, `charger`) VALUES ('$name', '$initials', '$item', '$issue', '$tel', '$email', '$cost', '$loggedby', '$bag', '$charger')";
if(mysqli_query($link, $sql)){
header('location:repairs.php');
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
$to = "emailaddress#emails.co.uk,$email"
$subject= "Thankyou $name - Your repair has been logged"
$body= "<h2>Thankyou $name</h2> /n
This is a confirmation email regarding your $item /n
Your repair log is below: /n
$item /n
$issue /n/n
<h3>Accessories</h3> /n
bag - $bag /n
charger - $charger /n/n
Your repair was logged by $loggedby on echo date("d-m-Y"); /n/n
We will contact you on $tel & $email when your $item is ready to
collect.
/n/n
Loud Crowd IT - 01302 965482 /n
repairs#loudcrowdit.co.uk /n
www.loudcrowd.agency /n"
$mail ($to,$subject,$body);
// close connection
mysqli_close($link);
?>
Does anyone know why I receive the error?
Internal server error means there's an error in your server side script, in this case :
$to = "emailaddress#emails.co.uk,$email" // missing a semicolon
The missing semicolon above triggers Unexpected '$subject' (T_VARIABLE)
also here :
$subject= "Thankyou $name - Your repair has been logged"
this is the code you should use :
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("#", "#", "#", "#");
// Check connection
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$name = $_POST['name'];
$initials = $_POST['initials'];
$item = $_POST['item'];
$issue = $_POST['issue'];
$tel = $_POST['tel'];
$email = $_POST['email'];
$cost = $_POST['cost'];
$loggedby = $_POST['loggedby'];
$bag = $_POST['bag'];
$charger = $_POST['charger'];
// attempt insert query execution
$sql = "INSERT INTO `repairs` (`name`,`initials`,`item`, `issue`, `telephone`,`email`, `cost`, `loggedby`, `bag`, `charger`) VALUES (?,?,?,?,?,?,?,?,?,?)";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, 'ssssssssss', $name, $initials, $item, $issue, $tel, $email, $cost, $loggedby, $bag, $charger);
if (mysqli_stmt_execute($stmt)) {
$to = "emailaddress#emails.co.uk,$email";
$subject = "Thankyou $name - Your repair has been logged";
$body = "<h2>Thankyou $name</h2> /n
This is a confirmation email regarding your $item /n
Your repair log is below: /n
$item /n
$issue /n/n
<h3>Accessories</h3> /n
bag - $bag /n
charger - $charger /n/n
Your repair was logged by $loggedby on " . date("d-m-Y") . "/n/n
We will contact you on $tel & $email when your $item is ready to
collect.
/n/n
Loud Crowd IT - 01302 965482 /n
repairs#loudcrowdit.co.uk /n
www.loudcrowd.agency /n";
if (mail($to, $subject, $body)) {
header('location:repairs.php');
}
} else {
printf("Error: %s.\n", mysqli_stmt_error($stmt));
}
mysqli_close($stmt);
// close connection
mysqli_close($link);
?>
How to Fix the 500 Internal Server Error
500 Internal Server Error is a server-side error, meaning the problem probably isn't with your computer or internet connection but instead with the website's server.
While not probable, it is possible that there's something wrong on your end, in which case we'll look at some things you can try:
Reload the web page. You can do that by clicking the refresh/reload button, pressing F5 or Ctrl-R, or trying the URL again from the address bar.
Even if the 500 Internal Server Error is a problem on the web server, the issue might just be temporary. Trying the page again will often be successful.
Note: If the 500 Internal Server Error message appears during the checkout process at an online merchant, be aware that duplicate attempts to checkout may end up creating multiple orders - and multiple charges! Most merchants have automatic protections from these kinds of actions, but it's still something to keep in mind.
Clear your browser's cache. If there's a problem with the cached version of the page you're viewing, it could be causing HTTP 500 issues.
Note: Internal Server Errors are not often caused by caching issues, but I have, on occasion, seen the error go away after clearing the cache. It's such an easy and harmless thing to try, so don't skip it.
Delete your browser's cookies. Some 500 Internal Server Error issues can be corrected by deleting the cookies associated with the site you're getting the error on.
After removing the cookie(s), restart the browser and try again.
Troubleshoot as a 504 Gateway Timeout error instead.
It's not very common, but some servers produce a 500 Internal Server Error when in reality a more appropriate message based on the cause of the problem, is 504 Gateway Timeout.

PHP forgot password

I am trying to create a forgot password page for the user in PHP but when I enter the code the page just reloads and nothing else happens . No errors nothing .
if($submit){
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$submit = $_POST['submit'];
$email_check = mysqli_query($conn ,"SELECT * FROM users WHERE email='" . $email. "'");
$count = mysqli_num_rows($email_check);
if($count != 0 ){
// generate a new password
$random = rand(72891, 92729);
$new_password = $random;
$email_password = $new_password;
$new_password = password_hash($new_password, PASSWORD_BCRYPT, array('cost' => 14));
$new_password = password_hash($new_password);
mysqli_query("update users set pw='" . $new_password. "' WHERE email='" . $email. "'");
$subject = "Login information";
$message = "Your password has been changed to $email_password";
$from = "From: example.me";
mail($email, $subject, $message, $from);
echo "Your new password has been sent to you";
} else {
echo"This email does not exists";
}
}
I will tell you exactly what is going on with your code here.
Part 1:
if($submit){
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$submit = $_POST['submit'];
$submit = $_POST['submit']; is assigned after your opening if($submit).
Result with error reporting: Undefined submit variable.
Part 2:
$new_password = password_hash($new_password, PASSWORD_BCRYPT, array('cost' => 14));
$new_password = password_hash($new_password);
You're trying to double hash which won't give you any added benefits and will also fail when trying to verify it later. What happened here is that the second one failed and shouldn't even be used at all.
Why did it fail? Because, it's missing a parameter.
Result:
Warning: password_hash() expects at least 2 parameters, 1 given in /path/to/file.php on line x
Added result: An empty password row (when the UPDATE happens. See "Part 3").
Part 3:
mysqli_query("update users set pw='" . $new_password. "' WHERE email='" . $email. "'");
The query doesn't contain a database connection for it.
Result:
Warning: mysqli_query() expects at least 2 parameters, 1 given in /path/to/file.php on line x
In regards to your variables and the connection API used is unknown, so you will have to make sure that you are using the same MySQL API to connect with, and that your variables and POST arrays contain values.
Error reporting will help you, as will checking for errors on the query.
References:
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/mysqli.error.php
Final notes:
Use a prepared statement instead, it's much safer
https://en.wikipedia.org/wiki/Prepared_statement
Also; you should let the user choose their own password in a reset with a unique/one time token and hash it "once", not twice and shouldn't be mailed their password and for a lot of reasons. This is best common practice. If the user's email account ever gets compromised and they haven't deleted the email containing their login password, then they are at risk in having their login account also being compromised.
$submit is not declared until after the validation of your if statement.
Validate using another variable. Good place to start is to check and see if $_POST is submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST')
To email the password change
$message = "Your password has been changed to $email_password";
to
$message = "Your password has been changed to {$email_password}";
The password stored in the DB has been hashed twice. Remove
$new_password = password_hash($new_password);
The SQL needs to be executed to update the password hash in the database.
$sql = "update users set pw='" . $new_password. "' WHERE email='" . $email. "'";
if (mysqli_query($conn, $sql)) {
echo "Password updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
You're testing for $submit but defining $submit inside of the test, so $submit likely isn't evaluating as true.
Try changing the outer if ($submit) to if (!empty($_POST))

getting white screen after executing php code

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

Undefined variable in PHP when referencing MySQL element

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.

Categories