I have a form as part of a custom plugin, but it is not retaining the data when submitted. It saves in the database, and if I refresh the page it shows the information, but I want it to stay in the form first time.
I know it must be something really stupid, I just don't seem to find it... Thanks in advance!
This is the code:
<?php
global $guarantor_details;
add_shortcode('guarantorForm', 'guarantor_form');
function guarantor_form()
{
$output = "";
global $current_user;
$current_user = wp_get_current_user();
$guarantor_details = getGuarantorData();
$message = (isset($_POST["guarantor_save"])) ? saveGuarantor() : false;
if ($message) $output .= '<div class="success">' . $message . '</div>';
$message = (isset($_GET["resend"]) == "true") ? generateGuarantorEmail($guarantor_details) : false;
if ($message) $output .= '<div class="success">' . $message . '</div>';
if($current_user->ID){
$output .= '
<h1>Guarantor Details</h1>
<form action="" method="POST" class="profileForm">
<div class="formField">
<label for="guarantor_title">Title</label>
<select name="guarantor_title">
<option value="Mr">Mr</option>
<option value="Miss">Miss</option>
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
</select>
</div>
<div class="formField">
<label for="guarantor_name">Guarantor Full Name</label>
<input name="guarantor_name" type="text" required
value="' . $guarantor_details->guarantor_name . '"/>
</div>
<div class="formField">
<label for="guarantor_relationship">Relationship to student</label>
<input name="guarantor_relationship" type="text" required
value="' . $guarantor_details->guarantor_relationship . '"/>
</div>
<div class="formField">
<label for="guarantor_address1">Address 1</label>
<input name="guarantor_address1" type="text" required
value="' . $guarantor_details->guarantor_address1 . '"/>
</div>
<div class="formField">
<label for="guarantor_address2">Address 2</label>
<input name="guarantor_address2" type="text" value="' . $guarantor_details->guarantor_address2 . '"/>
</div>
<div class="formField">
<label for="guarantor_city">City</label>
<input name="guarantor_city" type="text" required
value="' . $guarantor_details->guarantor_city . '"/>
</div>
<div class="formField">
<label for="guarantor_county">County</label>
<input name="guarantor_county" type="text" required
value="' . $guarantor_details->guarantor_county . '"/>
</div>
<div class="formField">
<label for="guarantor_postcode">Postcode</label>
<input name="guarantor_postcode" type="text" required
value="' . $guarantor_details->guarantor_postcode . '"/>
</div>
<div class="formField">
<label for="guarantor_country">Country</label>
<select name="guarantor_country">
' . countryList() . '
</div>
<div class="formField">
<label for="guarantor_mobile">Mobile</label>
<input name="guarantor_mobile" type="tel" required
value="' . $guarantor_details->guarantor_mobile . '"/>
</div>
<div class="formField">
<label for="guarantor_confirm_mobile">Confirm Mobile</label>
<input name="guarantor_confirm_mobile" id="confirm_mobile" type="tel" required value="' . $guarantor_details->guarantor_mobile . '"/>
</div>
<div class="formField">
<label for="guarantor_telephone">Telephone</label>
<input name="guarantor_telephone" type="tel" required
value="' . $guarantor_details->guarantor_telephone . '"/>
</div>
<div class="formField">
<label for="guarantor_email">Email</label>
<input name="guarantor_email" type="email" required
value="' . $guarantor_details->guarantor_email . '"/>
</div>
<div class="formField">
<input name="guarantor_save" type="submit" value="Save"/>
</div>
<div class="formField alignRight">
Lost the email with the link? Resend Email
</div>
</form>
';}
else{
$output = 'You must login to fill in guarantor details.';
}
return $output;
}
function getGuarantorData()
{
global $current_user;
global $wpdb;
$table = $wpdb->prefix . 'vebra_tenants';
$guarantor_details = $wpdb->get_row(
"
SELECT *
FROM $table
WHERE tenant_user_id = $current_user->ID
"
);
return isset($guarantor_details) ? $guarantor_details : false;
return $guarantor_details;
}
//save guarantor details
function saveGuarantor()
{
global $wpdb;
global $current_user;
$guarantor_details = getGuarantorData();
$details = $_POST;
unset($details["guarantor_save"]); //no submit
unset($details["guarantor_confirm_mobile"]); //no submit
if ($guarantor_details) {
$wpdb->update(
$wpdb->prefix . 'vebra_tenants',
$details,
array('tenant_user_id' => $current_user->ID));
} else {
$details['tenant_user_id'] = $current_user->ID;
$wpdb->insert($wpdb->prefix . 'vebra_tenants', $details);
$guarantor_details = getGuarantorData();
}
//let db know details updated
update_user_meta($current_user->ID, 'vebra_guarantor_details', true );
//send email if not already sent
if ($guarantor_details->guarantor_hash == "") {
generateGuarantorEmail($guarantor_details);
return "The guarantor details have been saved and an email has been sent to your guarantor to accept the agreement. They have seven days to respond.";
}
//set status percentage of that property
$pcode = get_user_meta($current_user->ID, 'vebra_pcode', true);
saveStatusProgress($pcode);
return "The guarantor details have been saved";
}
function generateGuarantorEmail($guarantor_details)
{
global $current_user;
global $wpdb;
$code = md5($guarantor_details->guarantor_name);
$wpdb->update($wpdb->prefix . 'vebra_tenants',
array('guarantor_hash' => $code,
'guarantor_sent' => date('Y-m-d h:m:s')),
array('tenant_user_id' => $current_user->ID,
));
$message = "Hello " . $guarantor_details->guarantor_name . "\n\n";
$message .= "Your name has been listed as a guarantor for a student let for " . $guarantor_details->tenant_firstname . " " . $guarantor_details->tenant_surname;
$message .= "\n\nIf you have agreed to being the guarantor, please click on the link below to go to a secure area of our website. There you will find a copy of the Assured Tenancy Agreement for the property, and the guarantor form. Please print off the guarantor form, sign and have it witnessed and then return it to us as soon as you can.";
$message .= "\n\n" . get_permalink(get_option('vebra_confirmPermalink')) . "?confirm=" . $guarantor_details->guarantor_hash;
$message .= "\n\n If you have not agreed to being a guarantor, would you please email us to let us know.";
$message .= "\n\n Thank you for your help.\n\n \n\n";
sendEmailToPublic($guarantor_details->guarantor_email, ' ', 'Guarantor Proposal', $message);
return "An email has been sent to the guarantor with a link for them to activate and accept to be a guarantor";
}
You might not getting database stored values inside $guarantor_details object.
so please check are you getting something in $guarantor_details->guarantor_name
if not then try to resolve it,
OR
If you just want to display submitted data then, you can simply print the post data in your case for guarantor_mobile its
<input name="guarantor_mobile" type="tel" required value="'. $_POST["guarantor_mobile"].'"/>
Thanks for the answers, but I solved this in a different way, had to load $guarantor_details = getGuarantorData(); just before building the form to make sure the data was displayed correctly.
Related
Im working on a Opencart project and Im having trouble getting input data into db table. Currently when i submit it enters an empty record into the db.
I have a form that has several inputs and a save button. The query from the model works just fine when entered in phpmyadmin so Im having issues between the view and controller. This is a large pr0ject is overly confusing to me. Any help would be appreciated
html:
" class="btn btn-primary">
<form method="post" enctype="multipart/form-data" id="form-campaign" class="form-horizontal">
<div class="form-group">
<div class="col-sm-5 col-sm-push-1 form-group required>
<label class="col-sm-2 control-label" for="input-campaign-name"><?php echo $entry_name; ?></label>
<input type="text" name="name" value="" placeholder="<?php echo $entry_name; ?>" id="input-campaign-name" class="form-control" />
<?php if (isset($error_name[$language['language_id']])) { ?>
<div class="text-danger"><?php echo $error_name[$language['language_id']]; ?></div>
<?php } ?>
</div>
</div>
<div class="col-sm-5 col-sm-push-1 form-group required>
<label class="col-sm-2 control-label" for="input-campaign-goal"><?php echo $entry_goal; ?></label>
<input type="text" name="goal" value="" placeholder="<?php echo $entry_goal; ?>" id="input-campaign-goal" class="form-control" />
<?php if (isset($error_name[$language['language_id']])) { ?>
<div class="text-danger"><?php echo $error_name[$language['language_id']]; ?></div>
<?php } ?>
</div>
</div>
</form>
php: controller
public function add() {
$this->load->language('campaigns/campaign');
$this->document->setTitle($this->language->get('heading_title'));
$this->load->model('campaigns/campaign');
if (($this->request->server['REQUEST_METHOD'] == 'POST')) {
$this->model_campaigns_campaign->addCampaign($this->request->post);
$this->session->data['success'] = $this->language->get('text_success');
$url = '';
if (isset($this->request->get['filter_campaign_id'])) {
$url .= '&filter_campaign_id=' . $this->request->get['filter_campaign_id'];
}
if (isset($this->request->get['filter_campaign_name'])) {
$url .= '&filter_campaign_name=' . urlencode(html_entity_decode($this->request->get['filter_campaign_name'], ENT_QUOTES, 'UTF-8'));
}
if (isset($this->request->get['filter_campaign_goal'])) {
$url .= '&filter_campaign_goal=' . $this->request->get['filter_campaign_goal'];
}
if (isset($this->request->get['order'])) {
$url .= '&order=' . $this->request->get['order'];
}
if (isset($this->request->get['page'])) {
$url .= '&page=' . $this->request->get['page'];
}
$this->response->redirect($this->url->link('campaigns/campaign', 'token=' . $this->session->data['token'] . $url, true));
}
$this->getForm();
}
php: model
public function addCampaign() {
$this->db->query("INSERT INTO " . DB_PREFIX . "campaigns SET campaign_name = '" . $this->db->escape($data['campaign_name']) . "', campaign_giving_goal = '" . (float)$data['campaign_giving_goal']
. "', campaign_giving_count_goal = '" . (float)$data['campaign_giving_count_goal'] . "', campaign_owner = '" . $this->db->escape($data['campaign_owner']). "'");
$this->cache->delete('campaign');
return $campaign_id;
}
I am trying to store the form data into database using ajax but it doesn't shows any success neither any error.
Here is my code.
<form method="POST" id="add_user" name='reg' >
<fieldset>
<legend>Student information:-</legend>
<ul>
<li>
<label> FirstName: </label><input type="text" id="name" name="name" required>
<span id='error' style="display:none;color:red;"> Only alphabets </span>
</li>
<li>
<label> LastName: </label><input type="text" id="lname" name="lname" required>
<span id='error1' style="display:none;color:red;"> Only alphabets </span>
</li>
<li>
<label>Username:</label>
<input type="text" id="username" name="username"/>
< /li>
<li>
<label>Password:</label>
<input type="password" id="password" name="password"/>
</li>
<label>
Gender: </label>
<input type="radio" id='gender' name="gender" value="male" required> Male
<input type="radio" name="gender" id='gender' value="female" required> Female
<input type="radio" name="gender" id='gender' value="other" required> Other
<li>
<label>
Email: </label>
<input id="email" type="text" name="email" required>
<span id='error2' style="display:none;color:red;"> Invalid email </span>
</li>
<li>
<label> Mobile:</label>
<input id="mobile" type="text" maxlength="10" name="mobile" required >
<span id='error3' style="display:none;color:red;"> only digits </span>
</li>
<li>
address: <textarea name="address" type="text" rows="3" cols="40"> </textarea>
</li>
</ul>
<p><button class = 'button' type="submit" id='submit'>Add User</button></p>
</fieldset>
</form>
This form in which i enter any values it got stored into database.
Here is my js file which uses ajax function to send data inext file which stores the result into database
serve.js
$(document).ready(function(){
$(document).on('submit','#add_user',function(e){
var form_data = $('#add_user').serialize();
var request = $.ajax({
url: 'fun.php?job=add',
cache : false,
data : form_data,
dataType : 'json',
contentType : 'application/json; charset=utf-8',
type : 'get'
});
request.done(function(output){
if (output.result == 'success'){
var name = $('#fname').val();
show_message("User '" + name + "' added successfully.", 'success' );
}, true);
} else{
show_message('Add request failed','error');
};
});
});
fun.php
if ($job != ''){
// Connect to database
$db_connection = mysqli_connect($db_server, $db_username, $db_password, $db_name);
if (mysqli_connect_errno()){
$result = 'error';
$message = 'Failed to connect to database: ' . mysqli_connect_error();
$job = '';
}
if ($job == 'add'){
/ / Add user
$query = "INSERT INTO oops ";
if (isset($_GET['name'])) { $query .= "name = '" . mysqli_real_escape_string($db_connection, $_GET['name']) . "', "; }
if (isset($_GET['lname'])) { $query .= "lname = '" . mysqli_real_escape_string($db_connection, $_GET['lname']) . "', "; }
if (isset($_GET['username'])) { $query .= "username = '" . mysqli_real_escape_string($db_connection, $_GET['username']) . "', "; }
if (isset($_GET['password'])) { $query .= "password = '" . mysqli_real_escape_string($db_connection, $_GET['password']) . "', "; }
if (isset($_GET['gender'])) { $query .= "gender = '" . mysqli_real_escape_string($db_connection, $_GET['gender']) . "', "; }
if (isset($_GET['email'])) { $query .= "email = '" . mysqli_real_escape_string($db_connection, $_GET['email']) . "', "; }
if (isset($_GET['mobile'])) { $query .= "mobile = '" . mysqli_real_escape_string($db_connection, $_GET['mobile']) . "', "; }
if (isset($_GET['address'])) { $query .= "address = '" . mysqli_real_escape_string($db_connection, $_GET['address']) . "'"; }
$query = mysqli_query($db_connection, $query);
if (!$query){
$result = 'error';
$message = 'query error';
} else {
$result = 'success';
$message = 'query success';
}
}
// Close database connection
mysqli_close($db_connection);
}
// Prepare data
$data = array(
"result" => $result,
"message" => $message,
"data" => $mysql_data
);
// Convert PHP array to JSON array
$json_data = json_encode($data);
print $json_data;
?>
Am I missing something please help if you found any fault in my code.
because you are using post method in your form:
<form method="POST" id="add_user" name='reg' >
and trying to receive params via get:
isset($_GET['name'])
just use post method everywhere
and also in jQuery you need to set:
type: "POST"
I am trying to pass a MySQL query into a variable but it is not storing it correctly. I am wanting the query result to be stored as a string.
Here is my attempt:
$authorid = $db->query("SELECT Author_ID FROM Authors WHERE Author_Name = '$author'");
The query works correctly in PHPMyAdmin so I know it is returning the correct information but I am unsure if this is the correct way to store it.
I am trying to use it for this:
$authoredquery = $db->query("SELECT Author_ID, Article_ID
FROM Articles_Authored
WHERE Author_ID = '$authorid' AND Article_ID ='$articleid'");
All of the query is spelled correctly. I was under the impression that this stored the query result as a string....
Here is a portion of the php code that runs after a form is submitted:
$dbHost = "localhost";
$dbUsername = "admin";
$dbPassword = "qegc0Qfs";
$dbName = "webdb";
// Create connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
} else {
// Post PHP variables
$journal = $_POST['journal_radio'];
$article_name = $_POST['article_name'];
$author1 = $_POST['author1_name'];
$author1uni = $_POST['author1_university'];
$author2 = $_POST['author2_name'];
$author2uni = $_POST['author2_university'];
$author3 = $_POST['author3_name'];
$author3uni = $_POST['author3_university'];
$author4 = $_POST['author4_name'];
$author4uni = $_POST['author4_university'];
$author5 = $_POST['author5_name'];
$author5uni = $_POST['author5_university'];
$author6 = $_POST['author6_name'];
$author6uni = $_POST['author6_university'];
$year = $_POST['year'];
$security = $_POST['is_security'];
function authorinfoinsert($author, $number, $authoruni, $articleid, $article, $db){
//check if Author already exists
$authorquery = $db->query("SELECT Author_Name FROM Authors WHERE Author_Name = '$author'");
if($authorquery->num_rows != 0) {
echo '<a href="> New Input </a><br />';
echo 'Author ' . $number . ' - ' . $author . ' - already present<br />';
} else {
//insert author if doesnt exist
$authorinsert = "INSERT INTO Authors (Author_Name) VALUES ('$author')";
if ($db->query($authorinsert) === TRUE) {
echo 'Author ' . $number . ' - ' . $author . ' - created successfully.<br />';
} else {
echo 'Error: ' . $authorinsert . '<br />' . $db->error . '<br />';
}
}
// store Author Author_ID value
$authorid = $db->query("SELECT Author_ID FROM Authors WHERE Author_Name = '$author'");
//check if Author University exists
$authoruniquery = $db->query("SELECT University_Name FROM University WHERE University_Name = '$authoruni'");
if($authoruniquery->num_rows != 0) {
echo ' New Input <br />';
echo 'Author ' . $number . ' University already present <br />';
} else {
//insert university if doesnt exist
$uniinsert = "INSERT INTO University (University_Name) VALUES ('$authoruni')";
if ($db->query($uniinsert) === TRUE) {
echo 'Author ' . $number . ' University - ' . $authoruni . ' - created successfully.<br />';
} else {
echo 'Error: ' . $uniinsert . "<br>" . $db->error . '<br />';
}
}
// store Author University_ID value
$authoruniid = $db->query("SELECT University_ID FROM University WHERE University_Name = '$authoruni'");
echo $authoruniid;
//Enter Author and Article in Articles_Authored
$authoredquery = $db->query("SELECT Author_ID, Article_ID FROM Articles_Authored WHERE Author_ID = '$authorid' AND Article_ID ='$articleid'");
if($authoredquery->num_rows != 0) {
echo ' New Input <br />';
echo 'Article Authored entry for Author ' . $number . ' - ' . $author . ' - already present<br />';
} else {
$articlesauthoredinsert = "INSERT INTO Articles_Authored (Article_ID, Author_ID, Name_Authored_As) VALUES ('$articleid','$authorid','$author')";
if ($db->query($articlesauthoredinsert) === TRUE) {
echo 'Article Authored - Author ' . $number . ' - created successfully <br />';
} else {
echo 'Error: ' . $articlesauthoredinsert . "<br>" . $db->error . '<br />';
}
}
//Enter Author University instance in Author_University
$authoruniinsert = "INSERT INTO Author_University (Article_ID, Author_ID, University_ID) VALUES ('$articleid','$authorid','$authoruniid')";
if ($db->query($authoruniinsert) === TRUE) {
echo 'University instance for Author ' . $number . ' created successfully<br />';
} else {
echo 'Error: ' . $authoruniinsert . "<br>" . $db->error . '<br />';
}
}
And I pass the args to the function like this:
authorinfoinsert($author1, 1, $author1uni, $articleid, $article, $db);
Here is all of the code if that helps. Sorry I know its a lot:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Input Form - Research Ranker</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#article_name" ).autocomplete({
</head>
<body>
<?PHP
if(!isset($_POST['submit'])){
print '
<div class="container-fluid ui-widget">
<form class="form-horizontal" method="post" action="test.php" onsubmit="return confirm("Is all of your data correct?");">
<fieldset>
<!-- Article Input -->
<legend>Article Input</legend>
<!-- Journal Radio Buttons (value is journal ISSN)-->
<div class="form-group">
<label class="col-md-4 control-label" for="journal_radio">Journal</label>
<div class="col-md-4">
<div class="radio">
<label for="journal_radio-0">
<input type="radio" name="journal_radio" id="journal_radio-0" value="2162-9730" checked="checked">
MIS Quarterly
</label>
</div>
<div class="radio">
<label for="journal_radio-1">
<input type="radio" name="journal_radio" id="journal_radio-1" value="1047-7047">
Information Systems Research
</label>
</div>
<div class="radio">
<label for="journal_radio-2">
<input type="radio" name="journal_radio" id="journal_radio-2" value="0742-1222">
Journal of Management Information Systems
</label>
</div>
<div class="radio">
<label for="journal_radio-3">
<input type="radio" name="journal_radio" id="journal_radio-3" value="1536-9323">
Journal of the Association for Information Systems
</label>
</div>
<div class="radio">
<label for="journal_radio-4">
<input type="radio" name="journal_radio" id="journal_radio-4" value="1476-9344">
European Journal of Information Systems
</label>
</div>
<div class="radio">
<label for="journal_radio-5">
<input type="radio" name="journal_radio" id="journal_radio-5" value="1365-2575">
Information Systems Journal
</label>
</div>
<div class="radio">
<label for="journal_radio-6">
<input type="radio" name="journal_radio" id="journal_radio-6" value="0963-8687">
Journal of Strategic Information Systems
</label>
</div>
<div class="radio">
<label for="journal_radio-7">
<input type="radio" name="journal_radio" id="journal_radio-7" value="0268-3962">
Journal of Information Technology
</label>
</div>
<div class="radio">
<label for="journal_radio-8">
<input type="radio" name="journal_radio" id="journal_radio-8" value="0167-9236">
Decision Support Systems
</label>
</div>
<div class="radio">
<label for="journal_radio-9">
<input type="radio" name="journal_radio" id="journal_radio-9" value="0378-7206">
Information and Management
</label>
</div>
</div>
</div>
<!-- Article Name Input-->
<div class="form-group">
<label class="col-md-4 control-label" for="article_name">Article Name:</label>
<div class="col-md-5">
<input id="article_name" name="article_name" type="text" placeholder="Article Name" class="form-control input-md" required="">
</div>
</div>
<!-- Author 1-->
<div class="form-group">
<label class="col-md-4 control-label" for="author1_name">Author 1:</label>
<div class="col-md-4">
<input id="author1_name" name="author1_name" type="text" placeholder="Author Name" class="form-control input-md" required="">
</div>
</div>
<!-- Author 1 University -->
<div class="form-group">
<label class="col-md-4 control-label" for="author1_university">University:</label>
<div class="col-md-4">
<input id="author1_university" name="author1_university" type="text" placeholder="Author University" class="form-control input-md" required="">
</div>
</div>
<!-- Author 2-->
<div class="form-group">
<label class="col-md-4 control-label" for="author2_name">Author 2:</label>
<div class="col-md-4">
<input id="author2_name" name="author2_name" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 2 University-->
<div class="form-group">
<label class="col-md-4 control-label" for="author2_university">University:</label>
<div class="col-md-4">
<input id="author2_university" name="author2_university" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 3-->
<div class="form-group">
<label class="col-md-4 control-label" for="author3_name">Author 3:</label>
<div class="col-md-4">
<input id="author3_name" name="author3_name" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 3 University-->
<div class="form-group">
<label class="col-md-4 control-label" for="author3_university">University:</label>
<div class="col-md-4">
<input id="author3_university" name="author3_university" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 4-->
<div class="form-group">
<label class="col-md-4 control-label" for="author4_name">Author 4: </label>
<div class="col-md-4">
<input id="author4_name" name="author4_name" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 4 University-->
<div class="form-group">
<label class="col-md-4 control-label" for="author4_university">University:</label>
<div class="col-md-4">
<input id="author4_university" name="author4_university" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 5-->
<div class="form-group">
<label class="col-md-4 control-label" for="author5_name">Author 5:</label>
<div class="col-md-4">
<input id="author5_name" name="author5_name" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 5 University-->
<div class="form-group">
<label class="col-md-4 control-label" for="author5_university">University:</label>
<div class="col-md-4">
<input id="author5_university" name="author5_university" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 6-->
<div class="form-group">
<label class="col-md-4 control-label" for="author6_name">Author 6:</label>
<div class="col-md-4">
<input id="author6_name" name="author6_name" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 6 University-->
<div class="form-group">
<label class="col-md-4 control-label" for="author6_university">University:</label>
<div class="col-md-4">
<input id="author6_university" name="author6_university" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Select Year Published -->
<div class="form-group">
<label class="col-md-4 control-label" for="year">Year Published</label>
<div class="col-md-4">
<select id="year" name="year" class="form-control">
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
</select>
</div>
</div>
<!-- Is Security Checkbox -->
<div class="form-group">
<label class="col-md-4 control-label" for="is_security"></label>
<div class="col-md-4">
<label class="checkbox-inline" for="is_security-0">
<input type="checkbox" name="is_security" id="is_security" value="1">
Security Related
</label>
</div>
</div>
<!-- Submit Form Button -->
<div class="form-group">
<div class="col-md-4 control-label">
<button id="submit" name="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</fieldset>
</form>
</div>';
} else {
$dbHost = "localhost";
$dbUsername = "admin";
$dbPassword = "qegc0Qfs";
$dbName = "webdb";
// Create connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
} else {
// Post PHP variables
$journal = $_POST['journal_radio'];
$article_name = $_POST['article_name'];
$author1 = $_POST['author1_name'];
$author1uni = $_POST['author1_university'];
$author2 = $_POST['author2_name'];
$author2uni = $_POST['author2_university'];
$author3 = $_POST['author3_name'];
$author3uni = $_POST['author3_university'];
$author4 = $_POST['author4_name'];
$author4uni = $_POST['author4_university'];
$author5 = $_POST['author5_name'];
$author5uni = $_POST['author5_university'];
$author6 = $_POST['author6_name'];
$author6uni = $_POST['author6_university'];
$year = $_POST['year'];
$security = $_POST['is_security'];
function authorinfoinsert($author, $number, $authoruni, $articleid, $article, $db){
//check if Author already exists
$authorquery = $db->query("SELECT Author_Name FROM Authors WHERE Author_Name = '$author'");
if($authorquery->num_rows != 0) {
echo ' New Input <br />';
echo 'Author ' . $number . ' - ' . $author . ' - already present<br />';
} else {
//insert author if doesnt exist
$authorinsert = "INSERT INTO Authors (Author_Name) VALUES ('$author')";
if ($db->query($authorinsert) === TRUE) {
echo 'Author ' . $number . ' - ' . $author . ' - created successfully.<br />';
} else {
echo 'Error: ' . $authorinsert . '<br />' . $db->error . '<br />';
}
}
// store Author Author_ID value
$authorid = $db->query("SELECT Author_ID FROM Authors WHERE Author_Name = '$author'");
//check if Author University exists
$authoruniquery = $db->query("SELECT University_Name FROM University WHERE University_Name = '$authoruni'");
if($authoruniquery->num_rows != 0) {
echo ' New Input <br />';
echo 'Author ' . $number . ' University already present <br />';
} else {
//insert university if doesnt exist
$uniinsert = "INSERT INTO University (University_Name) VALUES ('$authoruni')";
if ($db->query($uniinsert) === TRUE) {
echo 'Author ' . $number . ' University - ' . $authoruni . ' - created successfully.<br />';
} else {
echo 'Error: ' . $uniinsert . "<br>" . $db->error . '<br />';
}
}
// store Author University_ID value
$authoruniid = $db->query("SELECT University_ID FROM University WHERE University_Name = '$authoruni'");
echo $authoruniid;
//Enter Author and Article in Articles_Authored
$authoredquery = $db->query("SELECT Author_ID, Article_ID FROM Articles_Authored WHERE Author_ID = '$authorid' AND Article_ID ='$articleid'");
if($authoredquery->num_rows != 0) {
echo ' New Input <br />';
echo 'Article Authored entry for Author ' . $number . ' - ' . $author . ' - already present<br />';
} else {
$articlesauthoredinsert = "INSERT INTO Articles_Authored (Article_ID, Author_ID, Name_Authored_As) VALUES ('$articleid','$authorid','$author')";
if ($db->query($articlesauthoredinsert) === TRUE) {
echo 'Article Authored - Author ' . $number . ' - created successfully <br />';
} else {
echo 'Error: ' . $articlesauthoredinsert . "<br>" . $db->error . '<br />';
}
}
//Enter Author University instance in Author_University
$authoruniinsert = "INSERT INTO Author_University (Article_ID, Author_ID, University_ID) VALUES ('$articleid','$authorid','$authoruniid')";
if ($db->query($authoruniinsert) === TRUE) {
echo 'University instance for Author ' . $number . ' created successfully<br />';
} else {
echo 'Error: ' . $authoruniinsert . "<br>" . $db->error . '<br />';
}
}
//check if article exist
$articlequery = $db->query("SELECT Article_Title, ISSN FROM Articles WHERE Article_Title = '$article_name' AND ISSN = '$journal'");
if($articlequery->num_rows != 0) {
echo ' New Input <br />';
echo "<script type= 'text/javascript'>alert('Article Already Present');</script>";
} else {
//insert article if doesn't exist
$articleinsert = "INSERT INTO Articles (ISSN, Year_Published, Is_Security, Article_Title)
VALUES ('$journal','$year','$security','$article_name')";
if ($db->query($articleinsert) === TRUE) {
echo 'New Article - ' . $article_name . ' - created successfully<br />';
} else {
echo 'Error: ' . $articleinsert . "<br>" . $db->error . '<br />';
}
// store Article_ID value
$articleid = $db->query("SELECT Article_ID FROM Articles WHERE Article_Title = '$article_name' AND ISSN = '$journal'");
//insert author 1 info
authorinfoinsert($author1, 1, $author1uni, $articleid, $article, $db);
//check if Author 2 has input
if (isset($author2)){
authorinfoinsert($author2, 2, $author2uni, $articleid, $article, $db);
}
//check if Author 3 has input
if (isset($author3)){
authorinfoinsert($author3, 3, $author3uni, $articleid, $article, $db);
}
//check if Author 4 has input
if (isset($author4)){
authorinfoinsert($author4, 4, $author4uni, $articleid, $article, $db);
}
//check if Author 5 has input
if (isset($author5)){
authorinfoinsert($author5, 5, $author5uni, $articleid, $article, $db);
}
//check if Author 6 has input
if (isset($author6)){
authorinfoinsert($author6, 6, $author6uni, $articleid, $article, $db);
} else{
$db->close();
}
}
}
}
?>
</body>
</html>
Okay so from what you've told me, you're trying to use the object as a string, which is why it's not working.
$authorid is just $db->query(); which returns an object that you need to do something with. In this case, you need to grab the results from it like so:
$result = $db->query("SELECT Author_ID FROM Authors WHERE Author_Name = '$author'");
$row = $result->fetch_assoc();
$authorid = $row['Author_ID'];
Try that :)
My best guess is that it's returning an array rather than a string, which is why "echo" and "print" won't work.
You might try print_r($authoruniid) to see the structure of the array, then access your data through there.
I think you need to use mysqli fetch_assoc() to getting result of query
you must change your code to:
$dbHost = "localhost";
$dbUsername = "admin";
$dbPassword = "qegc0Qfs";
$dbName = "webdb";
// Create connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
} else {
// Post PHP variables
$journal = $_POST['journal_radio'];
$article_name = $_POST['article_name'];
$author1 = $_POST['author1_name'];
$author1uni = $_POST['author1_university'];
$author2 = $_POST['author2_name'];
$author2uni = $_POST['author2_university'];
$author3 = $_POST['author3_name'];
$author3uni = $_POST['author3_university'];
$author4 = $_POST['author4_name'];
$author4uni = $_POST['author4_university'];
$author5 = $_POST['author5_name'];
$author5uni = $_POST['author5_university'];
$author6 = $_POST['author6_name'];
$author6uni = $_POST['author6_university'];
$year = $_POST['year'];
$security = $_POST['is_security'];
function authorinfoinsert($author, $number, $authoruni, $articleid, $article, $db) {
//check if Author already exists
$authorquery = $db->query("SELECT Author_Name FROM Authors WHERE Author_Name = '$author'");
if ($authorquery->num_rows != 0) {
echo ' New Input <br />';
echo 'Author ' . $number . ' - ' . $author . ' - already present<br />';
} else {
//insert author if doesnt exist
$authorinsert = "INSERT INTO Authors (Author_Name) VALUES ('$author')";
if ($db->query($authorinsert) === TRUE) {
echo 'Author ' . $number . ' - ' . $author . ' - created successfully.<br />';
} else {
echo 'Error: ' . $authorinsert . '<br />' . $db->error . '<br />';
}
}
// store Author Author_ID value
$authorid = $db->query("SELECT Author_ID FROM Authors WHERE Author_Name = '$author'");
while ($row = $authorid->fetch_assoc()) {
/
echo $row['Author_ID'];
}
//check if Author University exists
$authoruniquery = $db->query("SELECT University_Name FROM University WHERE University_Name = '$authoruni'");
if ($authoruniquery->num_rows != 0) {
echo ' New Input <br />';
echo 'Author ' . $number . ' University already present <br />';
} else {
//insert university if doesnt exist
$uniinsert = "INSERT INTO University (University_Name) VALUES ('$authoruni')";
if ($db->query($uniinsert) === TRUE) {
echo 'Author ' . $number . ' University - ' . $authoruni . ' - created successfully.<br />';
} else {
echo 'Error: ' . $uniinsert . "<br>" . $db->error . '<br />';
}
}
// store Author University_ID value
$authoruniid = $db->query("SELECT University_ID FROM University WHERE University_Name = '$authoruni'");
while ($row = $authorid->fetch_assoc()) {/// better use this in a while loop to getting all records
echo $row['University_ID'];
}
//Enter Author and Article in Articles_Authored
$authoredquery = $db->query("SELECT Author_ID, Article_ID FROM Articles_Authored WHERE Author_ID = '$authorid' AND Article_ID ='$articleid'");
if ($authoredquery->num_rows != 0) {
echo ' New Input <br />';
echo 'Article Authored entry for Author ' . $number . ' - ' . $author . ' - already present<br />';
} else {
$articlesauthoredinsert = "INSERT INTO Articles_Authored (Article_ID, Author_ID, Name_Authored_As) VALUES ('$articleid','$authorid','$author')";
if ($db->query($articlesauthoredinsert) === TRUE) {
echo 'Article Authored - Author ' . $number . ' - created successfully <br />';
} else {
echo 'Error: ' . $articlesauthoredinsert . "<br>" . $db->error . '<br />';
}
}
//Enter Author University instance in Author_University
$authoruniinsert = "INSERT INTO Author_University (Article_ID, Author_ID, University_ID) VALUES ('$articleid','$authorid','$authoruniid')";
if ($db->query($authoruniinsert) === TRUE) {
echo 'University instance for Author ' . $number . ' created successfully<br />';
} else {
echo 'Error: ' . $authoruniinsert . "<br>" . $db->error . '<br />';
}
}
for more information about mysql_fetch_assoc() click here
I'm having a difficult time trying to make AJAX edit changes when the form is submitted on the same page and make the changes appear, but the image throws error: Undefined index: image in update.php on line 22 and 24. It refuses to pass the values.
Form (editForm.php):
<div class="modal-content editDisplay">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="editModalLabel">Edit Item</h4>
</div>
<form class="editForm" method="post" enctype="multipart/form-data">
<div class="modal-body">
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" name="Product_Name" placeholder="Name" value="<?php echo $product ?>">
<input type="hidden" name="oldProduct" value="<?php echo $oldProduct ?>">
</div>
<div class="form-group">
<label for="inputDescription">Description</label>
<textarea class="form-control" id="inputDescription" name="Description" placeholder="Description"><?php echo $description ?></textarea>
</div>
<div class="form-group">
<label for="inputPrice">Price</label>
<input type="text" class="form-control" id="inputPrice" name="Price" placeholder="Price" value="<?php echo $price ?>">
</div>
<div class="form-group">
<label for="inputQuantity">Quantity</label>
<input type="number" class="form-control" id="inputQuantity" name="Quantity" placeholder="Quantity" value="<?php echo $quantity ?>">
</div>
<div class="form-group">
<label for="inputSalePrice">Sale Price</label>
<input type="text" class="form-control" id="inputSalePrice" name="Sale_Price" placeholder="Sale Price" value="<?php echo $salePrice ?>">
</div>
<div class="form-group">
<label for="inputImage">Image Upload</label><br>
<fieldset class="file-fieldset">
<span class="btn btn-default btn-file">
<span class="glyphicon glyphicon-upload"></span> Browse Browse <input name="image" type="file" id="inputImage"/><br>
</span>
<input type="hidden" name="prevPicture" value="<?php $image ?>"/>
<span style="margin-left:8px;" value=""><?php echo $image ?></span>
</fieldset>
</div>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-default">Reset</button>
<button type="submit" class="btn btn-primary" id="saveButton" name="update">Save Changes</button>
</div>
</form>
</div>
PHP (update.php):
<?php
include('connection.php');
include('LIB_project1.php');
$productName = $_POST['Product_Name'];
$productDescription = $_POST['Description'];
$price = $_POST['Price'];
$quantity = $_POST['Quantity'];
$salePrice = $_POST['Sale_Price'];
$oldImage = $_POST['prevPicture'];
$oldProduct = $_POST['oldProduct'];
//$productName = 'Jaime';
//$productDescription = 'This is crazy';
//$price = '0';
//$quantity = '12234';
//$salePrice = '0';
//$oldImage = $_POST['prevPicture'];
//$oldProduct = $_POST['oldProduct'];
$imageName= $_FILES['image']['name']; //TODO line 22
echo ' The image is '.$imageName;
$image_temp = $_FILES['image']['tmp_name']; // line 24
echo 'Product name is: '.$productName;
//$productName = 'Dodo Square';
//$productDescription = 'Flower on a Bee. Such Beauty!';
//$price = 9;
//$quantity = 8;
//$salePrice = 230;
//$newImage = '038.jpg';
//$oldProduct = 'Times Square';
//working under the assumption that the image already exist in the database
$targetDirectory = 'productImages';
$files = scandir($targetDirectory,1);
//code passed
for($i=0; $i<sizeof($files); $i++)
{
if($oldImage==$files[$i])
{
unlink('productImages/'.$oldImage);
}
}
$target = "productImages";
//add the image to the directory
$target = $target.'/'.$imageName;
move_uploaded_file($image_temp,$target);
updateProduct($conn,'product',':productName', ':productDescription', ':price', ':quantity', ':imageName', ':salePrice', 'Product_Name', 'Description', 'Price', 'Quantity', 'Image_Name', 'Sale_Price', $productName, $productDescription, $price, $quantity,$imageName, $salePrice, $oldProduct, ':oldProduct');
//header('location:admin.php');
?>
updateProduct(...)
/*
* This is a function to update Product
*
*/
function updateProduct(PDO $connection,$table,$bindProductName, $bindProductDescription, $bindPrice, $bindQuantity, $bindImageName, $bindSalePrice,$productNameColumn, $productDescriptionColumn, $priceColumn, $quantityColumn, $imageNameColumn, $salePriceColumn, $productName, $productDescription, $price, $quantity, $imageName, $salePrice, $oldProduct, $bindOldProduct)
{
$result = false;
$sql = 'UPDATE ' . $table . ' SET ' . $productNameColumn . ' = ' . $bindProductName . ',' . $productDescriptionColumn . ' = ' . $bindProductDescription . ',' . $priceColumn . ' = ' . $bindPrice . ',' . $quantityColumn . ' = ' .
$bindQuantity . ',' . $salePriceColumn . ' = ' . $bindSalePrice . ',' . $imageNameColumn . ' = ' . $bindImageName . ' WHERE ' . $productNameColumn . ' = ' . $bindOldProduct;
$smtp = $connection->prepare($sql);
$smtp -> bindParam($bindProductName, $productName);
$smtp -> bindParam($bindProductDescription, $productDescription);
$smtp -> bindParam($bindPrice, $price);
$smtp -> bindParam($bindQuantity, $quantity);
$smtp -> bindParam($bindImageName, $imageName);
$smtp -> bindParam($bindSalePrice, $salePrice);
$smtp -> bindParam($bindOldProduct, $oldProduct);
if($smtp->execute() )
{
$result = true;
}
return $result;
}
AJAX (display edited changes) Problem: Need to submit those edited changes
$(document).ready(function()
{
//the user click save edit
$(".edit").on("submit",function(e)
{
e.preventDefault();
$.ajax({
type:"POST",
url:'update.php', //I will put project id here as well
data:$(".editForm").serialize(),
success:function(smsg)
{
alert(smsg);
//update the number of items the user has in their shopping cart
$.get('admin.php',function(data){
$('#refresh').load("admin.php #refresh");
//alert('success');
});
}
});
});
});
var inputImage = $("#inputImage");
var fd = new FormData(document.getElementById("editform"));
fd.append("image", inputImage);
$.ajax({
url: "",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response) {
}
});
By default the image is not being added to the form during your post, you need to get the entire form and append the image to it before sending it. I did this for asp.net, it should work for php too though.
Add a series of tests to your PHP and you'll figure it out quite quickly yourself.
You are already alerting the response sent by the PHP ajax processor file:
alert(smsg);
So, use that to troubleshoot/diagnose where things are going wrong.
First test can be to put a "I got here" message at the top of the PHP file -- at least then you know the ajax itself is working. So, modify the top of update.php to read:
<?php
echo "Got to here";
die();
If that alerts, then get rid of the die() and echo out a few more such tests at various places in the file. Use this method to narrow down the location (in the PHP file) of the error.
Echo out the data received so you know what is coming in. Modify update.php to be:
$productName = $_POST['Product_Name'];
$productDescription = $_POST['Description'];
$price = $_POST['Price'];
$quantity = $_POST['Quantity'];
$salePrice = $_POST['Sale_Price'];
$oldImage = $_POST['prevPicture'];
$oldProduct = $_POST['oldProduct'];
echo "$productName: " .$productName. " -- $productDescription: " .$productDescription. " - etc etc etc";
die();
I'm sure you'll find the error pretty quick -- certainly quicker than composing a detailed SO question and awaiting the answer...
Good luck!
Maybe it's because the image never send to server via ajax, so $_FILES have nothing under 'image' index.
Take a look at how to do file upload using jquery serialization
or consider to use FormData object.
Change <input name="image" type="file" id="inputImage"/ to <input name="image" type="file" id="inputImage"/>
I am trying to create a custom contact form page for my Wordpress theme. However on my way to finishing my codes the error message on my page won't show up.
Also, I am running on a localhost computer for testing this custom page and it seems it won't send my message to the ADMIN EMAIL that was set on my Wordpress Installation.
Here's the snippet on my WP Custom Contact Form:
<?php
/* Template Name: Contact Page */
?>
<?php
// Function for email address validation
function isEmail($verify_email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$verify_email));
}
$error_name = false;
$error_email = false;
$error_subject = false;
$error_message = false;
if (isset($_POST['submit'])) {
// Initialize the variables
$contact_name = '';
$contact_email = '';
$contact_subject = '';
$contact_message = '';
// Get the name
if (trim($_POST['contact_name']) === '') {
$error_name = true;
} else {
$name = trim($_POST['contact_name']);
}
// Get the email
if (trim($_POST['contact_email']) === '' || !isEmail($_POST['contact_email'])) {
$error_email = true;
} else {
$email = trim($_POST['contact_email']);
}
// Check if we have errors
if (!$error_name && !$error_email && !$error_subject && !$error_message) {
// Get the receiver email from the WP admin panel
$receiver_email = get_option('admin_email');
$subject = "Message from $contact_name";
$body = "You have a new quote request from $contact_name. Project details:" . PHP_EOL . PHP_EOL;
$body .= PHP_EOL . PHP_EOL;
$headers = "From: $contact_email" . PHP_EOL;
$headers .= "Reply-To: $contact_email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
// If all is good, we send the email
if (mail($receiver_email, $subject, $body, $headers)) {
$email_sent = true;
} else {
$email_sent_error = true;
}
}
}
?>
<?php get_header(); ?>
<!-- BLOG AREA -->
<section>
<hr class="no-margin" />
<div class="blog-container section-content">
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="box-layer custom-padding">
<div class="align-center">
<h2>We want to hear from you!</h2>
<p>If you are seeking to contact us, please fill up the form below. If you want to advertise or be partner with us just inform us on the message box below. </p>
<p>Thank you so much for your support!
<br/>We really appreciate!</p>
<?php if (isset($email_sent) && $email_sent == true) : ?>
<h2>Success!</h2>
<p>You have successfully sent the quote request. I'll get back to you as soon as possible.</p>
<?php elseif (isset($email_sent_error) && $email_sent_error == true) : ?>
<h2>There was an error!</h2>
<p>Unfortunately, there was an error while trying to send the email. Please try again.</p>
<?php else : ?>
<form action="<?php the_permalink(); ?>" method="POST" class="general-form" novalidate>
<p <?php if ($error_name) echo 'class="error"'; ?>><input name="contact_name" id="contact_name" class="form-control" placeholder="Your Name.." type="text" value="<?php if (isset($_POST['contact_name'])) echo $_POST['contact_name']; ?>" /></p>
<p <?php if ($error_email) echo 'class="error"'; ?>><input name="contact_email" id="contact_email" class="form-control" placeholder="Your Email.." type="email" value="<?php if (isset($_POST['contact_email'])) echo $_POST['contact_email']; ?>" /></p>
<p <?php if ($error_subject) echo 'class="error"'; ?>><input name="contact_subject" id="contact_subject" class="form-control" placeholder="Your Subject.." type="text" value="<?php if (isset($_POST['contact_subject'])) echo $_POST['contact_subject']; ?>"/></p>
<p <?php if ($error_message) echo 'class="error"'; ?>><textarea name="contact_message" id="contact_message" class="form-control" placeholder="Write your comment here.." rows="4" cols="100"><?php if (isset($_POST['contact_message'])) echo $_POST['contact_message']; ?></textarea></p>
<input class="btn btn-primary no-border" name="submit" type="submit" id="submit" value="Send Message">
</form>
<?php endif; ?>
</div>
</div>
<!-- RELATED ARTICLE AREA -->
</div>
<aside>
<!-- SIDEBAR AREA -->
<div class="col-md-3 col-md-offset-1 margin-sidebar">
<?php get_sidebar(); ?>
</div>
</aside>
</section>
<?php get_footer(); ?>
Any idea? or Is there a way you can correct my code if you see some errors?
To get you started
Make sure WP_DEBUG is set to true on your wp-config.php file.
You can get the last errors from mail() (answered here)
Use wordpress' functions if available, in this case wp_mail is at your disposal.
There are wordpress plugins such as gravity forms or contact form 7 which can accomplish the task.
Use filters and actions.
Had to post as an answer, couldn't comment yet.
HTH
If you would like to get the admin email address, you have to do it with:
$bloginfo = get_bloginfo( 'admin_email' );
get_option('admin_email') is only works when you save anything to that in the Theme Setup, probably it is empty now.
By the way, you can find many of professional, ready to use solution, like WordPress Contact Form Slider
<?php
/*
Plugin Name:Contact Form Plugin
Plugin URI: http://example.com
Description: Simple non-bloated WordPress Contact Form
Version: 1.0
Author: Agbonghama Collins
Author URI: http://w3guy.com
*/
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
define( 'MY_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
include( MY_PLUGIN_PATH . 'form/form.php');
include( MY_PLUGIN_PATH . 'admin/admin-menu.php');
include( MY_PLUGIN_PATH . 'database/table.php');
?>
Form.php
====================
<?php
function form()
{
echo '<form action="'.esc_url($_SERVER['REQUEST_URI']).'" method="post">';
echo '<p>';
echo 'Your First Name:';
echo '<br/>';
echo '<input type="text" name="fname" required/>';
echo '<br/>';
echo 'your Email-Id:';
echo '<br/>';
echo '<input type="email" name="email" required/>';
echo '<br/>';
echo 'Your Subject:';
echo '<br/>';
echo '<input type="text" name="subject" required/>';
echo '<br/>';
echo 'Your Message:';
echo '<br/>';
echo '<textarea name="message" cols="30" rows="4" required></textarea>';
echo '<br/>';
echo '<input type="submit" name="submit" value="Submit"/>';
echo '</form>';
}
if(isset($_REQUEST['submit']))
{
$name = $_POST['fname'];
$email = $_POST['email'];
$subject=$_POST['subject'];
$msg=$_POST['message'];
function insertuser($name,$email,$msg,$subject){
global $wpdb;
$table_name = $wpdb->prefix . "contactinfo";
$wpdb->insert($table_name, array('name' => $name, 'email' => $email , 'message'=> $msg , 'subject' => $subject) );
}
insertuser($name,$email,$msg,$subject);
}
function shortcode()
{
form();
}
add_shortcode('contact-form','shortcode');
?>
table.php
===================
<?php
global $wpdb;
$table_name = $wpdb->prefix . "contactinfo";
$charset_collate = $wpdb->get_charset_collate();
if( $wpdb->get_var ('SHOW TABLE LINK' .$table_name) != $table_name )
{
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
email varchar(40) NOT NULL,
message text NOT NULL,
subject text NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
?>