How to send sms to multiple contacts - yii

How to send sms to multiple contacts and get the result code for each of them. It is not working. I get opened only the last number in the 'numbers' string and not to all of them.
What am I doing wrong?
In my controller,
foreach ($sendarraystudent as $studentid) {
//$i++;
$student = Student::model()->findByPk($studentid);
$name = $student->student_firstname . " " . $student->student_middlename . " " . $student->student_lastname;
$smobile = $student->student_mobile;
//$mobilelist = $mobilelist . ',' . $smobile;
$msg1 = $msg;
$msg1 = str_replace("#course#", $course->course_name, $msg);
$msg1 = str_replace("#batch#", $batch->batch_name, $msg1);
$msg1 = str_replace("#name#", $name, $msg1);
$this->sendbulk($smobile, $msg1);
}
protected function sendbulk($mobilenum, $message) {
$no = $mobilenum;
$msg = $message;
$link = "http://url/api/v3/index.php?method=sms&api_key=A6xxxxxxxxxxx&to=" . $no . "&sender=xxxxxx&message=" . $msg . "&unicode=xxx";
header('Location: ' . $link) and exit;
}

I think it is because you use redirect header('Location: ' . $link) and exit;. Processing only one sms. Try this:
foreach ($sendarraystudent as $studentid) {
//...
$link = "http://url/api/v3/index.php?method=sms&api_key=A6xxxxxxxxxxx&to=" . $student->student_mobile . "&sender=xxxxxx&message=" . $msg1 . "&unicode=xxx"
$content = file_get_contents($link);
echo $content;
}

Related

TYPO3 Repository outside controller

I am using TYPO3 10.4.15 and try to write a TcaProcFunc for my own extension.
namespace HGA\Album\UserFunc;
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use HGA\Album\Domain\Repository\AlbumRepository;
use HGA\Album\Domain\Model\Album;
use TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface;
class TcaProcFunc
{
/**
* #param array $config
*
*/
public function getLink(&$config)
{
$ret = [];
$objectManager = GeneralUtility::makeInstance(ObjectManager::class);
$albumRepository= $objectManager->get(AlbumRepository::class);
$albums = $albumRepository->findAll();
foreach ($albums as $album){
$ret[] = ["Test1","Test1"];
}
$i = count($albums);
error_log("Album: " . $i, 0 );
$ret[] = ["Test", "Test"];
$config['items'] = $ret;
// error_log("UserFunc: " . var_export($config, true), 0);
}
}
The problem is, that findall() does not provide any result. $albumsis empty, but there is one record inside the database.
HGA is my vendor name and Album the extension name. The TcaProcFunc is in generell is working, but I don't have any access to the extension database.
Can anybody tell me, what is wrong with my code or how I what I can do to findthe problem?
Thank you in advance.
Finally I did it with ConnectionPool
namespace HGA\Album\UserFunc;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\CMS\Core\Database\ConnectionPool;
class TcaProcFunc
{
/**
* #param array $config
*
*/
public function getLink(&$config)
{
$ret = [];
$albums = GeneralUtility::makeInstance(ConnectionPool::class)
->getConnectionForTable('tx_album_domain_model_album')
->select(
['uid', 'album_artist', 'album'],
'tx_album_domain_model_album',
[]
)->fetchAll();
foreach ($albums as $album){
$ret[] = [$album['album_artist'] . ": " . $album['album'], $album['uid']];
}
$config['items'] = $ret;
}
}

Get mysql table columns names from database when exporting to csv

I'm exprting my databse in csv format, but I can't figure out how to export the mysql table columns names as well. Here is the code:
public function save($query)
{
$stmt = $this->db->prepare($query);
$stmt->execute();
/* header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
var_dump($stmt->fetch(PDO::FETCH_ASSOC));
$data = fopen('/tmp/db_user_export_".time().".csv', 'w');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "Success";
fputcsv($data, $row);
} */
$list = array ();
// Append results to array
array_push($list, array("## START OF USER TABLE ##"));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
array_push($list, array_values($row));
}
array_push($list, array("## END OF USER TABLE ##"));
// Output array into CSV file
$fp = fopen('php://output', 'w');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="file.csv"');
foreach ($list as $ferow) {
fputcsv($fp, $ferow);
}
}
for the query:
include_once 'dbconfig.php';
$query = "SELECT * FROM users";
$crud->save($query);
The file.csv exports correctly but I would like to also include the names of the mysql table columns from where the values are being taken out from.
Thanks in advance!
I was having issues posting my table head into the csv so I took another approach. Hope it helps anyone that's trying to do what I'm doing:
public function export($table)
{
$stmt2 = $this->db->prepare("DESCRIBE ".$table);
$stmt2->execute();
if ($stmt2->rowCount()>0) {
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
$csv_output .= $row['Field'].", ";
$i++;
}
}
$csv_output .= "\n";
$stmt3 = $this->db->prepare("SELECT * FROM ".$table);
$stmt3->execute();
while ($rowr = $stmt3->fetch(PDO::FETCH_BOTH)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}
$filename = "raport_proiecte_".date("Y-m-d_H-i",time()).".csv";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
print $csv_output;
exit;
}

Retrieving a int value from database

I am trying to get sender_id and receiver_id into my variables but it is giving me following error
Warning: mysql_fetch_array() expects parameter 1 to be resource,
object given in /opt/lampp/htdocs/Task/php/insertdatanew.php on line
36
Warning: mysql_fetch_row() expects parameter 1 to be resource, object
given in /opt/lampp/htdocs/Task/php/insertdatanew.php on line 42 N
CODE:
<?php
$sender_id = 0;
$receiver_id = 0;
session_start();
if(isset($_SESSION['login_user'])) {
//header('location: chat.php');
}
else {
header('location: chatlogin.php');
}
if(isset($_REQUEST['sender']) AND isset($_REQUEST['msg']) AND isset($_REQUEST['time']) AND isset($_REQUEST['receiver']) ){
$msg = $_REQUEST['msg'];
$time = $_REQUEST['time'];
$sender = $_REQUEST['sender'];
$receiver = $_REQUEST['receiver'];
echo $sender;
echo $receiver;
echo $msg;
echo $time;
//echo $msg;
if ( empty($_REQUEST['msg']) ) {
}
else{
require_once 'dc_chat.php';
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$result = $mysqli -> query("SELECT id from users where username LIKE '{$sender}'");
$row = mysql_fetch_row($result);
$sender_id = $row[0];
$result = $mysqli -> query("SELECT id from users where username LIKE '{$receiver}'");
$row = mysql_fetch_row($result);
$receiver_id = $row[0];
//echo $receiver_id;
$sql = $mysqli -> query("INSERT INTO `messages` (`sender_id`, `receiver_id`, `msg`, 'chattime') VALUES ('{$sender_id}', '{$receiver_id}', '{$msg}' ,'{$time}')");
if(! $sql ) {
echo 'N';
}
else {
echo 'Y';
}
}
}
else{
echo "hello";
}
?>
I am getting $msg, $time, $sender, $receiver from a ajax and datatype is JSON
You are mixing mysql and mysqli functions. mysql_fetch_row should probably be mysqli_fetch_row.
Replace if (!$sql) with if ($mysqli->affected_rows == 0) to test for success on the INSERT statement.
If you suspect an error in your SQL statement use echo $mysqli->error; after your query line to put that on the screen.

ZF2 insert multiple rows

I'd like to know if there is a way to insert multiple row in ZF2 using only one $sql object (and not using the query(SQL COMMAND) method).
I tried something like this, but it doesn't work:
public function setAgentProjectLink( $IDProject , $IDsAgents )
{
$values = array () ;
foreach ( $IDsAgents as $IDAgent):
{
$values[] = array ( 'id_agent' => $IDAgent , 'id_projet' => $IDProject) ;
} endforeach ;
$sql = new Sql( $this->tableGateway->adapter ) ;
$insert = $sql->insert() ;
$insert -> into ( $this->tableGateway->getTable() )
-> values ( $values ) ;
$statement = $sql->prepareStatementForSqlObject($insert);
$result = $statement->execute();
}
Trying to insert values in a database with two columns (id_agent, id_projet)
there is no generic way for multyinsert in ZF2 BUT if you are using mysql and not planning to change to other databases, i have written a multiInsert function for myself:
$data is an array of arrays of key,value pairs.
protected function multiInsert($table, array $data)
{
if (count($data)) {
$columns = (array)current($data);
$columns = array_keys($columns);
$columnsCount = count($columns);
$platform = $this->db->platform;
array_filter($columns, function ($index, &$item) use ($platform) {
$item = $platform->quoteIdentifier($item);
});
$columns = "(" . implode(',', $columns) . ")";
$placeholder = array_fill(0, $columnsCount, '?');
$placeholder = "(" . implode(',', $placeholder) . ")";
$placeholder = implode(',', array_fill(0, count($data), $placeholder));
$values = array();
foreach ($data as $row) {
foreach ($row as $key => $value) {
$values[] = $value;
}
}
$table = $this->db->platform->quoteIdentifier($table);
$q = "INSERT INTO $table $columns VALUES $placeholder";
$this->db->query($q)->execute($values);
}
}

Applying a SQL function on Zend_Db_Table_Row::save()

Is it possible, when saving a Zend_Db_Table_Row, to make ZF apply a SQL function on one column?
For example, if $row->save() generates by default this SQL query:
UPDATE table SET field = ? WHERE id = ?;
I would like it to automatically apply the GeomFromText() function on this field:
UPDATE table SET field = GeomFromText(?) WHERE id = ?;
Thanks for any hint on how to do this with Zend_Db!
Define a custom update method in your class that inherits from Zend_Db_Table (not from the Zend_Db_Table_Row) and use a Zend_Db_Expr to set the column to the function return value.
See the docs here: http://framework.zend.com/manual/en/zend.db.table.html#zend.db.table.extending.insert-update.
I am just guessing but you could try this:
<?php
class MyTable extends Zend_Db_Table_Abstract
{
protected $_name = 'my_table';
public function update(array $data, $where) {
/**
* Build "col = ?" pairs for the statement,
* except for Zend_Db_Expr which is treated literally.
*/
$set = array();
$i = 0;
foreach ($data as $col => $val) {
if ($val instanceof Zend_Db_Expr) {
$val = $val->__toString();
unset($data[$col]);
} else {
if ($this->_db->supportsParameters('positional')) {
$val = ($col == 'field') ? 'GeomFromText(?)' : '?';
} else {
if ($this->_db->supportsParameters('named')) {
unset($data[$col]);
$data[':col'.$i] = $val;
$val = ($col == 'field') ? 'GeomFromText(:col'.$i.')' : ':col'.$i;
$i++;
} else {
/** #see Zend_Db_Adapter_Exception */
require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception(get_class($this) ." doesn't support positional or named binding");
}
}
}
$set[] = $this->_db->quoteIdentifier($col, true) . ' = ' . $val;
}
$where = $this->_whereExpr($where);
/**
* Build the UPDATE statement
*/
$sql = "UPDATE "
. $this->_db->quoteIdentifier($this->_name , true)
. ' SET ' . implode(', ', $set)
. (($where) ? " WHERE $where" : '');
/**
* Execute the statement and return the number of affected rows
*/
if ($this->_db->supportsParameters('positional')) {
$stmt = $this->_db->query($sql, array_values($data));
} else {
$stmt = $this->_db->query($sql, $data);
}
$result = $stmt->rowCount();
return $result;
}
protected function _whereExpr($where)
{
if (empty($where)) {
return $where;
}
if (!is_array($where)) {
$where = array($where);
}
foreach ($where as $cond => &$term) {
// is $cond an int? (i.e. Not a condition)
if (is_int($cond)) {
// $term is the full condition
if ($term instanceof Zend_Db_Expr) {
$term = $term->__toString();
}
} else {
// $cond is the condition with placeholder,
// and $term is quoted into the condition
$term = $this->quoteInto($cond, $term);
}
$term = '(' . $term . ')';
}
$where = implode(' AND ', $where);
return $where;
}
}
?>