extending php execution time - php

Have tried to extend the execution time by these methods but the script keeps ending prematurely. It is basically cycling through a mysql database and doing something with each row. It should be lasting maybe five to ten minutes but stops consistently early at the same spot. I have tried the following:
set_time_limit(0);
curl_setopt($ch, CURLOPT_TIMEOUT, 2000000);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 200000);
None of them are working. Please help!
<?php
ini_set('max_execution_time', 500);
$user="5aabf73bdd2c7";
//$user = $_POST['user'];
$servername = "localhost";
$username = "placeprint_1";
$password = "JS313833";
$dbname = "placeprint_1";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
function file_get_contents_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 2000000);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 200000);
curl_setopt($ch,CURLOPT_BINARYTRANSFER, true);
$data = curl_exec($ch);
curl_close ( $ch );
return $data;
}
$sql = "SELECT link, id, cookie FROM rawlinks WHERE cookie='$user' ORDER by ID desc ";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$getimagefrom=$row["link"];
$id=$row["id"];
$cookie=$row["cookie"];
echo $getimagefrom;
echo "<br><br>ID:".$id."<br><br>";
$htmlaa = file_get_contents_curl($getimagefrom);
$docaa = new DOMDocument();
#$docaa->loadHTML($htmlaa);
$nodesaa = $docaa->getElementsByTagName('title');
$nodesxaa = $docaa->getElementsByTagName('img');
//get and display what you need:
$titlev = $nodesaa->item(0)->nodeValue;
$metasv = $docaa->getElementsByTagName('meta');
$asv = $docaa->getElementsByTagName('img');
for ($iv = 0; $iv < $metasv->length; $iv++)
{
$metav = $metasv->item($iv);
if($metav->getAttribute('name') == 'description')
$descriptionv = $metav->getAttribute('content');
if($metav->getAttribute('name') == 'keywords')
$keywordsv = $metav->getAttribute('content');
if($metav->getAttribute('property') == 'og:image');
$languagev = $metav->getAttribute('content');
}
for ($ivv = 0; $ivv < $asv->length; $ivv++)
{
$av = $asv->item($ivv);
echo $av->getAttribute('src');
echo "<br>";
$cvarv = $av->getAttribute('src');
echo " <img src='$cvarv' >";
$servername = "localhost";
$username = "placeprint_1";
$password = "JS313833";
$dbname = "placeprint_1";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$getimagefrom = rtrim($getimagefrom, '/');
$cvarv = urlencode($cvarv);
$titlev = preg_replace('/[^\p{L}\p{N}\s]/u', '', $titlev);
$descriptionv = preg_replace('/[^\p{L}\p{N}\s]/u', '', $descriptionv);
}
}
}
$con->close();
echo "FINISHED!!!!";
?>

From php.ini try to increase the max_execution_time and restart apache server.
To locate where your php.ini is you can create a phpinfo.php file and insert the following:
<?php phpinfo();
More informarion here: https://mediatemple.net/community/products/dv/204643880/how-can-i-create-a-phpinfo.php-page
You can then get the location of the php.ini configuration file location when you visit the phpinfo.php on your browser.
From the code I can suggest that instead of doing an INSERT mysql request for every loop, you should prepare the insert values in the loop and then perform the actual mysql request only once after the loop is finished.
Another suggestion is to have curl_close ( $ch ); before the return in file_get_contents_curl()
I have updated your code in order to be able to work in chunks instead of doing all the execution at once. I have created a table import_progress where we will store the last imported/executed row and fetch 20 rows for every execution:
/**
* Get the last imported ID
*
* #param mysqli $con
*
* #return int
*/
function get_last_inserted_id( $con ) {
$sql = "SELECT imported_id
FROM import_progress
ORDER by ID desc
LIMIT 1";
$result = $con->query( $sql );
if ( $result->num_rows == 0 ) {
//Since you are fetching in descending order
//We need to return a very high number if we did not import anything yet
return 999999999999999999;
} else {
while ( $row = $result->fetch_assoc() ) {
return $row['imported_id'];
}
}
}
/**
* Get the last imported ID
*
* #param mysqli $con
* #param array $ids
*
* #return int
*/
function insert_imported_ids( $con, $ids ) {
$ids = array_unique( array_filter( $ids ) );
if ( empty( $ids ) ) {
return false;
}
$sql = "INSERT INTO import_progress (imported_id) VALUES";
//We now append the data to the mysql string
$insert = [];
foreach ( $ids as $id ) {
$insert[] = "($id)";
}
$sql .= implode( ',', $insert ) . ';';
return $con->query( $sql );
}
/**
* #param string $url
*
* #return mixed
*/
function file_get_contents_curl( $url ) {
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_TIMEOUT, 2000000 );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 200000 );
curl_setopt( $ch, CURLOPT_BINARYTRANSFER, true );
$data = curl_exec( $ch );
curl_close( $ch );
return $data;
}
$user = "5aabf73bdd2c7";
$servername = "db";
$username = "root";
$password = "root";
$dbname = "stack_overflow";
// Create connection
$con = new mysqli( $servername, $username, $password, $dbname );
// Check connection
if ( $con->connect_error ) {
die( "Connection failed: " . $con->connect_error );
}
$last_inserted_id = get_last_inserted_id( $con );
$sql = "SELECT link, id, cookie FROM rawlinks
WHERE cookie='$user'
AND ID < $last_inserted_id
ORDER by ID desc
LIMIT 20";
$result = $con->query( $sql );
if ( $result->num_rows > 0 ) {
$imported_ids = [];
// output data of each row
while ( $row = $result->fetch_assoc() ) {
$getimagefrom = $row["link"];
$id = $row["id"];
$cookie = $row["cookie"];
echo $getimagefrom;
echo "<br><br>ID:" . $id . "<br><br>";
$htmlaa = file_get_contents_curl( $getimagefrom );
$docaa = new DOMDocument();
#$docaa->loadHTML( $htmlaa );
$nodesaa = $docaa->getElementsByTagName( 'title' );
$nodesxaa = $docaa->getElementsByTagName( 'img' );
//get and display what you need:
$titlev = $nodesaa->item( 0 )->nodeValue;
$metasv = $docaa->getElementsByTagName( 'meta' );
$asv = $docaa->getElementsByTagName( 'img' );
for ( $iv = 0; $iv < $metasv->length; $iv ++ ) {
$metav = $metasv->item( $iv );
if ( $metav->getAttribute( 'name' ) == 'description' ) {
$descriptionv = $metav->getAttribute( 'content' );
}
if ( $metav->getAttribute( 'name' ) == 'keywords' ) {
$keywordsv = $metav->getAttribute( 'content' );
}
if ( $metav->getAttribute( 'property' ) == 'og:image' ) {
;
}
$languagev = $metav->getAttribute( 'content' );
}
for ( $ivv = 0; $ivv < $asv->length; $ivv ++ ) {
$av = $asv->item( $ivv );
echo $av->getAttribute( 'src' );
echo "<br>";
$cvarv = $av->getAttribute( 'src' );
echo " <img src='$cvarv' >";
$cvarv = urlencode( $cvarv );
$titlev = preg_replace( '/[^\p{L}\p{N}\s]/u', '', $titlev );
$descriptionv = preg_replace( '/[^\p{L}\p{N}\s]/u', '', $descriptionv );
}
$imported_ids[] = (int)$id;
}
insert_imported_ids($con, $imported_ids);
}
$con->close();
echo "FINISHED!!!!";

Curl doesn't make any difference. If set_time_limit doesn't work it means that a global configuration overrides it, try printing the following:
var_dump(ini_get('max_execution_time'));
One time before executing set_time_limit(0); and also after you've done it.
This could be editable by php.ini but also is typically a blocked feature in free or shared hosting providers to prevent users to over-load the shared server.

add
ini_set('max_execution_time', 500);
at the top of the page, here 500 is number of seconds.

Related

Cronjobs on Direct Admin is not working

I created a cronjobs on direct admin, and if that running it will check curl =>>> change values in mysql. But it's not working. Please help me ##. Thanks
This is my code:
<?php
class ControllerVemaybayCronJobapp
{
function index(){
$connect = $this->connect();
$query_routes_1 = $connect->query("SELECT * FROM **** where status = '0' GROUP BY routes ");
for ($result = array();
$row = $query_routes_1->fetch_assoc();
$result[array_shift($row)] = $row);
foreach ($result as $i => $aaa){
$routes = $aaa['routes'];
$detail_routes_2 = $connect->query("SELECT * FROM **** where routes = '" . $routes . "' AND status = '0' ");
for ($result2 = array();
$row2 = $detail_routes_2 ->fetch_assoc();
$result2[array_shift($row2)] = $row2);
foreach ($result2 as $t => $value1) {
$ngay = $value1['ngay'];
$thang = $value1['thang'];
$nam = $value1['nam'];
$min = $value1['minPrice'];
$max = $value1['maxPrice'];
$providers = $value1['providers'];
$startdate = $nam.$thang.'01';
$enddate = $nam.$thang.'31';
$bien = $this->getlist_ticketsofdate($routes,$startdate,$enddate);
foreach ($bien as $k => $value) {
$moi2 = array();
$moi = $value['c'];
$moi2 = $value['f'];
if($value['_id']['dim'] == $ngay ){
if($min <= $value['c'] && $value['c'] <= $max && strpos($providers, $value['p']) !== false){
$connect->query("UPDATE **** SET status='1' where customer_id = '" . $value1['customer_id'] . "' ");
break;
}else{
foreach ($moi2 as $key => $value2) {
if($min <= $value2['cp'] && $value2['cp'] <= $max && strpos($providers, $value2['p']) !== false){
$connect->query("UPDATE **** SET status='1' where customer_id = '" . $value1['customer_id'] . "' ") ;
break;
}
}
}
}
}
}
}
}
function connect(){
$servername = "****";
$username = "****";
$password = "****";
$databasename = "****";
$conn = new mysqli($servername, $username, $password,$databasename);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
function getlist_ticketsofdate($diadiem,$startDate,$endDate){
$url = '****';
$providers = array();
$providers[0] = '****';
$providers[1] = '****';
$providers[2] = '****';
$routes = array();
$routes[0] = $diadiem;
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Connection:keep-alive';
$param = array(
'startDate' => $startDate,
'endDate' => $endDate,
'minPrice' => '0',
'maxPrice' => '700000',
'providers' => $providers,
'routes' => $routes,
'type' => 'date',
);
$data_string = json_encode($param);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$result_tickets = json_decode($response,true);
return $result_tickets;
}
}
?>
This is my cronjobs
Cron job may not works directly on admin, cause it may required authentications for some process.
Sample php file name mail.php
<?php
// the message
$msg = "First line of text\nSecond line of text";
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);
// send email
mail("someone#example.com","My subject",$msg);
?>
Cron command:
For url
* * * * * wget http://example.com/mail.php &> /dev/null
For Path
* * * * * <BASE DIR>/mail.php
This cron job send mail every minute.

Exlpode xml and turn into array

I want to know how to explode or split xml and turn into array and then insert it to database. Because i have an api that need to hit every day and it return xml.
here's my xml sample:
<ArrayOfUnitPrice>
<UnitPrice>
<PriceAmount>1579.7080</PriceAmount>
<PriceDate>2016-09-02</PriceDate>
<PriceType>XWZ</PriceType>
</UnitPrice>
<UnitPrice>
<PriceAmount>1028.4137</PriceAmount>
<PriceDate>2016-09-02</PriceDate>
<PriceType>ABC</PriceType>
</UnitPrice>
...
</ArrayOfUnitPrice>
I'm using this code to extract the xml response:
$ch = curl_init("111.222.333.444:8080/code.asmx/Price");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$result=curl_exec ($ch);
//my code here
curl_close($ch);
SOLVED
I already done solve my code by using this code below guys.
$xml = simplexml_load_string($result);
for ($i=0; $i < count($xml) ; $i++) {
$arr[] = array (
'PriceAmount' => $xml->UnitPrice[$i]->PriceAmount,
'PriceDate' => $xml->UnitPrice[$i]->PriceDate,
'PriceType' => $xml->UnitPrice[$i]->PriceType
);
}
$data = json_decode(json_encode($arr), true);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dailywork";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(is_array($data)){
$check = "SELECT * FROM table_unit";
if($conn->query($check)->num_rows > 0){
// my stuff to here :-D
}else{
/*Insert data to DB*/
$sql = "INSERT INTO table_unit (PriceAmount, PriceDate, PriceType) values ";
$valuesArr = array();
foreach($data as $row){
$PriceAmount = $row[PriceAmount][0];
$PriceDate = $row[PriceDate][0];
$PriceType = $row[PriceType][0];
$valuesArr[] = "('$PriceAmount', '$PriceDate', '$PriceType')";
}
$sql .= implode(',', $valuesArr);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
/*End Insert data to DB*/
}
}
$conn->close();
This function will give you an array of your xml
function xml2php($xmlcontent)
{
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $xmlcontent, $arr_vals);
xml_parser_free($xml_parser);
return $arr_vals;
}
pass your $result like this and check it
xml2php($result);
let me know if it helps you

PHP curl automatically sending two requests

Im Using PHP curl for saving website name page name on which user has just clicked and ip address in my database, but the problem curl send 2 requests automatically one with correct data and in other one just changed the page name to index.php, i want to abort the second request just, means when curl executes one time then no request by curl untill an other click on the same page, hope my discription will help you to find out my error for me, here is my code.
**This IS My Curl Code**
$wb_nm = $_SERVER[HTTP_HOST];
$pg_nm = $_SERVER[PHP_SELF];
$usr_ip = $_SERVER[REMOTE_ADDR];
$pg_nm_ultr = trim($pg_nm , '/');
$n_url = "localhost/curl/new_page.php";
$data = array(
"varhost" => $wb_nm,
"varpage" => $pg_nm_ultr,
"varip" => $usr_ip
);
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $n_url);
curl_setopt($post, CURLOPT_POSTFIELDS, $data);
curl_setopt($post, CURLOPT_RETURNTRANSFER, false);
$result = curl_exec($post);
curl_close($post);
?>
**And This Is new_page.php**
if(isset($_POST['varhost']) && isset($_POST['varpage']) && isset($_POST['varip']))
{
$web_name = $_POST['varhost'];
$page_name_ulter = $_POST['varpage'];
$user_ip = $_POST['varip'];
define("DB_HOSTNAME", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_DB", "pan");
$connection = mysqli_connect(DB_HOSTNAME, DB_USER, DB_PASS, DB_DB);
if(isset($connection)){
$query = "SELECT * FROM tbl_agencies WHERE weblink = '".$web_name."'";
$result = mysqli_query($connection , $query);
if($result){
while($row = mysqli_fetch_array($result)){
if(isset($row))
{
$D_id = $row['domain_id'];
$D_name = $row['website'];
if($D_id == 0)
{
return false;
}
}
else
{
}
break;
}
}
}
$date_date = date('Y-m-d');
$time_stamp = date("H:i:s");
$query_Code = "INSERT INTO user_details (website_domain_id , website_domain_name , page_clicked , user_IP , access_date , access_time) VALUES ('".$D_id."','".$D_name."' , '".$page_name_ulter."' , '".$user_ip."' , '".$date_date."' , '".$time_stamp."')";
$result_Code = mysqli_query($connection , $query_Code);
if($result_Code)
{
mysqli_close($connection);
}
}
?>
In curl_setopt($post, CURLOPT_POSTFIELDS, $fields);, you can send fields as an associative array. So this code:
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
is actually not needed such that curl_setopt($post, CURLOPT_POSTFIELDS, $fields); becomes
curl_setopt($post, CURLOPT_POSTFIELDS, $data);

SQL Query in PHP script doesnt fill table in database

In PHP script I parsed some .csv file and trying to execute on a few ways and this is a closest I can get. When I run query manually in database everything is o.k but when I go through the the script I just got New record created successfully and the table stays empty except ID which count how many inserts I got.
o.k that's cool optimization but I still don't getting the data. Yap the $dataPacked is clear below is my whole script can you pls gave some suggestion.
<?php
class AdformAPI {
private $baseUrl = 'https://api.example.com/Services';
private $loginUrl = '/Security/Login';
private $getDataExportUrl = '/DataExport/DataExportResult?DataExportName=ApiTest';
public function login($username, $password) {
$url = $this->baseUrl . $this->loginUrl;
$params = json_encode(array('UserName' => $username, 'Password' => $password));
$response = $this->_makePOSTRequest($url, $params);
$response = json_decode($response, true);
if (empty($response['Ticket'])) {
throw new \Exception('Invalid response');
}
// var_dump($response);
return $response['Ticket'];
}
public function getExportData($ticket) {
$url = $this->baseUrl . $this->getDataExportUrl;
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Ticket: '. $ticket
));
$output = curl_exec($ch);
return $output;
}
public function downloadFileFromUrl($url, $savePath) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$data = curl_exec ($ch);
$error = curl_error($ch);
curl_close ($ch);
// if (!is_dir($savePath) && is_writable($savePath)) {
$file = fopen($savePath, "w+");
fputs($file, $data);
fclose($file);
// } else {
// throw new \Exception('Unable to save file');
// }
}
private function _makePOSTRequest($url, $json_data) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($json_data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
}
// Login and data download url
$api = new AdformAPI();
$ticket = $api->login('example', '123546');
$exportDataResponseJson = $api->getExportData($ticket);
$exportDataResponse = json_decode($exportDataResponseJson, true);
if (empty($exportDataResponse['DataExportResult']) || $exportDataResponse['DataExportResult']['DataExportStatus'] != "Done") {
throw new \Exception('GetDataExport invalid response');
}
// Download zip
$fileDir = '/var/www/html/app-catalogue/web/export';
$fileName = 'report.zip';
$filePath = $fileDir . DIRECTORY_SEPARATOR . $fileName;
$api->downloadFileFromUrl($exportDataResponse['DataExportResult']['DataExportResultUrl'], $filePath);
// Unzip
$zip = new ZipArchive;
$res = $zip->open($filePath);
$csvFilename = '';
if ($res === true) {
for ($i = 0; $i < $zip->numFiles; $i++) {
$csvFilename = $zip->getNameIndex($i);
}
$zip->extractTo($fileDir);
$zip->close();
} else {
throw new Exception("Unable to unzip file");
}
// Parse CSV
$csvPath = $fileDir . DIRECTORY_SEPARATOR . $csvFilename;
if (is_readable($csvPath)) {
$dataCsv = file_get_contents($fileDir . DIRECTORY_SEPARATOR . $csvFilename);
$dataArr = explode("\n", $dataCsv);
$dataPacked = array();
foreach ($dataArr as $row) {
$row = str_replace(" ", "", $row);
//$row = wordwrap($row, 20, "\n", true);
$row = preg_replace('/^.{20,}?\b/s', "$0&nbsp", $row);
$row = explode("\t", $row);
$dataPacked[] = $row;
}
}
// SQL Connestion
$servername = "192.168.240.22";
$username = "liferaypublic";
$password = "liferaypublic";
$dbname = "liferay_dev";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->query("set names 'utf8'");
$sql = " INSERT INTO ho_adform_reports (`Timestamp`, `Campaign`, `Paid_Keywords`, `Natural_Search_Keywords`, `Referrer_Type`, `Referrer`, `Page`, `Order_ID`)
VALUES ";
$flag = true;
foreach($dataPacked as $rowArray) {
if($flag or count($rowArray)<= 7) { $flag = false; continue; }
$sql .= "('".implode("','", $rowArray)."'),";
}
$sql = trim($sql,",");
echo $sql; //For debug only
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
//var_dump($dataPacked);
try this - I am assuming you have sanitised the values in $dataPacked.
Note edited to addslashes just in case.
$conn->query("set names 'utf8'");
$sql = " INSERT INTO ho_adform_reports (`Timestamp`, `Campaign`, `Paid_Keywords`, `Natural_Search_Keywords`, `Referrer_Type`, `Referrer`, `Page`, `Order_ID`)
VALUES ";
$flag = true;
foreach($dataPacked as $rowArray) {
if($flag or count($rowArray)<= 7) { $flag = false; continue;}
foreach ($rowArray as $k=>$v) {
$sanitised = preg_replace("/[^[:alnum:][:space:]]/ui", '', $v);
$rowArray[$k] = addslashes(trim($sanitised));
}
$sql .= "('".implode("','", $rowArray)."'),";
}
$sql = trim($sql,",");
echo $sql; //For debug only
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();

Syntax for PHP while($row =mysql_fetch_row...?

I am trying to send SMS to multiple recipients. The code I am trying to achieve this is like this:
The problem I am facing is the message is being delivered to only the first record in the table.
Need some help, what & where I am going wrong?
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$result = mysql_query("SELECT name,mobile FROM members");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while($row = mysql_fetch_row($result)) {
$mobile=$row[1];
$name=$row[0];
$request = "";
$param['mobileno'] = "91". $mobile;
$param['message'] = "Dear $name (organisation name) wishes you a very very Happy Birthday";
$param['username'] = "username";
$param['password'] = "password";
$param['sendername'] = "sender";
foreach ($param as $key => $val ){$request .= $key . "=" . urlencode($val);
$request .= "&";}$request = substr( $request, 0, strlen( $request ) - 1 );
$url = "http://smsapi" . $request;
$ch = curl_init($url);curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
var_dump($result);exit;
curl_close( $ch );
}
You need to stick to Joomla coding standards. Don't go using mysql_* functions as they are deprecated and pose security threats.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*')
->from('members');
$db->setQuery($query);
$rows = $db->loadObjectList();
while($rows){
foreach ( $rows as $row ) {
$mobile = $row->mobile;
$name = $row->name;
}
//rest of code
}

Categories