Unable to save submitted data in a MySQL database using PHP - 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
}
}
}

Related

Can't get a JSON object response to an Ajax request on live server

I have a form which when submitted made request to the server through ajax using php curl. Everything worked perfectly in my local environment(wamp) but when I moved it to live server, it doesn't return any json response.
I can't figure out why it worked in wampserver but not on live server?
php code
<?php
if(isset($_POST['logins']))
{
require_once 'functions.php';
require_once("cons.php");
$licence = $_POST['licence'];
$url = "http://tapi.com/apis/User/api.php?licence=".$licence;
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);
$data = json_decode($response, true);
$msg = $data['message'];
$lic = $data['licence'];
$p = $data['period'];
$u = $data['user'];
$sta = $data['status'];
if($msg == 'Successfully Validated!')
{
//$_SESSION['data'] = array($data, true);
$url = "http://tapi.com/apis/User/api.php?lic=".$lic;
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);
$data = json_decode($response, true);
$msg = $data['message'];
if($msg == 'inserted')
{
$host = $_SERVER['HTTP_HOST'];
$hostaddrs = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$sys_info = php_uname();
$exp_date = encryptIt2($p);
$date = date('Y-m-d');
$ts = encryptIt2($date);
$queryu = "insert into tray(host, license, validity, et)values('$host', '$lic', '$exp_date', '$ts')";
$get = mysqli_query($mysqli,$queryu);
if($get){
echo "yes";
}else{
echo $mysqli -> error;
}
}else{
echo $msg;
}
}
else
{
echo $data['message'];
}
}
?>
jQuery code
function licenceForm()
{
var data = $("#licence-form").serialize();
$.ajax({
type : 'POST',
url : 'ext/b0a012.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#btn-login").html('<img src="assets/img/find.png"
width="26" height="25"> Please wait...');
},
success : function(response)
{
if(response=="yes"){
$(".hideit").hide();
$(".shows").show();
setTimeout('window.location.href = "index.php"; ',2000);
}else{
$("#error").fadeIn(1000,function(){
$("#error").html('<div class="alert alert-danger text center">
<img src="assets/img/attention.png" width="45" height="40" />
<br/> '+response+'</div>');
$("#btn-login").html('Error occured. Try again.');
});
}
}
});
return false;
}
API
if (isset($_GET['licence']) && $_GET['licence']!="") {
$licence = $con->real_escape_string($_GET['licence']);
//$licence = "M7RS-8C46-APSE";
$selec = mysqli_query($con, "SELECT licence, period, users FROM licence_used WHERE licence='$licence'");
$mrow = mysqli_fetch_array($selec);
$count = mysqli_num_rows($selec);
if($count > 0){
$q2 = mysqli_query($con,"select count(licence) use_count FROM licence_used WHERE licence='$licence'");
$get = mysqli_fetch_array($q2);
//query 2
$selec = mysqli_query($con, "SELECT licence,
period, users FROM licence_used WHERE licence='$licence'");
$users = $mrow['users'];
$num = $get['use_count'];
if($num == $users){
$user_arr=array(
"status" => false,
"message" => "Licence key entered has been used up by ".$num." users. Please purchase another licence.",
);
}else{
while($row = mysqli_fetch_array($selec)){
// create array
$user_arr=array(
"status" => true,
"message" => "Successfully Validated!",
"licence" => $mrow['licence'],
"period" => $mrow['period'],
"user" => $mrow['users'],
"mstatus" => $mrow['status']
);
}
}
}else{
$select = mysqli_query($con, "SELECT licence, period, users FROM licence WHERE licence='$licence'");
if(mysqli_num_rows($select) == 0){
$user_arr=array(
"status" => false,
"message" => "Invalid Licence Key Entered. Please contact the software company.",
);
}else{
while($row = mysqli_fetch_array($select)){
// create array
$user_arr=array(
"status" => true,
"message" => "Successfully Validated!",
"licence" => $row['licence'],
"period" => $row['period'],
"user" => $row['users'],
"mstatus" => $row['status']
);
}
}
}
}
header("Content-Type:application/json");
print_r(json_encode($user_arr));
I used postman to test it and it worked. Do anyone know what the issue might be? Thanks.

I made a CodeIgniter forgot password function but its not working

Good day! I'm making a forgot password function on the CodeIgniter PHP framework but it doesn't really work. When I click on the send button no email is send.
Some db info:
db name: kadokado
db table: users
db email column: email
db password column: wachtwoord
db id column: user_id
My controller (Auth.php) :
public function forgot()
{
$this->load->model('User_model'); // load user model
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if($this->form_validation->run() == FALSE) {
$this->load->view('templates/header');
$this->load->view('forgot');
$this->load->view('templates/footer');
}else{
$email = $this->input->post('email');
$clean = $this->security->xss_clean($email);
$userInfo = $this->User_model->getUserInfoByEmail($clean);
if(!$userInfo){
$this->session->set_flashdata('flash_message', 'We hebben dit email adres niet kunnen vinden');
redirect(site_url().'auth/login');
}
if($userInfo->status != true){ //if status is not approved
$this->session->set_flashdata('flash_message', 'Your account is not in approved status');
redirect(site_url().'auth/login');
}
//build token
$token = $this->User_model->insertToken($userInfo->id);
$qstring = $this->base64url_encode($token);
$url = site_url() . 'auth/reset_password/token/' . $qstring;
$link = '' . $url . '';
$message = '';
$message .= '<strong>A password reset has been requested for this email account</strong><br>';
$message .= '<strong>Please click:</strong> ' . $link;
echo $message; //send this through mail
exit;
}
}
public function reset_password()
{
$token = $this->base64url_decode($this->uri->segment(4));
$cleanToken = $this->security->xss_clean($token);
$user_info = $this->User_model->isTokenValid($cleanToken); //either false or array();
if(!$user_info){
$this->session->set_flashdata('flash_message', 'Token is invalid or expired');
redirect(site_url().'auth/login');
}
$data = array(
'voornaam'=> $user_info->voornaam,
'email'=>$user_info->email,
'token'=>base64_encode($token)
);
$this->form_validation->set_rules('wachtwoord', 'Wachtwoord', 'required|min_length[5]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required|matches[wachtwoord]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('templates/header');
$this->load->view('reset_password', $data);
$this->load->view('templates/footer');
}else{
$this->load->library('wachtwoord');
$post = $this->input->post(NULL, TRUE);
$cleanPost = $this->security->xss_clean($post);
$hashed = $this->password->create_hash($cleanPost['wachtwoord']);
$cleanPost['wachtwoord'] = $hashed;
$cleanPost['user_id'] = $user_info->id;
unset($cleanPost['passconf']);
if(!$this->User_model->updatePassword($cleanPost)){
$this->session->set_flashdata('flash_message', 'Er is iets foutgegaan');
}else{
$this->session->set_flashdata('flash_message', 'Uw wachtwoord is geupdate, u kunt nu inloggen');
}
redirect(site_url().'auth/login');
}
}
My model (User_model.php) :
<?php
class User_model extends CI_Model {
public function getUserInfoByEmail($email)
{
$q = $this->db->get_where('users', array('email' => $email), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
return $row;
}else{
error_log('no user found getUserInfo('.$email.')');
return false;
}
}
public function getUserInfo($user_id)
{
$q = $this->db->get_where('users', array('user_id' => $user_id), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
return $row;
}else{
error_log('no user found getUserInfo('.$user_id.')');
return false;
}
}
public function insertToken($user_id)
{
$token = substr(sha1(rand()), 0, 30);
$date = date('Y-m-d');
$string = array(
'token'=> $token,
'user_id'=>$user_id,
'created'=>$date
);
$query = $this->db->insert_string('tokens',$string);
$this->db->query($query);
return $token . $user_id;
}
public function isTokenValid($token)
{
$tkn = substr($token,0,30);
$uid = substr($token,30);
$q = $this->db->get_where('tokens', array(
'tokens.token' => $tkn,
'tokens.user_id' => $uid), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
$created = $row->created;
$createdTS = strtotime($created);
$today = date('Y-m-d');
$todayTS = strtotime($today);
if($createdTS != $todayTS){
return false;
}
$user_info = $this->getUserInfo($row->user_id);
return $user_info;
}else{
return false;
}
}
}
?>
My view (reset_password.php) :
<?php include_once ('templates/header.php'); ?>
<?php include_once ('templates/sidebar2.php'); ?>
<div class="col-lg-4 col-lg-offset-4">
<h2>Reset your password</h2>
<h5>Hello <span><?php echo $voornaam; ?></span>, Voer uw wachtwoord 2x in aub</h5>
<?php
$fattr = array('class' => 'form-signin');
echo form_open(site_url().'auth/reset_password/token/'.$token, $fattr); ?>
<div class="form-group">
<?php echo form_password(array('name'=>'wachtwoord', 'id'=> 'wachtwoord', 'placeholder'=>'Wachtwoord', 'class'=>'form-control', 'value' => set_value('wachtwoord'))); ?>
<?php echo form_error('password') ?>
</div>
<div class="form-group">
<?php echo form_password(array('name'=>'passconf', 'id'=> 'passconf', 'placeholder'=>'Confirm Password', 'class'=>'form-control', 'value'=> set_value('passconf'))); ?>
<?php echo form_error('passconf') ?>
</div>
<?php echo form_hidden('user_id', $user_id);?>
<?php echo form_submit(array('value'=>'Reset Password', 'class'=>'btn btn-lg btn-primary btn-block')); ?>
<?php echo form_close(); ?>
</div>
<div class="clearfix"></div>
<?php include_once ('templates/footer.php'); ?>
I hope someone can help me out!

Store form data into wordpress database

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>";
}
}

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

No output from PHP MySQL function array

I have an array with values declared in a while statement at the end of function fetch_conversation_messages in a backend file for a private message system. However, the array that is revealed is blank (other than the echos and print_rs that I have used for debugging).
I am very new to this forum, PHP and MySQL, so please help me.
Thank you in advance.
// Fetches all of the messages in the given converstion.
function fetch_conversation_messages($conversation_id){
$conversation_id = (int)$conversation_id;
$sql = "SELECT
`conversations_messages`.`message_date`,
`conversations_messages`.`message_text`,
`users`.`user_name`
FROM `conversations_messages`
INNER JOIN `users` ON `conversations_messages`.`user_id` = `users`.`user_id`
WHERE `conversations_messages`.`conversation_id` = {$conversation_id}
ORDER BY `conversations_messages`.`message_date` DESC";
$result = mysql_query($sql);
var_dump($result);
$messages = array();
while (($row = mysql_fetch_assoc($result)) !== false){
$messages[] = array(
'date' => $row['message_date'],
'unread' => $row['message_unread'],
'text' => $row['message_text'],
'user_name' => $row['user_name'],
);
echo mysql_num_rows($result);
var_dump($row);
}
echo count($messages);}
Also, there is a foreach error (written below as a comment on the first answer) in view_conversation.page.inc.php, which is this page:
<?php
$errors = array();
$valid_conversation = (isset($_GET['conversation_id']) && validate_conversation_id($_GET['conversation_id']));
if ($valid_conversation === false){
$errors[] = 'Invalid Conversation ID.';
}
if (isset($_POST['message'])){
if (empty($_POST['message'])){
$errors[] = 'You must enter a message.';
}
if (empty($errors)){
add_conversation_message($_GET['conversation_id'], $_POST['message']);
}
}
if (empty($errors) === false){
foreach ($errors as $error){
}
}
echo $error;
if ($valid_conversation){
/*if (isset($_POST['message'])){
update_conversation_last_view($_GET['conversation_id']);*/
$messages = fetch_conversation_messages($_GET['conversation_id']);
print_r($messages);
/*}else{
$messages = fetch_conversation_messages($_GET['conversation_id']);
update_conversation_last_view($_GET['conversation_id']);
}*/
}
?>
Inbox
Logout
<form action="" method="post">
<p><textarea name="message" rows="10" cols="110"></textarea></p>
<p><input type="submit" value="Add Message" /></p>
</form>
<?php
foreach ($messages as $message){
?>
<?php if ($message['unread']) echo 'unread'; ?>
<p class="name">Username: <?php echo $message['user_name']; ?></p>
<p class="text">Date: <?php echo date('d/m/Y H:i:s', $message['date']); ?></p>
<p>Message: <?php echo $message['text']; ?></p>
<?php
}
?>

Categories