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.
Related
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.
This is what I have and it's not working. I need to check if the fields in Your_Location.php is empty. If it is, throw an error. If not; run the query as follow. It would work if I throw in //if (!mysqli_query($conn,$sqlinsert))
<?php
//session_start();
include 'dbConfig.php';
include 'Your_Location.php';
$childfirst = $_POST['element_1'];
$childlast = $_POST['element_2'];
$childdobyear = $_POST['element_3_3'];
$childdobmon = $_POST['element_3_1'];
$childdobday = $_POST['element_3_2'];
$childbaptize = $_POST['element_4'];
$childrelationship = $_POST['inputrelation'];
$childdob = "$childdobyear-$childdobmon-$childdobday";
$sqlinsert="INSERT INTO memchild (ID, FirstName, LastName, DOB, Baptize, Relationship)
VALUES
('$getid2','$childfirst','$childlast','$childdob','$childbaptize','$childrelationship')";
//Build arrays of fields
$required = array('element_1', 'element_2', 'element_3_3', 'element_3_2', 'element_3_1', 'elelment_4', 'inputrelation');
//Loop to check for empties
$error = false;
foreach($required as $fields) {
if(empty($_POST[$fields])){
$error = true;
}
}
if($error){
Sleep(3)
?>
<script>
document.getElementById('li_9').innerHTML = '* $childfirst Make sure the fields are not empty.';
</script>
<?php
exit();
}Else{
mysqli_query($conn,$sqlinsert)
?>
<script>
document.getElementById('li_9').innerHTML = '$childfirst $childlast has been added.';
</script>
<?php
sleep(3);
echo "<meta http-equiv='refresh' content='0'>";
}
?>
First try to check if the keys actually exist.
$childfirst = isset($_POST['element_1'])? $_POST['element_1'] : null;
secondly, you can check what field is not filled in:
$errorMessage = '';
foreach($required as $key) {
if(empty($_POST[$key])){
$error = true;
// break; // Uncomment if you want to exit the loop if one field is not set
// $errorMessage .= $key . ' is not filled in'; // Uncomment if you want to add message for every missing key
}
}
for your scripts, you are trying to combine PHP value with javascript, you need to actually echo or print the value like this:
<script>
document.getElementById('li_9').innerHTML += "* <?php echo $childfirst;?> Make sure the fields are not empty.";
</script>
and also for the second one
<script>
document.getElementById('li_9').innerHTML += "<?php echo $childFirst . ' ' . $childLast;?> has been added.";
</script>
Hey your error is you passing string values to check and its not empty already
change this line
$required = array('element_1', 'element_2', 'element_3_3', 'element_3_2', 'element_3_1', 'elelment_4', 'inputrelation');
to
$required = array("$element_1", "$element_2");
Add the other elements too
And change this too
foreach($required as $fields) {
if(empty($fields)){
$error = true;
}
}
Hope it works for You
So I am trying to make a simple e-commerce site. Once I submit the form (btn-submit), I am not able to insert any data to my database. Only the address and contact number verification works.
Here is my code:
if ( isset($_POST['btn-submit']) ) {
// clean user inputs
$oadd = trim($_POST['oadd']);
$oadd = strip_tags($oadd);
$oadd = htmlspecialchars($oadd);
$contact = trim($_POST['contact']);
$contact = strip_tags($contact);
$contact = htmlspecialchars($contact);
// address validation
if (empty($oadd)) {
$error = true;
$oaddError = "Please enter a valid address.";
} else if (strlen($oadd) < 5) {
$error = true;
$oaddError = "Please enter a valid address.";
}
// contact number validation
if (empty($contact)) {
$error = true;
$contactError = "Please enter your contact number.";
} else if (strlen($contact) < 7) {
$error = true;
$contactError = "Contact number must have atleast 7 digits.";
} else if (!preg_match("/^[0-9 ]+$/",$lname)) {
$error = true;
$lnameError = "Please enter a valid contact number.";
}
// if there's no error, continue to place order
if( !$error ) {
$query = 'INSERT INTO cust_order(Order_Date, Order_Status, Order_Total , Address, Contact_No) VALUES (CURDATE(), "in process" , (SELECT SUM(p.Product_Price) FROM cart c, product p WHERE c.Prod_ID = p.Product_ID and c. User_ID = "'.$userRow['User_ID'].'"),"'.$oadd.'","'. $contact.'")';
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Your order has been placed. To view the details, go to your order history";
unset($oadd);
unset($contact);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong. Please try again later.";
}
}
}
What could possibly be wrong with my code? I did similar queries in the other pages but this is the only one not working. Any help would be greatly appreciated! Thanks in advance!
Try to understand the code flow:
if( !$error ) {
// This will only works when **$error is false and the not of false is true**, otherwise this block does not execute
}
So this code works only when there is no validation error occurs in your code and $error contains false
//$userRow is not define any where...
//to check error occur or not :
echo $error;
if(!$error)
{
echo "IN IF";
//also go with die..
$res = mysql_query($query) or die();
}
else
{
echo "IN ELSE";
}
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;
}
}
}
}
?>
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 */ };
?>