Strange issue with timestamp update in MYSQL - php

I have a strange issue i have come accross on a few sites i have built, but i am unable to find the problem, it seems so simple, when a user logs in to the site i update the timestamp for the column "member_login" to NOW() which works great, the only issue is, it also updates the "member_joined" column to the exact same time as the "member_login" timestamp but NOWHERE in the code do i tell it to update the "member_joined" column! the entire login script is fairly simple:
login.php
<?php
session_start();
include('includes/db_connection.php');
include('includes/functions.php');
?>
<?php
if (isset($_POST['submitLogin'])) {
$username = trim(strtolower($_POST['username']));
$password = trim(strtolower($_POST['password']));
if (empty($username) || empty($password)) {
include('includes/header.php');
include('includes/navbar.php');
stderr('Please fill in <b>both</b> login fields.');
include('includes/footer.php');
}
$memberInfo = DB::getInstance()->selectOne(
'
SELECT DISTINCT member_username, member_fees_paid, member_fees_paid_on
FROM `membership`
WHERE `member_username` = :member_username
AND `member_password` = :member_password',
[
'member_username' => $username,
'member_password' => $password
]
);
if (!count($memberInfo)) {
include('includes/header.php');
include('includes/navbar.php');
stderr('Sorry, username <b>and/or</b> password combination not found.');
include('includes/footer.php');
} else {
$_SESSION['member'] = $username;
if ($memberInfo['member_fees_paid'] === 'N') {
$payedOn = new \DateTime($memberInfo['member_fees_paid_on']);
$payedOn->setTime(0, 0, 0);
$monthAgo = new \DateTime('28 days ago');
$monthAgo->setTime(0, 0, 0);
if ($monthAgo > $payedOn) {
try {
DB::getInstance()->execute(
'
UPDATE `membership`
SET `member_fees_paid`= \'N\'
WHERE `member_username` = :member_username
AND `member_password` = :member_password',
[
'member_username' => $username,
'member_password' => $password
]
);
header('Location: my-account.php');
} catch (Exception $e) {
include('includes/header.php');
include('includes/navbar.php');
stderr($e->getMessage());
include('includes/footer.php');
}
}
}
try {
DB::getInstance()->execute(
'
UPDATE `membership`
SET `member_login` = NOW()
WHERE `member_username` = :member_username
AND `member_password` = :member_password',
[
'member_username' => $username,
'member_password' => $password
]
);
header('Location: my-account.php');
} catch (Exception $e) {
include('includes/header.php');
include('includes/navbar.php');
stderr($e->getMessage());
include('includes/footer.php');
}
}
}
?>
<?php
include('includes/header.php');
include('includes/navbar.php');
?>
<div class="panel panel-primary">
<div class="panel-heading">Login to your account.</div>
<div class="panel-body">
<form action="login.php" method="post" class="form-horizontal container-fluid" role="form">
<div class="row form-group">
<div class="col-sm-6 text-right">
<label class="control-label">Username:</label>
</div>
<div class="col-sm-6">
<input type="text" name="username" class="form-control" size="40" required="required"/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label class="control-label">Password:</label>
</div>
<div class="col-sm-6">
<input type="password" name="password" class="form-control" size="40" required="required"/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label class="control-label" style="display: inline-block;"> </label>
</div>
<div class="col-sm-6 text-right">
<button type="submit" name="submitLogin" class="btn btn-primary">Login</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">Forgot <b>your password</b>? recover it here.</div>
</div>
<?php
include('includes/footer.php');
On a successful login we just update the timestamp for the "member_login" and redirect to the "my-account.php" page, which works as it should, but it keeps updating the "member_joined" colums the same as the "member_login" i cannot figure out why it is doing this, any help would be appreciated!

If your column member_joined is type timestamp, you might want to check that on update CURRENT_TIMESTAMP isn't being used - you can check this in a database reader such as phpMyAdmin, SequalPro, Heidi etc.
This will automatically update the datestamp to the current date/time.

Related

How to return the mysql query result back to the html page after execution php script?

I am having a form where the user enters 2 variables. These 2 variables are used in my mysqlquery. The result can be either: no matches or 1 or more matches. In each case I would like to have the output of that sql query as result on the original webpage below the entry fields (in the "queryresult" text field). How to do that?
The query is working but after clicking the button a new page is opened with the result of the query which is what I don't want.
you can see the form here: www.larscichowski.nl/coinexchange
I tried already with hidden iframe and checked the answers on a similar question
within the html this is the code for the form part:
<section class="section-form" id="form">
<div class="row" >
<h2>Coin Exchange Finder</h2>
</div>
<div class="row">
<form method="get" action="query.php" class="contact-form">
<div class="row">
<div class="col span-1-of-3">
<label for="name">Source Coin</label>
</div>
<div class="col span-1-of-3">
<input class="typeahead form-control" name="sourcecoin" id="sourcecoin" type="text" required>
</div>
</div>
<div class="row">
<div class="col span-1-of-3">
<label for="name">Destination Coin</label>
</div>
<div class="col span-1-of-3">
<input class="typeahead form-control" name="destcoin" id="destcoin" type="text" >
</div>
</div>
<script type="text/javascript">
<div class="row">
<div class="col span-1-of-3">
<label> </label>
</div>
<div class="col span-2-of-3">
<input type="submit" value="Find matching
exchanges">
</div>
</div>
<div class="row">
<div class="col span-1-of-3">
<label>We found the following matches:</label>
</div>
<div class="col span-2-of-3">
<input type="text" id="queryResult"/>
</div>
</div>
</form>
</div>
</section>
the query.php file looks like this:
<?php
$servername = "xx";
$username = "xx";
$password = "xx";
$dbname = "xx";
$sourcecoin = strip_tags(trim($_POST["sourcecoin"]));
$destcoin = strip_tags(trim($_POST["destcoin"]));
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "Connection not established. Check credentials";
}
$sql = "SELECT Pairs_Source.Exchange, Exchanges.HyperLink
FROM Pairs AS Pairs_Source INNER JOIN Pairs AS Pairs_Dest ON
Pairs_Source.Exchange = Pairs_Dest.Exchange
Left join Exchanges on Pairs_Source.Exchange=Exchanges.Exchange
WHERE Pairs_Source.Coin='$sourcecoin' AND Pairs_Dest.Coin='$destcoin'";
$result = $conn->query($sql);
$json = [];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$json[]=$row['Exchange'];
//echo "<br> They have got the following exchange(s) in common: ".
$row["Exchange"] ."<br>";
}
} else {
echo "Unfortunately these 2 coins don't have an exchange in
common";
}
echo json_encode($json);
$conn->close();
?>
You can submit the form to the same page and have the php code in the same file.
To do this, wrap your PHP code within if($_SERVER['REQUEST_METHOD'] == 'POST'), so it will only run when the form is submitted.
You need to change your form tag so it submits to the current page (or the page name in the action):
<form method="post" action="" class="contact-form">
Then, you can change your result part to something like this. (So it will store the message that you want to display into a variable):
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$message = "<br> They have got the following exchange(s) in common:
". $row["Exchange"] ."<br>";
}
} else {
$message = "Unfortunately these 2 coins don't have an exchange in
common";
}
Finally, you can echo the message anywhere in your page by doing this:
if(isset($message)) {
echo $message;
}
Your page will look something like this:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// The contents of query.php
}
// the html code

php login page worked in localhost but not in live server

I have been tired of finding out why this login.php can run well in localhost enviroment but not in the live server. when login, error with wrong username & password but while in localhost, successful. connection with db is correct.
anyone can help me check my coding.
below is my code
<?php require_once('Connections/conn.php'); ?>
<?php
session_start();
if(isset($_POST["s_username"]) && isset($_POST["s_password"])){
$s_username = $_POST["s_username"];
$s_password = $_POST["s_password"];
echo "<script>window.alert('$s_username - $s_password');</script>";
$sql= mysql_query("SELECT * FROM student WHERE studentNo = $s_username AND studentPswd = $s_password LIMIT 1");
$sql2= mysql_query("SELECT * FROM clockin WHERE studentNo = '$s_username' AND status=0 LIMIT 1");
$existCount = mysql_num_rows($sql);
$s_status = "1";
if($existCount==1){
while($row = mysql_fetch_array($sql)){
$s_no=$row['studentNo'];
$s_name=$row['studentName'];
}
if($existCount2==1){
while($row2 = mysql_fetch_array($sql2)){
$s_status=$row2['status'];
$s_clockid=$row2['clockID'];
}}
$_SESSION["s_no"]=$s_no;
$_SESSION["MM_Username"]=$s_username;
if($sql==true){
echo "<script>window.alert('Login Success');</script>";
</script>";
if($s_status==1){
header("refresh:1 ,url=beginSession.php ");
exit();
}
else {
echo "<script>window.alert('Sesi Lepas Belum Ditamatkan.');</script>";
header("refresh:1 ,url=startedSession2.php?clockid=$s_clockid");
exit();
}
}
}
else{
echo "<script>window.alert('Login Failed.');</script>";
header("refresh:1 ,url=login.php");
exit();
}
}
?>
<body>
<div class="wrapper-page">
<div class="panel panel-color panel-primary panel-pages">
<div class="panel-heading bg-img">
<div class="bg-overlay"></div>
<h3 class="text-center m-t-10 text-white"><strong>Masuk ke</strong>
<p><img src="img/logo2.png" alt="" title=""></p></h3>
</div>
<div class="panel-body">
<form class="form-horizontal m-t-20" id="form1" method="post" action="login.php">
<div class="form-group">
<div class="col-xs-12">
<input name="s_username" class="form-control input-lg" type="text" required="" placeholder="Username">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input name="s_password" class="form-control input-lg" type="password" required="" placeholder="Password">
</div>
</div>
<div class="form-group text-center m-t-40">
<div class="col-xs-12"><label>
<button class="btn btn-primary btn-lg w-lg waves-effect waves-light" type="submit" value="Log in">Log In</button></label>
<label>Daftar Baru</label>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
I hope anyone can help me.
Thank you
Try this
session_start();
require_once('Connections/conn.php');
session_start(); is always top of the page.
also remove the additional closing :
echo "<script>window.alert('Login Success');</script>";
This code is causing syntax error:
echo "<script>window.alert('Login Success');</script>";
</script>";
Remove the additional </script>":
echo "<script>window.alert('Login Success');</script>";
https://www.tinywebhut.com/errors-and-custom-error-handling-in-php-56
Be Careful
You are using deprecated mysql, use mysqli extension instead. I suppose you are aware of SQL injection. Always use prepared statements.
Prepared statements already help to remove a ton of problems to get the query working.

Can not save data to Database cakephp

I have table SubjectTutor who has column id, subject_id, tutor_id, province_id, city_id, school_id, state_private and status. I want to insert data into SubjectTutor table but the error is
province_id, city_id, school_id and state_private will not
saved into table SubjectTutor, but id, subject_id, and tutor_id
will be saved.
this is controller. I also set province_id, city_id, school_id and state_private value.
public function admin_add_pack($standard_id=null)
{
$this->loadModel('Plan');
$this->loadModel('SubjectTutor');
$this->loadModel('Standard');
$this->loadModel('Province');
$this->loadModel('City');
$this->loadModel('School');
$this->loadModel('User');
$standard_data = $this->Standard->find('first',array('conditions'=>array('Standard.id'=>$standard_id)));
$province_id = 32;
$city_id = 44;
$school_id = 1855;
$this->set('title_for_layout','Subject');
if(!empty($this->request->data))
{
if (!isset($this->request->params['_Token']['key']) || ($this->request->params['_Token']['key'] != $this->request->params['_Token']['key']))
{
$blackHoleCallback = $this->Security->blackHoleCallback;
$this->$blackHoleCallback();
}
//validate user data
$this->SubjectTutor->set($this->request->data['SubjectTutor']);
$this->SubjectTutor->setValidation('add');
if ($this->SubjectTutor->validates())
{
// $this->request->data['Subject']['user_id'] = $this->Auth->user('id');
$userdata = $this->request->data['SubjectTutor'];
$this->SubjectTutor->save($userdata,false);
$subject_tutor_id = $this->SubjectTutor->id;
$this->SubjectTutor->school_id = 1855;
$this->SubjectTutor->province_id = 32;
$this->SubjectTutor->city_id = 44;
$this->SubjectTutor->state_private = 1;
$this->Session->setFlash("Record has been added successfully", 'admin_flash_good');
$this->redirect(array('controller'=>'standards', 'action'=>'subject_list',$standard_id));
}
else
{
$this->Session->setFlash("Record has not been created", 'admin_flash_bad');
}
}
$tutors = $this->User->getStandardTutorList($standard_id);
$subjects = $this->Subject->getStandardSubjectList($standard_id);
$standards = $this->Standard->getStandardList();
$provinces = $this->Province->getProvinceList();
$cities = $this->City->getCityList();
$schools = $this->School->getSchoolList();
$this->set(compact('provinces'));
$this->set(compact('standards','standard_id','province_id','city_id','school_id','standard_data','tutors','subjects','provinces','cities','schools','tutor_id'));
}
this is ctp file:
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1"> Select Tutor </label>
<?php echo($this->Form->input('SubjectTutor.tutor_id', array('options'=>$tutors,'div'=>false, 'label'=>false, "class" => "form-control",'empty'=>'Select Tutor')));?>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1"> Select Standard </label>
<?php echo ($this->Form->input('Subject.standard_id2', array('options'=>$standards,"div"=>false,"default"=>$standard_id,"label"=>false,"class"=>"form-control",'disabled'=>true))); ?>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1">Select Subject </label>
<?php echo ($this->Form->input("SubjectTutor.subject_id", array('empty'=>'--Select Subject--', 'options'=>$subjects,"div"=>false,"label"=>false,"class"=>"form-control",'disabled'=>false))); ?>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1">Province </label>
<?php echo ($this->Form->input("SubjectTutor.province_id", array('empty'=>'--Select Province--', 'options'=>$provinces,"div"=>false,"default"=>$province_id,"label"=>false,"class"=>"form-control",'disabled'=>true))); ?>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1">City </label>
<?php echo ($this->Form->input("SubjectTutor.city_id", array('empty'=>'--Select City--', 'options'=>$cities,"div"=>false,"default"=>$city_id,"label"=>false,"class"=>"form-control",'disabled'=>true))); ?>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1">School </label>
<?php echo ($this->Form->input("SubjectTutor.school_id", array('empty'=>'--Select School--', 'options'=>$schools,"div"=>false,"default"=>$school_id,"label"=>false,"class"=>"form-control",'disabled'=>true))); ?>
</div>
</div>
When you use the 'disabled' option for a field in a view, that field doesn't get set when the form data is saved.. Either use 'readonly' option instead, or set those values in the controller before you save (since you don't need user input anyway). Or display the value to the user without pretending they have any input, and use hidden fields to pass the correct data.

Can't add data through PHP and MySQL

Validate function
function validate(add_app_form){
var valid = true;
var userTxt = document.getElementById("patient_name").value;
var dateTxt = document.getElementById("app_date").value;
var timeTxt = document.getElementById("app_time").value;
var oldName = document.getElementById("select_old").value;
if(userTxt == "" && dateTxt == "" && timeTxt == "" && oldName == "choose")
{
//$("#lblTxt").text("Username and Password are required!");
$('#patient_name').css('border-color', 'red');
$('#app_date').css('border-color', 'red');
$('#app_time').css('border-color', 'red');
$('#select_old').css('border-color', 'red');
$("#add_app_lbl").text("Please Fill all the form");
valid = false;
}
if(userTxt == "" && oldName == "choose")
{
$('#patient_name').css('border-color', 'red');
$("#add_app_lbl").text("Please Add Patient Name Or select an old patient");
valid = false;
}
if(dateTxt == "")
{
$('#app_date').css('border-color', 'red');
$("#add_app_lbl").text("Please Add a Date");
valid = false;
}
return valid;
}
EDITED CODE
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../include/global.php');
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
if(isset($_POST['add_app_btn'])){
//Values From AJAX
$patient_name = $_POST['patient_name'];
$date_app = $_POST['app_date'];
$time_app = $_POST['app_time'];
$reason = $_POST['app_reason'];
$old_patient_id = $_POST['select_old'];
//If new patient
if($patient_name == "" && $old_patient_id != "choose")
{
try{
//See if date and time exist
$appExist = "SELECT * FROM appointment WHERE id_logged = :id_logged AND date_app = :date_app and time_app = : time_app";
$appExistStmt = $conn->prepare($appExist);
$appExistStmt->bindValue(":id_logged", $id_logged);
$appExistStmt->bindValue(":date_app", $date_app);
$appExistStmt->bindValue(":time_app", $time_app);
$appExistStmt->execute();
$appExistStmtCount = $appExistStmt->rowCount();
if($appExistStmtCount == 0)
{
//Add to appointment table
$appAdd = "INSERT INTO appointment(id_logged, patient_id, date_app, time_app, reason)
VALUES(:id_logged, :patient_id, :date_app, :time_app, :reason)";
$appAddStmt = $conn->prepare($appAdd);
$appAddStmt->bindValue(":id_logged", $id_logged);
$appAddStmt->bindValue(":patient_id", $old_patient_id);
$appAddStmt->bindValue(":date_app", $date_app);
$appAddStmt->bindValue(":time_app", $time_app);
$appAddStmt->bindValue(":reason", $reason);
$appAddStmt->execute();
echo "added";
}
else
{
echo "not added";
header("Location: add_appoint.php");
}
}
catch(PDOException $m)
{
$m->getMessage();
echo "error";
header("Location: add_app_btnoint.php");
}
}
}
?>
EDITED CODE 2
<form class="form-horizontal" id="add_app_form" method="post" action="add_appoint.php" onSubmit="return validate(this);">
<div class="box-body">
<div class="form-group">
<label for="patient_name" class="col-sm-3 control-label">Old Patient</label>
<div class="col-sm-4">
<select id="select_old" name="select_old">
<option value="choose">Choose Name</option>
<?php foreach($name_array as $na) { ?>
<option value="<?php echo $na['id'] ?>"><?php echo $na['patient_name'] ?></option>
<?php } ?>
</select>
</div>
<label for="patient_name" class="col-sm-1 control-label">New</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="patient_name" name="patient_name" placeholder="New Patient Name">
</div>
</div>
<div class="form-group">
<label for="app_date" class="col-sm-2 control-label">Date</label>
<div class="col-sm-4">
<input type="date" class="form-control" id="app_date" name="app_date">
</div>
<label for="app_time" class="col-sm-2 control-label">Time</label>
<div class="col-sm-4">
<input type="time" class="form-control" id="app_time" name="app_time">
</div>
</div>
<div class="form-group">
<label for="app_reason" class="col-sm-2 control-label">Reason</label>
<div class="col-sm-10">
<textarea class="form-control" id="app_reason" name="app_reason" placeholder="Reason"></textarea>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submit" id="add_app_btn" name="add_app_btn" class="btn btn-success pull-right">Add Appointment</button>
</div><!-- /.box-footer -->
</form>
I have a php code that take values from a form and add them into MySQL database.
First part of the PHP code, see if the admin choose an already exist patient from drop list, then add a date and time of an appointment with a reason.
Then values are posted into PHP code where we see if we have already an appointment in those date and time. If not ($appExistStmtCount == 0) then go and insert an appointment.
The problem is that nothing added to database and can't see any PHP errors echoed.
Here is the PHP code:
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../include/global.php');
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
if(isset($_POST['add_app_btn'])){
//Values From AJAX
$patient_name = $_POST['patient_name'];
$date_app = $_POST['app_date'];
$time_app = $_POST['app_time'];
$reason = $_POST['app_reason'];
$old_patient_id = $_POST['select_old'];
//If new patient
if($patient_name == "" && $old_patient_id != "choose")
{
try{
//See if date and time exist
$appExist = "SELECT * FROM appointment WHERE id_logged = :id_logged AND date_app = :date_app and time_app = : time_app";
$appExistStmt = $conn->prepare($appExist);
$appExistStmt->bindValue(":id_logged", $id_logged);
$appExistStmt->bindValue(":date_app", $date_app);
$appExistStmt->bindValue(":time_app", $time_app);
$appExistStmt->execute();
$appExistStmtCount = $appExistStmt->rowCount();
if($appExistStmtCount == 0)
{
//Add to appointment table
$appAdd = "INSERT INTO appointment(id_logged, patient_id, date_app, time_app, reason)
VALUES(:id_logged, :patient_id, :date_app, :time_app, :reason)";
$appAddStmt = $conn->prepare($appAdd);
$appAddStmt->bindValue(":id_logged", $id_logged);
$appAddStmt->bindValue(":patient_id", $old_patient_id);
$appAddStmt->bindValue(":date_app", $date_app);
$appAddStmt->bindValue(":time_app", $time_app);
$appAddStmt->bindValue(":reason", $reason);
$appAddStmt->execute();
echo "added";
}
else
{
echo "not added";
header("Location: add_appoint.php");
}
}
catch(PDOException $m)
{
$m->getMessage();
echo "error";
header("Location: add_app_btnoint.php");
}
}
}
?>
And here the HTML form:
<form class="form-horizontal" id="add_app_form" onSubmit="return validate(this);">
<div class="box-body">
<div class="form-group">
<label for="patient_name" class="col-sm-3 control-label">Old Patient</label>
<div class="col-sm-4">
<select id="select_old" name="select_old">
<option value="choose">Choose Name</option>
<?php foreach($name_array as $na) { ?>
<option value="<?php echo $na['id'] ?>"><?php echo $na['patient_name'] ?></option>
<?php } ?>
</select>
</div>
<label for="patient_name" class="col-sm-1 control-label">New</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="patient_name" name="patient_name" placeholder="New Patient Name">
</div>
</div>
<div class="form-group">
<label for="app_date" class="col-sm-2 control-label">Date</label>
<div class="col-sm-4">
<input type="date" class="form-control" id="app_date" name="app_date">
</div>
<label for="app_time" class="col-sm-2 control-label">Time</label>
<div class="col-sm-4">
<input type="time" class="form-control" id="app_time" name="app_time">
</div>
</div>
<div class="form-group">
<label for="app_reason" class="col-sm-2 control-label">Reason</label>
<div class="col-sm-10">
<textarea class="form-control" id="app_reason" name="app_reason" placeholder="Reason"></textarea>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submi;" id="add_app_btn" class="btn btn-success pull-right">Add Appointment</button>
</div><!-- /.box-footer -->
</form>
PS
Values can be seen in the URL but the page just refresh and nothing added
Your form has no method, so it's passing data through get. You need to add method="post" to your form.
Edit. As #u_mulder mentioned, you need to add name attribute to your button for the check in your php if the button is clicked.

Sending email using constant contact mail server instead of php mail

From past few days, I am searching for a solution in Constant Contact APIs at http://developer.constantcontact.com/libraries/sample-code.html,, but was unable to find it. So, below is our requirement.
In my website we have donations, memberships etc. When a user fills Donation form or Membership form or Contact form etc., once user submits the form, we need to send a confirmation email to user.Our requirement is, we want this email to be send from Constant Contact mail server instead of send grid or php mail server. we have already account in constant contact for sending news letters. we need to use those details foe sending confirmation emails for single user and store the email ID in our Constant Contact Account.
We need the helpful APIs to communicate in the above procedure/manner.
We didn't find any solution to send email for single donated user. how to send email to single user and message.
Current we are using third party service(Send Grid), now we would like to move to Constant Contact. We have developed this website in PHP programming language.
Kindly help us to integrate in the above procedure/manner.
Here i attached the file. i am getting error when i using the given API's and format
Below is my simple code
<?php
require_once 'Ctct/autoload.php';
use Ctct\ConstantContact;
use Ctct\Components\Contacts\Contact;
use Ctct\Components\Contacts\ContactList;
use Ctct\Components\Contacts\EmailAddress;
use Ctct\Components\EmailMarketing\Campaign;
use Ctct\Components\EmailMarketing\MessageFooter;
use Ctct\Components\EmailMarketing\Schedule;
use Ctct\Exceptions\CtctException;
// Enter your Constant Contact APIKEY and ACCESS_TOKEN
define("APIKEY", "xxxxxxxxxxxxxxxxxxxxxxxx");
define("ACCESS_TOKEN", "xxxxxxxx-xxxx-xxxx-xxxx-989939366970");
$date = date('Y-m-d H:i:s');
$cc = new ConstantContact(APIKEY);
try {
$lists = $cc->getLists(ACCESS_TOKEN);
} catch (CtctException $ex) {
foreach ($ex->getErrors() as $error) {
print_r($error);
}
}
print_r($lists);
if (isset($_POST['email']) && strlen($_POST['email']) > 1) {
$action = "Getting Contact By Email Address";
try {
// check to see if a contact with the email addess already exists in the account
$response = $cc->getContactByEmail(ACCESS_TOKEN, $_POST['email']);
// create a new contact if one does not exist
if (empty($response->results)) {
$action = "Creating Contact";
$contact = new Contact();
$contact->addEmail($_POST['email']);
$contact->addList($_POST['list']);
$contact->first_name = $_POST['fname'];
$contact->last_name = $_POST['fname'];
/*
* The third parameter of addContact defaults to false, but if this were set to true it would tell Constant
* Contact that this action is being performed by the contact themselves, and gives the ability to
* opt contacts back in and trigger Welcome/Change-of-interest emails.
*
* See: http://developer.constantcontact.com/docs/contacts-api/contacts-index.html#opt_in
*/
$returnContact = $cc->addContact(ACCESS_TOKEN, $contact, true);
// update the existing contact if address already existed
} else {
$action = "Updating Contact";
$contact = $response->results[0];
$contact->addList($_POST['list']);
$contact->first_name = $_POST['fname'];
$contact->last_name = $_POST['fname'];
/*
* The third parameter of updateContact defaults to false, but if this were set to true it would tell
* Constant Contact that this action is being performed by the contact themselves, and gives the ability to
* opt contacts back in and trigger Welcome/Change-of-interest emails.
*
* See: http://developer.constantcontact.com/docs/contacts-api/contacts-index.html#opt_in
*/
$returnContact = $cc->updateContact(ACCESS_TOKEN, $contact, true);
}
}
catch (CtctException $ex) {
echo '<span class="label label-important">Error ' . $action . '</span>';
echo '<div class="container alert-error"><pre class="failure-pre">';
print_r($ex->getErrors());
echo '</pre></div>';
die();
}
}
function createCampaign(array $params)
{
$cc = new ConstantContact(APIKEY);
$campaign = new Campaign();
$campaign->name = $params['fname'];
$campaign->subject = "Test Mail Subject";
$campaign->from_name = $params['fname'];
$campaign->from_email = $params['email'];
//$campaign->greeting_string = $params['greeting_string'];
//$campaign->reply_to_email = $params['email'];
$campaign->text_content = $params['content_text'];
$campaign->email_content = $params['content_text'];
$campaign->email_content_format = 'HTML';
// add the selected list or lists to the campaign
$campaign->addList('venky.para#gmail.com');
return $cc->addEmailCampaign(ACCESS_TOKEN, $campaign);
}
function createSchedule($campaignId, $time)
{
$cc = new ConstantContact(APIKEY);
$schedule = new Schedule();
$schedule->scheduled_date = $time;
return $cc->addEmailCampaignSchedule(ACCESS_TOKEN, $campaignId, $schedule);
}
global $wpdb;
if(isset($_POST['submit']))
{
$fname=mysql_real_escape_string($_POST['fname']);
$useremail=mysql_real_escape_string($_POST['email']);
$content=mysql_real_escape_string($_POST['content_text']);
// attempt to create a campaign with the fields submitted, displaying any errors that occur
try {
$campaign = createCampaign($_POST);
} catch (CtctException $ex) {
echo '<span class="label label-important">Error Creating Campaign</span>';
echo '<div class="container alert-error"><pre class="failure-pre">';
print_r($ex->getErrors());
echo '</pre></div>';
die();
}
// attempt to schedule a campaign with the fields submitted, displaying any errors that occur
try {
$schedule = createSchedule($campaign->id,$date);
} catch (CtctException $ex) {
echo '<span class="label label-important">Error Scheduling Campaign</span>';
echo '<div class="container alert-error"><pre class="failure-pre">';
print_r($ex->getErrors());
echo '</pre></div>';
die();
}
}
?>
<script type="text/javascript">
function validtestmail(){
var fname=document.getElementById('fname').value;
var email=document.getElementById('email').value;
var content_text=document.getElementById('content_text').value;
if(fname=='')
{
alert('Enter Name');
document.getElementById('fname').focus();
return false;
}
else if(email=='')
{
alert('Enter Email');
document.getElementById('email').focus();
return false;
}
else if(content_text=='')
{
alert('Enter Content');
document.getElementById('content_text').focus();
return false;
}
}
</script>
<div class="container ">
<div class="row ">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="innerPagesBlock fullWidth">
<div id="primary" class="col-xs-12 col-sm-12 col-md-8 col-lg-8 content-area contactbg">
<div class="myprofileHeading">Change Password </div>
<form class="form-horizontal" role="form" id="member_cp" name="member_cp" action="<?php echo get_bloginfo('home'); ?>/testmail" method="post" onsubmit="return validtestmail();" style="margin-top:30px;">
<!-- Self form start-->
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 formLog">
<span style="font-size:16px; font-weight: bold; color: #FFFFFF;">
<?php
if($msg)
{?>
<div class="<?php echo $class; ?>" role="alert"><?php
echo $msg;
?>
</div><?php
}
?>
</span>
</div>
<div class="form-login formMain">
<label for="inputEmail3" class="col-xs-12 col-sm-4 col-md-4 col-lg-4 control-label">Name:<span>*</span></label>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 formLog">
<input type="text" class="form-control" id="fname" name="fname" placeholder="Name" value="" >
</div>
<label for="inputEmail3" class="col-xs-12 col-sm-4 col-md-4 col-lg-4 control-label">Email: <span>*</span></label>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 formLog">
<input type="text" class="form-control" id="email" name="email" placeholder="Email" value="" >
</div>
<label for="inputEmail3" class="col-xs-12 col-sm-4 col-md-4 col-lg-4 control-label">Content: <span>*</span></label>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 formLog">
<input type="text" class="form-control" id="content_text" name="content_text" placeholder="Content" value="" >
</div>
<div class="col-xs-6 col-sm-2 col-md-2 col-lg-2 formLog">
<button type="submit" class="btn btn-primary btnSubmit" name="submit" id="submit">Submit</button>
</div>
<div class="col-xs-6 col-sm-2 col-md-2 col-lg-2 formLog">
<button type="reset" name="button2" id="button2" class="btn btn-primary btnReset">Reset</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div id="main-content" class="main-content">
<?php
if ( is_front_page() && twentyfourteen_has_featured_posts() ) {
// Include the featured content template.
get_template_part( 'featured-content' );
}
?>
</div><!-- #main-content -->
Here how to send email to single user. How?. Is it possible?. Please help me. My time wasting from last 2 weeks.
Thanking You
You need to cast $_POST['list'] as a string. It may be posting as an integer.
Changing this:
$contact->addList($_POST['list']);
to this:
$contact->addList( (string)$_POST['list'] );
would probably do it.

Categories