Store form data into wordpress database - php

I have created a simple html form to test, how I can insert data in wpdb. I know how to do it in PHP but in wordpress I am getting confused!
global $wpdb;
if (isset($_POST['submit'])) {
$name = $_POST['r1s1']; //Here r1s1 is name of the form control
$email = $_POST['r2s1'];
$contact = $_POST['r3s1'];
$address = $_POST['r5s1'];
if ($name != '' || $email != '') {
$post = $wpdb->insert(
'table', array(
'feild' => $name,
'dev' => $email,
'tenant' => $contact,
'mod' => $address,
), array(
'%s',
'%s',
'%s',
'%s'
)
);
echo $post;
if ($post) {
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
} else {
echo "<br/><br/><span>Insertion Failed...!!</span>";
}
} else {
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
When I click on submit button then it shows message insertion failed...!! ( Message that I am printing via echo). This code is written in template. What I am doing wrong?

global $wpdb;
$wpdb->insert( 'table_name', array( 'field_name' => $_POST['r1s1'], 'field_name' => $_POST['r2s1'],'field_name' => $_POST['r3s1'],'field_name' => $_POST['r4s1']) );
Try This one

You can try below code?
global $wpdb;
$table_name = $wpdb->prefix . "your_table_name";
if (isset($_POST['submit'])) {
$name = $_POST['r1s1']; //Here r1s1 is name of the form control
$email = $_POST['r2s1'];
$contact = $_POST['r3s1'];
$address = $_POST['r5s1'];
$data = array(
'feild' => $name,
'dev' => $email,
'tenant' => $contact,
'mod' => $address
);
if ($name != '' || $email != '') {
$result = $wpdb->insert($table_name, $data);
if ($result) {
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
} else {
echo "<br/><br/><span>Insertion Failed...!!</span>";
}
} else {
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}

Related

Wordpress: I have a custom change email form, how do I send confirmation email

I have the following code in my functions.php to generate a form for users to change their account email from the front end. It works, but I'd like for it to send a the standard confirmation email Wordpress usually does when an email is changed, rather than instantly changing it. Is this simple, or difficult?
function change_email_form() {
$user_id = get_current_user_id();
$user_info = get_userdata($user_id);
$user_email = $user_info->user_email;
?>
<form id="updateemail" action="#updateemail" method="post">
<input id="new_email" type="text" name="new_email" title="new_email" placeholder="<?php echo $user_email; ?>" required>
<button class="submit" type="submit">Update Email</button>
</form>
<?php }
function change_email(){
if(isset($_POST['new_email'])){
$_POST = array_map('stripslashes_deep', $_POST);
$new_email = sanitize_email($_POST['new_email']);
$user_id = get_current_user_id();
$user_info = get_userdata($user_id);
$user_email = $user_info->user_email;
$errors = array();
$current_user = get_user_by('id', $user_id);
// Check for errors
if ( $user_email == $new_email ) {
$errors[] = 'Address unchanged';
}
if ( ! is_email( $new_email ) ) {
$errors[] = 'Address invalid';
}
if ( email_exists( $new_email ) ) {
$errors[] = 'Address unavailable';
}
if(empty($errors)){
$args = array(
'ID' => $user_id,
'user_email' => $new_email,
);
wp_update_user( $args );
send_confirmation_on_profile_email();
echo '<small class="notice">Address updated</small>';
} else {
// Echo Errors
foreach($errors as $error){
echo '<p>';
echo '<small class="notice">';
echo $error;
echo '</small>';
}
}
}
}
function email_form_shortcode(){
change_email();
change_email_form();
}
add_shortcode('changeemail_form', 'email_form_shortcode');

Unable to save submitted data in a MySQL database using PHP

Please may I ask for some assistance on this as I have been trying to fix for days now.It is accepting data when i key in but not appearing in the database when i check.
Here is my code
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["btnSave"])) {
$db = new \dbPlayer\dbPlayer();
$msg = $db->open();
//echo '<script type="text/javascript"> alert("'.$msg.'");</script>';
if ($msg = "true") {
$userIds = $db->getAutoId("U");
$flup = new fileUploader\fileUploader();
$perPhoto = $flup->upload("/hms/files/photos/",$_FILES['perPhoto'], $userIds[1]);
// var_dump($perPhoto);
$handyCam=new \handyCam\handyCam();
if (strpos($perPhoto, 'Error:') === false) {
$dateNow=date("Y-m-d");
$data = array(
'userId' => $userIds[1],
'name' => $_POST['name'],
'studentId' => $_POST['studentId'],
'cellNo' => $_POST['cellNo'],
'gender' => $_POST['gender'],
'dob' => $handyCam->parseAppDate($_POST['dob']),
'passportNo' => $_POST['passportNo'],
'fatherName' => $_POST['fatherName'],
'fatherCellNo' => $_POST['fatherCellNo'],
'perPhoto' => $perPhoto,
'isActive' => 'Y'
);
$result = $db->insertData("studentinfo",$data);
if($result>=0) {
$id =intval($userIds[0])+1;
$query="UPDATE auto_id set number=".$id." where prefix='U';";
$result=$db->update($query)
Use this form to fix your problem
if(isset($_POST["btn-pub"]))
{
$title = $_POST["title"];
$cat = $_POST["postCat"];
$Author = "Imran AKKI";
$ImgName = $_FILES['PostImg']['name'];
$ImgTemp = $_FILES['PostImg']['tmp_name'];
$cont = $_POST["postCon"];
if (empty($title) || empty($cont)){
?>
<div class="alert alert-danger"><?php echo "Please fill in the fields"; ?>
</div>
<?php
}elseif($cont > 10000){
?>
<div class="alert alert-warning"><?php echo "The content of the post is very large"; ?>
</div>
<?php
}else{
$postImage = rand(0,10000)."_".$ImgName;
move_uploaded_file($ImgTemp,"Uploads\postImges\\" .$postImage);
$query = "INSERT INTO posts(PostTitle, PostCat, PostImg, PostContent,PostAuthor) VALUES ('$title','$cat','$postImage','$cont','$Author')";
$res=mysqli_query($conn,$query);
if(isset($res)){
?>
<div class="alert alert-success"><?php echo "The article was added successfully"; ?> </div>
<?php
}else{
?>
<div class="alert alert-danger"><?php echo "An error occurred during addition"; ?> </div>
<?php
}
}
}

my previously store data are automatically deleted while updating a data

I am currently working on a job portal project, where I can store user information,
in my project after registration, user can go there dashboard, and update there remaining form like, education detail and company detail. but after that when user like to update one of the any field in form, it can update that field but it can delete my remaining field, in education detail field or company detail field. What kind of this problem is occurred ?
updateprofile.php
<?php
session_start();
if(empty($_SESSION['id_user']))
{
header("Location: ../index.php");
exit();
}
require_once("../db.php");
if(isset($_POST))
{
//Escape Special Characters
$firstname = $conn->real_escape_string( $_POST['fname']);
$lastname = $conn->real_escape_string($_POST['lname']);
$gender = $conn->real_escape_string($_POST['gender']);
$contactno = $conn->real_escape_string($_POST['contactno']);
$address = $conn->real_escape_string($_POST['address']);
$city = $conn->real_escape_string($_POST['city']);
$state = $conn->real_escape_string($_POST['state']);
$aboutme = $conn->real_escape_string($_POST['aboutme']);
$qualification = $conn->real_escape_string($_POST['qualification']);
$stream = $conn->real_escape_string($_POST['stream']);
$coursetype = $conn->real_escape_string($_POST['coursetype']);
$university = $conn->real_escape_string($_POST['university']);
$passingyear = $conn->real_escape_string($_POST['passingyear']);
$skill = $conn->real_escape_string($_POST['skill']);
$industry = $conn->real_escape_string($_POST['industry']);
$functional_area = $conn->real_escape_string($_POST['functional_area']);
$role = $conn->real_escape_string($_POST['role']);
$is_current_job = $conn->real_escape_string($_POST['is_current_job']);
$startdate = $conn->real_escape_string($_POST['startdate']);
$enddate = $conn->real_escape_string($_POST['enddate']);
$current_compname = $conn->real_escape_string($_POST['current_compname']);
$current_salary = $conn->real_escape_string($_POST['current_salary']);
$designation = $conn->real_escape_string($_POST['designation']);
$notice_period = $conn->real_escape_string($_POST['notice_period']);
$job_desc = $conn->real_escape_string($_POST['job_desc']);
$experience = $conn->real_escape_string($_POST['experience']);
$current_location = $conn->real_escape_string($_POST['current_location']);
$prefer_location = $conn->real_escape_string($_POST['prefer_location']);
$uploadOk = true;
if(is_uploaded_file($_FILES['resume']['tmp_name']))
{
$folder_dir = "../uploads/resume/";
$base = basename($_FILES['resume']['name']);
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
$file = uniqid() . "." . $resumeFileType;
$filename = $folder_dir .$file;
if(file_exists($_FILES['resume']['tmp_name']))
{
if($resumeFileType == "pdf")
{
if($_FILES['resume']['size'] < 500000)
{
// File size is less than 5MB
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
}
else
{
$_SESSION['uploadError'] = "Wrong Size of file. Max Size Allowed : 5MB";
header("Location: edit_profile.php");
exit();
}
}
else
{
$_SESSION['uploadError'] = "Wrong Format of file only pdf Allowed.";
header("Location: edit_profile.php");
exit();
}
}
}
else
{
$uploadOk = false;
}
//Update User Details Query
$sql = "UPDATE user SET firstname='$firstname', lastname='$lastname',gender='$gender',contactno='$contactno', address='$address', city='$city', state='$state',aboutme='$aboutme',qualification='$qualification', stream='$stream',coursetype='$coursetype',university='$university',passingyear='$passingyear',skill='$skill',
industry='$industry',functional_area='$function_area',role='$role',is_current_job='$is_current_job',startdate='$startdate',enddate='$enddate',current_compname='$current_compname',current_salary='$current_salary',designation='$designation',notice_period='$notice_period',job_desc='$job_desc',experience='$experience',current_location='$current_location',prefer_location='$prefer_location'";
if($uploadOk == true)
{
$sql .= ",resume='$file'";
}
$sql .= " WHERE id_user='$_SESSION[id_user]'";
if($conn->query($sql) === TRUE)
{
//If data Updated successfully then redirect to dashboard
header("Location: index.php");
exit();
}
else
{
echo "Error ". $sql . "<br>" . $conn->error;
}
//Close database connection.
$conn->close();
}
else
{
//redirect them back to dashboard page if they didn't click update button
header("Location: edit_profile.php");
exit();
}
image of user table
Using prepared statements and dynamic field mapping to update only those fields which has value in it, here is what your code should look like
<?php
session_start();
if (empty($_SESSION['id_user'])) {
header("Location: ../index.php");
exit();
}
require_once("../db.php");
if (isset($_POST)) {
$uploadOk = true;
if (is_uploaded_file($_FILES['resume']['tmp_name'])) {
$folder_dir = "../uploads/resume/";
$base = basename($_FILES['resume']['name']);
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
$file = uniqid() . "." . $resumeFileType;
$filename = $folder_dir . $file;
if (file_exists($_FILES['resume']['tmp_name'])) {
if ($resumeFileType == "pdf") {
if ($_FILES['resume']['size'] < 500000) {
// File size is less than 5MB
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
} else {
$_SESSION['uploadError'] = "Wrong Size of file. Max Size Allowed : 5MB";
header("Location: edit_profile.php");
exit();
}
} else {
$_SESSION['uploadError'] = "Wrong Format of file only pdf Allowed.";
header("Location: edit_profile.php");
exit();
}
}
} else {
$uploadOk = false;
}
//Update User Details Query
$postf2sqlf = array(
'firstname' => 'firstname',
'lastname' => 'lastname',
'gender' => 'gender',
'contactno' => 'contactno',
'address' => 'address',
'city' => 'city',
'state' => 'state',
'aboutme' => 'aboutme',
'qualification' => 'qualification',
'stream' => 'stream',
'coursetype' => 'coursetype',
'university' => 'university',
'passingyear' => 'passingyear',
'skill' => 'skill',
'industry' => 'industry',
'functional_area' => 'function_area',
'role' => 'role',
'is_current_job' => 'is_current_job',
'startdate' => 'startdate',
'enddate' => 'enddate',
'current_compname' => 'current_compname',
'current_salary' => 'current_salary',
'designation' => 'designation',
'notice_period' => 'notice_period',
'job_desc' => 'job_desc',
'experience' => 'experience',
'current_location' => 'current_location',
'prefer_location' => 'prefer_location'
);
$sql = 'UPDATE `user` SET ';
$skipComma = true;
$params = array('');
foreach ($postf2sqlf as $p => $s) {
if (isset($_POST[$p]) && !empty($_POST[$p])) {
$sql .= ($skipComma ? '' : ',') . '`' . $s . '` = ?';
$params[] = &$_POST[$p];
$params[0] .= 's';
$skipComma = false;
}
}
if ($uploadOk == true) {
$sql .= ",resume=?";
$params = &$file;
$params[0] .= 's';
}
$sql .= " WHERE id_user=?";
$params[0] .= 's';
$params[] = &$_SESSION['id_user'];
$stmt = $db->prepare($sql);
call_user_func_array(array($stmt, 'bind_param'), $params);
$res = $stmt->execute();
if ($stmt->errno == 0) {
//If data Updated successfully then redirect to dashboard
header("Location: index.php");
exit();
} else {
echo "Error " . $sql . "<br>" . $conn->error;
}
//Close database connection.
$conn->close();
} else {
//redirect them back to dashboard page if they didn't click update button
header("Location: edit_profile.php");
exit();
}
Explanation
Created $postf2sqlf array, holding the Form fields as index, and sql field names as value.
Iterating over $postf2sqlf and checking if the index is set and not empty in $_POST, started collecting the parameters passing references in $params to use in a prepared statement to avoid SQL Injection. $params[0] holds the type (s => string) of named parameters, as mysqli_statement::bind_param requires this, and as parameters added, another s is concatenated. (For a strict sql, instead of s, other types could be used upon checking their types but for simplicity's sake I used s)
The reason to collect variables by passing references is because `mysqli_statement::bind_param requires the variables pass by references.
call_user_func_array was used to call mysqli_statement::bind_param with the $params with each index being a different argument.
Finally, $stmt->errno was checked against 0 (0 being no errors), to check that it was actually completed correctly.

I have tried to update data into database in this way but something maybe not working for the first if statement where if ( !empty($_POST) )

I have tried to update data into database in this way but something maybe not working for the first if statement where if ( !empty($_POST) )
Please see this image to understand clearly
<?php require_once '../App/start.php'; if ( !empty($_POST) ) { $id = $_POST['id']; $label = $_POST['label']; $title = $_POST['title']; $slug = $_POST['slug']; $body = $_POST['body']; $updatePage = $db->prepare("UPDATE pages SET label=:label, title=:title,body =:body, slug=:slug, updated=NOW() WHERE id = :id"); $updatePage->execute([ 'id' => $id, 'label' => $label, 'title' => $title, 'body' => $body, 'slug' => $slug ]); header('Location:' . BASE_URL . '/index.php'); } if (!isset($_GET['id'])) { header('Location:' . BASE_URL . '/Admin/list.php'); die(); } $edit = $db->prepare("SELECT id, label, title, body, slug FROM pages WHERE id = :id"); $edit->execute(['id' => $_GET['id']]); $edits = $edit->fetch(PDO::FETCH_ASSOC); require_once VIEW_ROOT . '/Admin/edit.php';
From this code first statement does not working to update data to database
You should test post like following if you want to check method and values.
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset ($_POST ['id']))
Otherwise if ( isset ($_POST ['id']) ) is enough.

Mailchimp false positive on multiple list subscribe

Here is my code which I am using to subscribe users to multiple Mailchimp lists in which they choose and is posted to this file by an ajax request. Here is the code:
So for some reason this returns a success from Mailchimp, but it doesn't actually subscribe to the lists I have entered. I have confirmed the list ids are correct and fields are too.
(I have removed all reference to the actual IDs)
<?php
include 'MailChimp.php';
$mailchimp = new MailChimp('MYAPI_KEY'); //I have my code in here
$newsletter_keyarray = array(
"List one" => "listoneid",
"List two" => "listtwoid",
"List three" => "listthreeid",
"List four" => "listfourid"
);
$any_errors = false;
foreach ($_POST['lists'] as $key => $list) {
if(in_array($list, $newsletter_keyarray)){
$merge_vars_array = array(
'EMAIL' => $_POST['email']
);
if($list == "List one"){
$merge_vars_array['MMERGE1'] = $_POST['fname'];
$merge_vars_array['MMERGE2'] = $_POST['sname'];
$merge_vars_array['MMERGE3'] = $_POST['org'];
}else if($list == "List two"){
$merge_vars_array['FNAME'] = $_POST['fname'];
$merge_vars_array['LNAME'] = $_POST['sname'];
$merge_vars_array['MMERGE4'] = $_POST['job'];
$merge_vars_array['MMERGE5'] = $_POST['org'];
}else if($list == "List three"){
$merge_vars_array['FNAME'] = $_POST['fname'];
$merge_vars_array['LNAME'] = $_POST['sname'];
$merge_vars_array['MMERGE3'] = $_POST['org'];
$merge_vars_array['MMERGE4'] = $_POST['job'];
}else if($list == "List four"){
$merge_vars_array['FNAME'] = $_POST['fname'];
$merge_vars_array['LNAME'] = $_POST['sname'];
$merge_vars_array['MMERGE4'] = $_POST['job'];
$merge_vars_array['MMERGE5'] = $_POST['org'];
}
$mailResults = $mailchimp->call('lists/subscribe', array(
'id' => $newsletter_keyarray[$list],
'email' => array('email' => $_POST['email']),
'merge_vars' => $merge_vars_array,
'double_optin' => false
));
if(isset($mailResults['status']) && $mailResults['status'] == 'error'){
$any_errors = true;
}
}
}
//enter api and userdetails here
$response_array = array();
if($any_errors){
header('Content-type: application/json');
$response_array['status'] = 'error';
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$response_array['message'] = 'The email you have entered is not valid';
}else if(isset($mailResults['error']) && $mailResults['error'] != ""){
$response_array['message'] = $mailResults['error'];
}
echo json_encode($response_array);
}else{
header('Content-type: application/json');
$response_array['status'] = 'success';
echo json_encode($response_array);
}
?>
I have figured it out kind of stupid of me.
The issue was in_array which compares the value rather than the key. So in the end I used array_key_exists

Categories