I’m using PHPRunner and I'm trying to create a button to send an email to selected users with personalized body message. I found an example in PHPRunner support page (Send an email to selected users) but it is only with an hardcoded message, so I’m trying to modify the example.
I managed to send correctly the email with personalized message if I only select one user, but if I select more than one all of them will receive the same message.
This is what I have now:
$emails = array();
while( $data = $button->getNextSelectedRecord() )
{
if( $data["EMAIL_FIELD"] )
$emails[] = $data["EMAIL_FIELD"];
$body = $data["MESSAGE_FIELD"];
}
// send the email
$email = implode(", ", $emails);
$subject = "";
$arr = runner_mail(array('to' => $email, 'subject' => $subject, 'body' => $body));
$result["txt"] = "Email were sent.";
// if error happened print a message on the web page
if( !$arr["mailed"] )
{
$errmsg = "Error happened: <br>";
$errmsg.= "File: " . $arr["errors"][0]["file"] . "<br>";
$errmsg.= "Line: " . $arr["errors"][0]["line"] . "<br>";
$errmsg.= "Description: " . $arr["errors"][0]["description"] . "<br>";
$result["txt"] = $errmsg;
}
What should I change? Thank you.
Problem:
In the foreach loop you are appending every new email address to one variable:
$emails[] = $data["EMAIL_FIELD"];
and you are assigning new value to $body variable (overriding the old one) in each iteration:
$body = $data["MESSAGE_FIELD"];
Therefore when you are calling runner_mail just once outside of the while loop, you will send same body (from the last iteration) to all recipients (you built an array of all recipients using while loop).
Solution:
You need to call runner_mail for each recipient (as the body is different). You can achieve it by moving the call to runner_mail inside the while loop:
while( $data = $button->getNextSelectedRecord() )
{
// Send only if email field not empty
if( $data["EMAIL_FIELD"] ) {
// This no longer should be an array of emails
$email = $data["EMAIL_FIELD"];
$body = $data["MESSAGE_FIELD"];
$subject = "";
// Email will be sent for each record
$arr = runner_mail(array('to' => $email, 'subject' => $subject, 'body' => $body));
}
}
Related
I am trying to print contents of message body of proto file. But my code below is printing details of import too which I don't want. Any suggestion on how to filter this so that only message contents will be printed.
FileInputStream fin = new FileInputStream("mymessages.desc");
Descriptors.FileDescriptorSet set = Descriptors.FileDescriptorSet.parseFrom(fin);
for(FileDescriptorProto fileDesc : set.getFileList()){
List<DescriptorProto> descList = fileDesc.getMessageTypeList();
for(DescriptorProto desc : descList ){
System.out.Println(desc) ; // print all proto info including the imported field as well as message
}
}
}
My proto file
syntax = "proto3"
import "validate.proto";
message User{
string firstName = 1;
string lastName = 2;
}
You could just delete the header lines:
System.out.println(desc.replaceAll("(?sm)\\A.*?(?=^message)", ""));
The regex (?sm)\\A.*?(?=^message) matches everything from start up to, but not including, the first line that starts with message, which is replaced with a blank (ie deleted).
Here is my goal
1. I have only one ID send from the server with list of string separated comma
this how it look like: ID=1, names=blue,red,green,yellow
2. This is my attempt:
2.1 i try to change the names to arrays by using this code
$myString = "Red,Blue,Black";
$myArray = explode(',', $myString);
2.2 and i try my insertion like this:
$sql="INSERT INTO `cat_interest`(`id`,`categories`) VALUES (1,'".$myArray["categories"]."'";
if (!$result = $mysqli->query($sql)){
$message = array('Message' => 'insert fail');
echo json_encode($message);
}else{
$message = array('Message' => 'new record inserted');
echo json_encode($tempArray);
}
Here is my complete code view
<?php
define('HOST','serveraddress');
define('USER','root');
define('PASS','pass');
define('DB','dbname');
ini_set('display_errors',1);
//ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$mysqli = new mysqli(HOST,USER,PASS,DB);
$message= array();
$myString = "Red,Blue,Black";// incoming string comma names
$myArray = explode(',', $myString);
$sql="INSERT INTO `cat_interest`(`id`,`categories`) VALUES (1,'".$myArray["categories"]."'";
if (!$result = $mysqli->query($sql)){
$message= array('Message' => 'insertion failed');
echo json_encode($message);
}else{
$message= array('Message' => 'new record inserted');
echo json_encode($message);
} ?>
This is what i want to achieve below
TABLE
ID Categories
1 RED
1 Blue
1 Black
after insertion
Please help i don't know what i doing wrong
While that SQL is invalid, you never close the values. Explode also doesn't build an associated array.
A rough example of how you could build a valid SQL statement would be
$myString = "Red,Blue,Black";// incoming string comma names
$myArray = explode(',', $myString);
print_r($myArray);
$sql = "INSERT INTO `cat_interest`(`id`,`categories`) VALUES";
foreach($myArray as $value){
$sql .= " (1, '{$value}'),";
}
$sql = rtrim($sql, ',');
Demo: https://eval.in/587840
When in doubt about how an array in constructed use print_r or var_dump. When having an issue with a query in mysqli use error reporting, http://php.net/manual/en/mysqli.error.php.
Also in your current usage you aren't open to SQL injections but if $myString comes from user input, or your DB you could be. You should look into using parameterized queries; http://php.net/manual/en/mysqli.quickstart.prepared-statements.php.
I am new to php .. anyway I have an application that require to provide the vacation information from the database to the supervisor and then allow the supervisor to enter his approval of this vacation ,
To do this, I use 2 php pages:
one to retrieve the employee vacation request information
and the other to insert the supervisor approval into the database
I want the application to insert this approval value in the record of this employeeID that I retrieve his information in this application.
The retrieval of employee information is done correctly, but the insert doesn't work !
I try this query but it didn't work (it didn't return any results when I exceute the query):
<?php
if(! $conn)
{
die('Could not connect: '.mysql_error());
}
mysql_select_db("a2202757_OURDATA",$conn);
$flag['code']=0;
if($r = mysql_query ("UPDATE request_vacation SET VacationApprove='".$_POST['Approval']."' WHERE IDEmployee=$id",$conn));
{
$flag['code']=1;
}
print(json_encode($flag));
mysql_close($conn);
?>
What is the problem ?
What happens is that you assign a variable ( = is an assignment for comparison you use == or ===) in an if statement.
When you want to check and assign at the same time use this:
if(false !== $r = $mysql_query("UPDATE .......") {
echo 'Update successfull';
}
else {
echo 'Update failed with error ' . mysql_error();
}
It is difficult to solve the problem if you do not provide any error message about the database connection. Please use the following code and using your host and username password to let php to print out the error message. It would be useful if you can provide further error information.
$conn = mysql_connect('localhost','username','password');
if(! $conn)
{
die('Could not connect: '.mysql_error());
}
$db_selected = mysql_select_db("a2202757_OURDATA",$conn);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
$flag['code']=0;
$r = mysql_query ("UPDATE request_vacation SET VacationApprove='".$_POST['Approval']."' WHERE IDEmployee=$id",$conn);
if (!$r) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
if($r != null);
{
$flag['code']=1;
}
print(json_encode($flag));
mysql_close($conn);
Try this
<?php
if (isset ( $_POST ['Approval'] )/* && isset ( $_POST ['IDEmployee'] )*/) {
mysql_connect ( 'server', 'username', 'password' ) or die ( mysql_error () );
mysql_select_db ( 'a2202757_OURDATA' );
// mysql_query ( "UPDATE request_vacation SET VacationApprove='" . $_POST ['Approval'] . "' WHERE IDEmployee= '" . $_POST ['IDEmployee'] . "'" ) or die ( mysql_error () );
// Hey, What is $id, I leave it up to you.
mysql_query ( "UPDATE request_vacation SET VacationApprove='" . $_POST ['Approval'] . "' WHERE IDEmployee= '" . $id . "'" ) or die ( mysql_error () );
if (mysql_affected_rows () != - 1) {
// some rows has affected
echo mysql_affected_rows () . 'rows has affected';
} else {
// No row has affected
}
} else {
die ( 'Approval '/* . 'and/or IDEmployee'*/ . ' are not properly set' );
}
?>
and, please give some more detail
I think your code formatting is somehow broken on stackexchange.
Below is an example of how to use queries, because you code seems to be fairly broken and nonsense.
Attention: Don't use that in a production environment because it includes some SQLInjection vulnerabilities.
$id = $_POST["IDEmployee"];
// this sets the VacationApprove clumn of request_vacation
// to the $_POST['Approval'] variable where IDEmployee matches
// the previously selected $id
$insRes = mysql_query("UPDATE request_vacation SET VacationApprove = '".$_POST['Approval']."' WHERE IDEmployee = '".$id."'")
I don't know what you are trying to achieve. Please be more specific about your problem.
I need to add a code to my sendEmail.php bellow which would rotate evenly between two or more recipient. Right now all goes to one recipent "sendto" myemail#gmail.com. So I want to add more myemail-1#gmail.com, myemail-2#gmail.com and so on. This way each will receive fresh leads.
<?php
ob_flush();
session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['phone'] = $_POST['phone_1']."- ".$_POST['phone_2']."- ".$_POST['phone_3'];
$_SESSION['liberation'] = $_POST['liberation'];
$sendto = "myemail#gmail.com";
$email = $_POST['email'];
$username= nl2br($_POST['username']);
$subject = "New lead from my website";
$headers = "From: <form#manysites.com> \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<p><strong>Name:</strong> ".$_POST['username']."</p>\r\n";
$msg .= "<p><strong>Sent by:</strong> ".$_POST['email']."</p>\r\n";
$msg .= "<p><strong>Phone No.: </strong> ".$_POST['phone_1']."- ".$_POST['phone_2']."- ".$_POST['phone_3']."</p>\r\n";
$msg .= "<p><strong> conviction date:</strong> ".$_POST['liberation']."</p>\r\n";
$msg .= "</body></html>";
#mail($sendto, $subject, $msg, $headers);
header("Location:continue.php");
?>
You can simply use the comma operator and then send it right away.. like this..
$sendto = 'myemail1#gmail.com,myemail2#gmail.com,myemail3#gmail.com';
mail($sendto, $subject, $msg, $headers);
Alternatively, you can use an implode() too..
$myemails = array('myemail1#gmail.com','myemail2#gmail.com','myemail3#gmail.com');
$sendto = implode(',',$myemails);
mail($sendto, $subject, $msg, $headers);
Sending them separately....
$myemails = array('myemail1#gmail.com','myemail2#gmail.com','myemail3#gmail.com')
foreach($myemails as $email)
{
mail($email, $subject, $msg, $headers);
}
I think the challenge here is that this script runs with no knowledge of what happened on any occasion that it previously ran. So, one option would be to store the information about who received the last lead. This way when the next person fills in your web form, you can retrieve the value of the last recipient and send the current lead to the next recipient in an array of defined recipients (then update the information about who was the last recipient for the next time).
If you don't have access to a database (or file or something else that is a 'permanent' type of storage) to store the value of the last recipient in, you could simply randomize who receives the current lead. The law of averages suggests that over time, the lead distribution should be relatively equal, though in practice this could result in one person getting all of the leads in a given period.
$recipients=array("recipient1#email.com","recipient2#email.com");
$randnum = mt_rand(0,1);
$sendto = $recipients[$randnum];
Hey Ive run into a little problem in my SQL/PHP/JAVA application Im hoping you guys can help :)
I have a java application that when run is connected to my website when the java application validates that it is running it talks to my website and my website assigns a session Id to both the java application and the website itself.
cool we good so far?
alright my java application sends data at regular intervals to a page called Dashboard.php what I would like to do is save the data into my Mysql table then when new data is received by Dashboard.php from my java application where the sessionID is the same I would like the table to update to the new data that was just received
here is the php i have so far although it doesnt work.
function update($script_name, $version, $runtime, $status, $ranged, $attack, $defense, $strength, $magic, $sessionID, $username)
{
global $db;
$sql = "SELECT * FROM Dashboard WHERE session_id = '$sessionID'";
try {
$results = $db->query($sql);
if ($results->rowCount() <= 0) {
$query = "INSERT INTO Dashboard (script_name, version, runtime, status, ranged, attack, defense, strength, magic, session_id, username) VALUES ('$script_name', '$version', '$runtime', '$status', '$ranged', '$attack', '$defense', '$strength', '$magic', '$sessionID', $username)";
$db->exec($query);
} else {
foreach ($results as $row) {
$timerunnew = $row['runtime'] + $runtime;
$v4new = $row['ranged'] + $range;
$v5new = $row['attack'] + $attack;
$v6new = $row['defense'] + $defense;
$v7new = $row['strength'] + $strength;
$v8new = $row['magic'] + $magic;
}
$db->exec("UPDATE Dashboard SET `runtime` = $timerunnew, `ranged` = $v4new, `attack` = $v5new, `defense` = $v6new, `strength` = $v7new, `magic` = $v8new WHERE session_id = '$sessionID'");
}
} catch (PDOException $ex) {
echo "fail";
}
}
Ive also tried experimenting with ON DUPLICATE KEY UPDATE value = VALUES(value) however I have had no luck does anyone have a solution? any help would be much appreciated
If this is the only way that records can be inserted into the Dashboard table, then it is impossible for two records to share the same session_id (save for a race hazard occurring between the SELECT and INSERT commands). In which case, you should:
Ensure that there is a UNIQUE key defined on session_id:
ALTER TABLE Dashboard ADD UNIQUE KEY (session_id);
Use INSERT ... ON DUPLICATE KEY UPDATE, ideally with a properly parameterised prepared statement:
$qry = $db->prepare('
INSERT INTO Dashboard (
script_name, version, runtime, status, ranged, attack,
defense, strength, magic, session_id, username
) VALUES (
:script_name, :version, :runtime, :status, :ranged, :attack,
:defense, :strength, :magic, :session_id, :username
) ON DUPLICATE KEY UPDATE
runtime = runtime + VALUES(runtime),
attack = attack + VALUES(status),
defense = defense + VALUES(defense),
strength = strength + VALUES(strength),
magic = magic + VALUES(magic)
');
$qry->execute([
':script_name' => $script_name,
':version' => $version,
':runtime' => $runtime,
':status' => $status,
':ranged' => $ranged,
':attack' => $attack,
':$defense' => $defense,
':strength' => $strength,
':magic' => $magic,
':session_id' => $sessionID,
':username' => $username
]);