PHP PDO not inserting or throwing error - php

The email is not being inserted into the database, however I am receiving an echo of success without any errors. I'm not sure what is going wrong. I've tried it with a duplicate email and I get the duplicate email message so it is connecting to the database, and it will not insert when it is a duplicate; however, it seems to not be inserting anything when it is not a duplicate. It seems to just skip the step of uploading.
<?php
include 'db_functions.php';
$_POST['email'] = 'somenewemail#gmail.com';
if(isset($_POST['email']) && ($_POST['email'] != NULL || $_POST['email'] != '')){
$ERRORS = array();
$cleanEmail = htmlentities($_POST['email']);
$database = dbconnlocal();
$queryEmailExists = $database->prepare("SELECT email FROM email_list WHERE email= ?");
$queryUploadEmail = $database->prepare("INSERT INTO email_list (email) VALUES ( ? )");
$database->beginTransaction();
try
{
$queryEmailExists->execute(array($cleanEmail));
$results = $queryEmailExists->fetchAll(PDO::FETCH_ASSOC);
$dbEmail = $results[0]['email'];
if(trim($dbEmail) == trim($cleanEmail)) {
// duplicate email
throw new Exception('duplicateEmail');
} else {
// new email
$queryUploadEmail->execute(array($cleanEmail));
echo json_encode('success');
}
}
catch (Exception $e)
{
switch(trim($e->getMessage())) {
case 'duplicateEmail':
// handle duplicate error
$ERRORS['error'] = 'duplicateEmail';
break;
default:
// handle default errors
$ERRORS['error'] = 'default';
break;
}
echo json_encode($ERRORS['error']);
}
} else { echo json_encode('emptyEmail'); /* empty email */ };
?>

Related

Validation for registration page in PHP

I have a registration page and I want to validate it. I have this code:
$msg = "";
$msg_3 = "";
if(isset($_POST['submit'])) {
$First_Name = ((isset($_POST['First_Name']))?sanitize($_POST['First_Name']):'');
$Last_Name = ((isset($_POST['Last_Name']))?sanitize($_POST['Last_Name']):'');
$email = ((isset($_POST['email']))?sanitize($_POST['email']):'');
$confirm_email = ((isset($_POST['confirm_email']))?sanitize($_POST['confirm_email']):'');
$mobile_number = ((isset($_POST['mobile_number']))?sanitize($_POST['mobile_number']):'');
$password = ((isset($_POST['password']))?sanitize($_POST['password']):'');
$confirm_password = ((isset($_POST['confirm_password']))?sanitize($_POST['confirm_password']):'');
$gender = ((isset($_POST['gender']))?sanitize($_POST['gender']):'');
$day = ((isset($_POST['day']))?sanitize($_POST['day']):'');
$month = ((isset($_POST['month']))?sanitize($_POST['month']):'');
$year = ((isset($_POST['year']))?sanitize($_POST['year']):'');
$insurance = ((isset($_POST['insurance']))?sanitize($_POST['insurance']):'');
$agree = ((isset($_POST['agree']))?sanitize($_POST['agree']):'');
$sql = "SELECT email, mobile_number FROM customers WHERE email ='$email' OR mobile_number ='$mobile_number'";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if ($email == $row['email']) {
$msg = "<span class='text-danger'>The email address you've entered is already associated with another account.
<br>Please sign in or enter a different email address. Please try again.</span>";
} if ($mobile_number == $row['mobile_number']) {
$msg_3 = "<span class='text-danger'>The mobile phone number you've entered is already associated with another account.
<br>Please sign in or enter a different number. Please try <br>again.</span>";
}
}
} else {
// Insert into database and send email
}
Now how could I validate each field if it is empty and print different messages under each field in this nested if and while. I'm getting confused.
If you will use same names in db as in form you could use something like this:
$keys = ['gender', 'email', 'mobile_number']; //etc
$errors = [];
while ($row = $result->fetch_assoc()) {
array_walk($keys, function ($key) {
if (empty($row[$key])) {
$errors[] = "$key is required"
}
if (isset($_POST[$key]) && $_POST[$key] == $row[$key]) {
$errors[] = "please enter $key"
}
})
}
if you need to have more customized messages you might map keys to error text like:
$keys = ['gender' => ['equal' => 'your error message', 'empty' => 'empty msg'], 'email' => ['equal' => 'email validation error', 'empty' => 'error msg 2']]; //etc
$errors = [];
while ($row = $result->fetch_assoc()) {
array_walk($keys, function ($errorMsg, $key) {
if (isset($_POST[$key]) && $_POST[$key] == $row[$key]) {
$errors[$key] = $errorMsg['equal'];
}
if (empty($row[$key])) {
$errors[$key] = $errorMsq['empty'];
}
})
}
Do not repeat
Prevent SQL Injection
You can do something like this.
<?php
if(isset($_POST['submit'])) {
$errors = [];
function getPost($postIndex, $errorMessage = '') {
global $errors;
if (!empty( $_POST[$postIndex] )) {
$value = $_POST[$postIndex];
return $value;;
} else {
$errors[$postIndex] = $errorMessage;
return null;
}
}
function validateString($s) {
return htmlspecialchars(trim($s));
}
getPost('First_Name', 'Firstname Cannot Be Empty');
getPost('Last_Name', 'Lastname cannot be empty');
$email = getPost('email', 'Your Error Message');
getPost('confirm_email', 'Your Error Message');
$mobile_number = getPost('mobile_number', 'Your Error Message');
getPost('password', 'Your Error Message');
getPost('confirm_password', 'Your Error Message');
getPost('gender', 'Your Error Message');
getPost('day', 'Your Error Message');
getPost('month', 'Your Error Message');
getPost('year', 'Your Error Message');
getPost('insurance', 'Your Error Message');
getPost('agree', 'Your Error Message');
$stmt = $mysqli -> prepare('SELECT email, mobile_number FROM customers WHERE email =? OR mobile_number =?');
if (
$stmt &&
$stmt -> bind_param('ss', $email, $mobile_number) &&
$stmt -> execute() &&
$stmt -> store_result() &&
$stmt -> bind_result($dbEmail, $dbMobileNumber) &&
$stmt -> fetch()
) {
if ($email == $dbEmail) {
// email equal error message
} if ($mobile_number == $row['mobile_number']) {
// mobile number equal error message
}
}
if (count($errors)) {
echo "You have an error";
}
// or get the post index in your HTML form and show the error message there
// <?php isset($errors['firstName']) ? echo $errors['firstname'] : null;
}

Unable to get Table Name using variable string MYSQL Error

if ($_GET['category'] == "ebooks")
{ $tableName = $smallsubcodewithoutspace.'_ebooks';
$sectionTitle = "Ebook";
}
elseif ($_GET['category'] == "syllabus")
{ $tableName = $smallsubcodewithoutspace.'_syllabus';
$sectionTitle = "Syllabus";
}
elseif ($_GET['category'] == "pnotes")
{ $tableName = $smallsubcodewithoutspace.'_pnotes';
$sectionTitle = "Practical Note";
}
elseif ($_GET['category'] == "assignments")
{ $tableName = $smallsubcodewithoutspace.'_assignments';
$sectionTitle = "Assignment";
}
elseif ($_GET['category'] == "tnotes")
{ $tableName = $smallsubcodewithoutspace.'_tnotes';
$sectionTitle = "Theory Notes";
}
//if form has been submitted process it
if(isset($_POST['submit'])){
$_POST = array_map( 'stripslashes', $_POST );
//collect form data
extract($_POST);
//very basic validation
if($contentTitle ==''){
$error[] = 'Please enter the Content Title !';
}
if($contentLink ==''){
$error[] = "Please enter the Content Link !";
}
if(!isset($error)){
try {
//insert into database
$stmt = $db->prepare("INSERT INTO `$tableName` (contentTitle,contentLink,contentAuthor) VALUES (:contentTitle, :contentLink, :contentAuthor)") ;
$stmt->execute(array(
':contentTitle' => $contentTitle,
':contentLink' => $contentLink,
':contentAuthor' => $contentAuthor
));
//redirect to index page
header('Location: add-content.php?notallowed=true');
exit;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<div align="center" class="alertpk"><div class="alert alert-warning" role="alert">'.$error.'</div></div>';
}
}
Actually, problem started when I tried inserting Table name with variable. Tables exist in database. total 5 databases are there in which I will insert data according to users selection, but when form executed, a error is thrown saying:
SQLstate[42000]: SYNTAX ERROR OR ACCESS VIOLATION 1103, INCORRECT TABLE NAME ' '
The error INCORRECT TABLE NAME '' error means you don't have a value in $tableName. Your $_GET['category'] is not picking up a recognized value or the extract($_POST) is changing $tableName to an empty value.
I got the solution, I shifted tableVariables section inside try and its now working.
var dump your variable, post to see what value comes up.

PHP redirecting before finish MySQL insert

I have this code on "insert.php":
if ($stmt = $GLOBALS['mysqli']->prepare("INSERT INTO table1(iduser, title, msg, anonim, ip, iduniversity) VALUES (?,?,?,?,?,?)")) {
$stmt->bind_param("issisi", $_SESSION['iduser'], $_POST['title'], $_POST['msg'], $anonim, getIP(), $_SESSION['iduniversity']);
if ($stmt->execute()) {
$idmsg = $GLOBALS['mysqli']->insert_id;
$i = 0;
$stmt2 = $GLOBALS['mysqli']->prepare("INSERT INTO tag(idmsg, tag) VALUES(?,?)");
foreach ($tags as $tag) {
if ($tag != '') {
$stmt2->bind_param("is", $idmsg, $tag);
if ($stmt2->execute()) {
$i++;
}
}
}
$stmt2->close();
$stmt->close();
mysqli_close($GLOBALS['mysqli']);
sendFile($idmsg);
header("Location: /public/watch_msg.php?idmsg=" . $idmsg);
exit();
} else {
exit("Ops! Ocorreu algum erro. COD1370");
}
} else {
exit("Ops! Ocorreu algum erro. COD1371");
}
So, everything is working fine, except that sometimes when it redirects to "watch_msg.php" the message seems not to be on the database yet. When this happens, as soon as I refresh the page, everything is there!
First thing I thought is that there could be a race-condition somewhere, but I read in another question that PHP is sequential, and as I close both statements and connection before the redirect (so that used tables should be unlocked), why i'm getting this result somethimes? What i'm doing wrong?
Also, no functions outputs anything, but "sendFile" saves an image if the user sends one, so headers should be fine (it also gives me the error when I comment the function).
Code on watch_msg:
$msg = NULL;
$tags = NULL;
$coments = NULL;
$data_high = date("Y-m-d H:i:s");
$iduser;
if ($loggedin) { //If logged in
$idmsg = filter_input(INPUT_GET, 'idmsg', FILTER_SANITIZE_STRING);
$iduser = $_SESSION['iduser'];
$query = "SELECT * FROM table1 WHERE iduser = ? AND idmsg = ? AND datemsg < ?";
$stmt = $GLOBALS['mysqli']->prepare($query);
$stmt->bind_param("iis", $iduser, $idmsg, $data_high);
if ($stmt->execute()) {
$msg = mysqli_fetch_assoc($stmt->get_result());
if ($msg === NULL) {
exit('This message doesn\'t exists');
}
...
} else {
echo "Error.";
}
}

Cant insert Data into my Mysql Database?

I need a help from this error i cant insert data into my database, can you see my codes, im newly in php so please help me for this. thank you for your helping and giving a good answer,
it always saying "an error eccurred while sending" it is based on my else condition
<?php
if(isset($_SESSION['username']))
{
$form = true;
$orfvp_destination = '';
$oreq_approver= '';
$oreq_noter = '';
$orfvp_duration = '';
$orfvp_purpose = '';
//to check if the form has been sent
if(isset($_POST['rfvp_destination'], $_POST['req_approver'], $_POST['req_noter'], $_POST['rfvp_duration'], $_POST['rfvp_purpose']))
{
$orfvp_destination = $_POST['rfvp_destination'];
$oreq_approver = $_POST['req_approver'];
$oreq_noter = $_POST['req_noter'];
$orfvp_duration = $_POST['rfvp_duration'];
$orfvp_purpose = $_POST['rfvp_purpose'];
//to remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$orfvp_destination = stripslashes($orfvp_destination);
$oreq_approver = stripslashes($oreq_approver);
$oreq_noter = stripslashes($oreq_noter);
$orfvp_duration = stripslashes($orfvp_duration);
$orfvp_purpose = stripslashes($orfvp_purpose);
}
//to check if all the fields are filled
if($_POST['rfvp_destination']!='' and $_POST['req_approver']!='' and $_POST['req_noter']!='' and $_POST['rfvp_duration']!='' and $_POST['rfvp_purpose']!='')
{
//to protect the variables
$rfvp_destination = mysql_real_escape_string($orfvp_destination);
$req_approver = mysql_real_escape_string($oreq_approver);
$req_noter = mysql_real_escape_string($oreq_noter);
$rfvp_duration = mysql_real_escape_string(nl2br(htmlentities($orfvp_duration, ENT_QUOTES, 'UTF-8')));
$rfvp_purpose = mysql_real_escape_string($orfvp_purpose);
//to check if the recipient exists
$dn1 = mysql_fetch_array(mysql_query('select count(user_id) as req_approver, user_id as req_approverid, (select count(*) from request) as npm from users where user_username="'.$req_approver.'"'));
$dn2 = mysql_fetch_array(mysql_query('select count(user_id) as req_noter, user_id as req_noterid, (select count(*) from request) as npm from users where user_username="'.$req_noter.'"'));
if($dn1['req_approver'] and $dn2['req_noter']==1)
{
//to check if the recipient is not the actual user
if($dn1['req_approverid']!=$_SESSION['userid'] and $dn2['req_noter']!=$_SESSION['userid'])
{
$id = $dn1['npm']+1 and $dn2['npm']+1;
//We send the message
if(mysql_query('insert into rfv (rfv_id, rfv_code, rfv_driver, rfv_vehicle)values("'.$id.'", "RFV2015-'.$id.'", "", "")')
and mysql_query('insert into rfv-p (rfv_code, rfvp_destination, rfvp_purpose, rfvp_duration)values("RFV2015-'.$id.'", "rfvp_destination", "rfvp_purpose", "rfvp_duration")')
and mysql_query('insert into request (req_code, req_date, req_status, req_dateneeded, req_requestor, req_approver, req_noter, form_id)values( "RFV2015-'.$id.'", NOW(), "Waiting for Approval", "'.$_POST['req_dateneeded'].'", "'.$_SESSION['userid'].'", "'.$dn1['req_approverid'].'","'.$dn2['req_noterid'].'", 2)'))
{
?>
<p style="color:red" align="center" >Request Successfully Created!</p>
<p style="color:red" align="center" >Home</p>
<?php
$form = false;
}
else
{
//Otherwise, we say that an error occured
$error = 'An error occurred while sending the message';
}
}
else
{
//Otherwise, we say the user cannot send a message to himself
$error = 'You cannot send a message to yourself.';
}
}
else
{
//Otherwise, we say the recipient does not exists
$error = 'The recipient does not exists.';
}
}
else
{
//Otherwise, we say a field is empty
$error = 'A field is empty. Please fill of the fields.';
}
}
elseif(isset($_GET['req_approver'], $_GET['req_noter']))
{
//We get the username for the recipient if available
$oreq_approver = $_GET['req_approver'];
$oreq_noter = $_GET['req_noter'];
}
if($form)
{
//We display a message if necessary
if(isset($error))
{
echo '<div class="message" align="center" style="color:red">'.$error.'</div>';
}
//We display the form
?>
In the above script 2 if are not closed. First one is if(isset($_SESSION['username'])) and second one is if($form). Close the curly bracket } at correct place and that should work as expected.

Can't figure out how to format this logic statement in PHP

I have some PHP I'm using to validate a form, and once the validation is complete the data from the form is sent into a database. My problem isn't actually a code problem, it's just I can't figure out how to write the if-else statement blocks.
Basically I have all these if statements that check if one of the form fields is empty or doesn't meed the criteria, and then a corresponding else statement which simply holds the data they've entered, so when the form reloads they don't have to enter it in again. At the moment I have an else statement at the end which posts all the data into my database when all the fields are validated - the problem is that I have one too many else statements and it gives me errors for this.
So I figure I have to wrap the whole block of code in one if-else statement, that would basically say if there are no errrors, do the else which sends the data to the database.
Basically I have the else done, I just need help to think of what condition to put for the if
Here's my code
//Define the database connection
$conn = mysqli_connect("danu.nuigalway.ie","myb1608re","fa3xul", "mydb1608") or die (mysql_error());
## Initialise varialbes to null ##
$nameError ="";
$emailError ="";
$categoryError ="";
$messageError ="";
$validName ="";
$validEmail ="";
$validMessage ="";
## On submitting form below function will execute ##
if(isset($_POST['submit']))
{
//assign details to be posted to variables
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$category = $_POST['category'];
//if name is less than 10 characters
if (empty($_POST["name"]) || strlen($name)<10)
{
$nameError ="* Name is too short";
}
else
{
$validName = $_POST["name"];
}
//if email is too short or is not the right format
if (empty($_POST["email"]) || !preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email) || strlen($email)<10 )
{
$emailError = "* You did not enter a valid email";
$validEmail = $_POST["email"];
}
else
{
$validEmail = $_POST["email"];
}
//if a category is not chosen
if (empty($_POST["category"])) {
$categoryError = "* Please select a category";
}
//if the message is left blank
if (empty($_POST["message"]) || strlen($message)<25 ) {
$messageError = "* Your message is too short";
}
else {
$validMessage = $_POST["message"];
}
//If there are no errors, email details to admin
else {
// variables to send email
$to = "e.reilly4#nuigalway.ie";
$subject = "Contact Form";
$body = "\r\n
Category: $_POST[category] \r\n
Message: $_POST[message] \r\n
Name: $_POST[name] \r\n
Email: $_POST[email]";
// Email Function
mail($to,$subject,$body);
//Insert the data into the database
$conn->query("INSERT INTO Assignment(Name, Email, Category, Message)VALUES('$name', '$email', '$category', '$message')", MYSQLI_STORE_RESULT);
$conn->close();
echo "sent to database";
}
}
?> <!-- End of PHP -->
Essentially I need to figure out another if statement to put just after the first one, but for the life of me I can't think of a condition to have. I thought what if I made a boolean that was false, and once all the data is correct it is put to true, but I can't figure out how to implement it. Just looking for any ideas on how to go about it
When I do validation, I personally try to come up with a function that will validate each value similarly. There are a few checks you should be doing as you go. Here is a restructure of what you have with some notations:
<?php
//Define the database connection
$conn = mysqli_connect("danu.nuigalway.ie","myb1608re","fa3xul", "mydb1608") or die (mysql_error());
// I usually build a simple validate function
// This is just an example, you can edit based on your needs
function validate_var($value = false,$type = 'str')
{
// Validate the different options
if(!empty($value) && $value != false) {
switch ($type) {
case ('str'):
return (is_string($value))? true:false;
case ('num') :
return (is_numeric($value))? true:false;
case ('email'):
return (filter_var($value,FILTER_VALIDATE_EMAIL))? true:false;
}
// This will just check not empty and string length if numeric
if((is_numeric($type) && !empty($value)) && (strlen($value) >= $type))
return true;
}
// Return false if all else fails
return false;
}
// On post, proceed
if(isset($_POST['submit'])) {
//assign details to be posted to variables
$name = $_POST['name'];
$email = $_POST['email'];
// Strip the message of html as a precaution
// Since you are not binding in your sql lower down, you should probably use
// htmlspecialchars($_POST['message'],ENT_QUOTES))
// or use the binding from the mysqli_ library to escape the input
$message = htmlspecialchars(strip_tags($_POST['message']),ENT_QUOTES));
// Do a "just-incase" filter (based on what this is supposed to be)
$category = preg_replace('/[^a-zA-Z0-9]/',"",$_POST['category']);
// Validate string length of 10
if(!validate_var($name,10))
$error['name'] = true;
// Validate email
if(!validate_var($email,'email'))
$error['email'] = true;
// Validate message length
if(!validate_var($message,25))
$error['message'] = true;
// Validate your category
if(!validate_var($category))
$error['category'] = true;
// Check if there are errors set
if(!isset($error)) {
// Use the filtered variables,
// not the raw $_POST variables
$to = "e.reilly4#nuigalway.ie";
$subject = "Contact Form";
$body = "\r\n
Category: $category \r\n
Message: $message \r\n
Name: $name \r\n
Email: $email";
// Don't just send and insert, make sure you insert into your databases
// on successful send
if(mail($to,$subject,$body)) {
//Insert the data into the database
$conn->query("INSERT INTO Assignment(Name, Email, Category, Message)VALUES('$name', '$email', '$category', '$message')", MYSQLI_STORE_RESULT);
$conn->close();
echo "sent to database";
}
else
echo 'An error occurred.';
}
else {
// Loop through errors cast
foreach($error as $kind => $true) {
switch ($kind) {
case ('name') :
echo "* Name is too short";
break;
case ('email') :
echo "* You did not enter a valid email";
break;
case ('category') :
echo "* Please select a category";
break;
case ('message') :
echo "* Your message is too short";
break;
}
}
}
}
?>

Categories