I'm currently using a script which when someone searches for a movie on my site, it checks the MySQL db to see if the movie data exists.
If it does, it shows the search result. If it doesn't, it goes to IMDB.com, scrapes content and then inserts that data into the MySQL database.
Does anyone know from quickly looking at the code below if there's a way to quickly disable that from happening by just commenting out a line or will it require someone to go over it thoroughly?
I don't want it to go to IMDB if it doesn't see the movie data in the MySQL DB.
<?php
function PageMain() {
global $TMPL;
include('./includes/imdb.php');
$all = 'Sorry, it seems that the movie you where looking for doesn\'t exist or we don\'t have it in our database...';
$text = $_GET['a'];
$name = htmlspecialchars(urldecode($_GET['q']), ENT_QUOTES);
$per_page = 50;
$page_query = mysql_query("SELECT COUNT(id) from imdb WHERE title LIKE '%%$name%'");
$pages = ceil(mysql_result($page_query, 0) / $per_page);
$page = (isset($_GET['page']) AND (int)$_GET['page'] > 0) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
if(!empty($name)) {
$queryid = 'SELECT * FROM imdb WHERE title LIKE "%%'.$name.'%"';
if(mysql_fetch_row(mysql_query($queryid)) >= 1) {
$query = "SELECT * FROM imdb WHERE title LIKE '%%%s%%' LIMIT %d, %d;";
$query = sprintf($query, $name, $start, $per_page);
$result = mysql_query($query);
$TMPL_old = $TMPL; $TMPL = array();
$skin = new skin('search/rows'); $all = '';
while($TMPL = mysql_fetch_assoc($result)) {
if ($TMPL['votes'] == NULL) {$TMPL['votes'] = '?';}
if ($TMPL['tagline'] == NULL) {$TMPL['tagline'] = 'None';}
$TMPL['title_encoded'] = str_replace("+", "-", urlencode($TMPL['title']));
$TMPL['genre'] = '';
foreach(explode(', ', $TMPL['genres']) as $v)
$TMPL['genre'] .= ''.$v.', ';
$TMPL['actor'] = '';
foreach(explode(', ', $TMPL['actors']) as $v)
$TMPL['actor'] .= ''.$v.', ';
$all .= $skin->make();
}
//Incepe selectarea actorilor
$query_actors = "SELECT `actors` FROM `imdb` ORDER BY `id` DESC LIMIT 0,3";
$actors_result = mysql_query($query_actors);
$TMPL = array (); $skin = new skin('shared/actors'); $actors = '';
while ($TMPL = mysql_fetch_assoc($actors_result))
{
$TMPL['actor'] = '';
foreach(explode(', ', $TMPL['actors']) as $v)
$TMPL['actor'] .= ''.$v.' <br />';
$actors .= $skin->make();
}
// Incepe paginarea
$skin = new skin('shared/pagination'); $pagination = '';
if ($pages >= 1 && $page <= $pages) {
for ($x=1; $x<=$pages; $x++) {
$TMPL['pagination'] = ($x == $page) ? '<strong>'.$x.'</strong> ' : ''.$x.' ';
$pagination .= $skin->make();
}
}
$TMPL = $TMPL_old; unset($TMPL_old);
$TMPL['actors'] = $actors;
$TMPL['rows'] = $all;
$TMPL['pagination'] = $pagination;
$text = 'content';
} else {
$imdb = new Imdb();
$movieArray = $imdb->getMovieInfo(htmlEntities($_GET['q']));
if(!isset($movieArray['title_id'])) { $TMPL['rows'] = $all; } else {
$title_id = $movieArray['title_id'];
$poster = $movieArray['poster'];
$title = $movieArray['title'];
$tagline = $movieArray['tagline'];
$year = $movieArray['year'];
$release = $movieArray['release_date'];
$votes = $movieArray['rating'];
$plot = $movieArray['plot'];
$runtime = $movieArray['runtime'];
$storyline = $movieArray['storyline'];
$genres = $movieArray['genres'];
$stars = $movieArray['stars'];
$oscars = $movieArray['oscars'];
$mpaa = $movieArray['mpaa_rating'];
$country = $movieArray['country'];
$actori = implode(", ", $stars);
$genuri = implode(", ", $genres);
$countries = implode(", ", $country);
$trivia = $movieArray['trivia'];
$selectData = "SELECT * FROM `imdb` where `imdbid` = '$title_id'";
if(strlen($poster) >= 5) {
if(mysql_fetch_row(mysql_query($selectData)) === false) {
$insertData = "INSERT INTO `imdb` (`imdbid` , `poster` , `title` , `tagline` , `plot` , `year` , `release`, `country`, `runtime` , `storyline`, `genres`, `actors`, `votes`, `oscars`, `mpaa`, `trivia`) VALUES ('$title_id', 'posters/$title_id.jpg', '$title', '$tagline', '$plot', '$year', '$release', '$countries', '$runtime', '$storyline', '$genuri', '$actori', '$votes', '$oscars', '$mpaa', '$trivia')";
mysql_query($insertData);
$ch = curl_init ($poster);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.12 Safari/535.2');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$rawdata=curl_exec ($ch);
curl_close ($ch);
$fp = fopen('posters/'.$title_id.'.jpg', 'w');
fwrite($fp, $rawdata);
fclose($fp);
}
} else {
if(mysql_fetch_row(mysql_query($selectData)) === false) {
$insertData = "INSERT INTO `imdb` (`imdbid` , `poster` , `title` , `tagline` , `plot` , `year` , `release`, `country`, `runtime` , `storyline`, `genres`, `actors`, `votes`, `oscars`, `mpaa`, `trivia`) VALUES ('$title_id', 'posters/noposter.jpg', '$title', '$tagline', '$plot', '$year', '$release', '$countries', '$runtime', '$storyline', '$genuri', '$actori', '$votes', '$oscars', '$mpaa', '$trivia')";
mysql_query($insertData);
}
}
$query = "SELECT * FROM imdb WHERE title LIKE '%%%s%%' LIMIT %d;";
$query = sprintf($query, $name, 40);
$result = mysql_query($query);
$TMPL_old = $TMPL; $TMPL = array();
$skin = new skin('search/rows'); $all = '';
while($TMPL = mysql_fetch_assoc($result)) {
if ($TMPL['votes'] == NULL) {$TMPL['votes'] = '?';}
if ($TMPL['tagline'] == NULL) {$TMPL['tagline'] = 'None';}
$TMPL['title_encoded'] = str_replace("+", "-", urlencode($TMPL['title']));
$TMPL['genre'] = '';
foreach(explode(', ', $TMPL['genres']) as $v)
$TMPL['genre'] .= ''.$v.', ';
$TMPL['actor'] = '';
foreach(explode(', ', $TMPL['actors']) as $v)
$TMPL['actor'] .= ''.$v.', ';
$all .= $skin->make();
}
//Incepe selectarea actorilor
$query_actors = "SELECT `actors` FROM `imdb` ORDER BY `id` DESC LIMIT 0,3";
$actors_result = mysql_query($query_actors);
$TMPL = array (); $skin = new skin('shared/actors'); $actors = '';
while ($TMPL = mysql_fetch_assoc($actors_result))
{
$TMPL['actor'] = '';
foreach(explode(', ', $TMPL['actors']) as $v)
$TMPL['actor'] .= ''.$v.' <br />';
$actors .= $skin->make();
}
$TMPL = $TMPL_old; unset($TMPL_old);
$TMPL['actors'] = $actors;
$TMPL['rows'] = $all;
$text = 'content';
}
}
}
$TMPL['query'] = $name;
$TMPL['title'] = 'yourgamecodes.com/ - Movie - '.$name.'';
$skin = new skin("search/$text");
return $skin->make();
}
?>
This:
else {
$imdb = new Imdb();
$movieArray = $imdb->getMovieInfo(htmlEntities($_GET['q']));
You could comment out that whole else block and it would not make any more calls to imdb
Comment out the queries with INSERT
// $insertData = "INSERT INTO `imdb` (...)
// mysql_query($insertData);
Related
I have some 'else if' cases in a page. Now I want to make only a single function so that code length may be shorten.
elseif ($domain == 1 && $case == 2) {
$result = array();
foreach ($array as $data) {
$result[] = $data;
}
foreach ($result as $index) {
foreach ($index as $value) {
$resultArr[] = explode(' ', $value[0]);
}
}
$valuesArr = array();
//////********Below code is repeated in this page **************///////
$sql = "INSERT INTO LEAD_TMP_UPLOAD (LEAD_SOURCE , LAST_NAME , EMAIL , MOBILE , IVR_NUMBER , RECORDING_URL , COUNTRY , LEAD_STATUS , DEAD_REASON , PROJECT_NAME
, CUSTOMER_QUERY , DESCRIPTION , LEAD_OWNER , FOLLOW_UP_DATE , CITY_INTERESTED_IN , LOCALITY , UPLOAD_DATE , UPLOAD_BY_ID , REFERED_BY
, REFERED_LEAD_ID , SUB_BROKER_DETAIL , BUDGET , USER_ENQUIRY_TIME , LEAD_TYPE , INSERT_STATUS , PROCESSING_STATUS , UPDATED_AT , LEAD_STAGE ) values ";
foreach ($resultArr as $data) {
$lead_source = "99Acres";
$name = trim(strip_tags(str_replace('Name : ', '', $data[0]))) ;
$emailId = trim(strip_tags(str_replace(array('Email : ', 'Verified'), '', $data[1])));
$contactNo = trim(strip_tags(str_replace(array('Phone number : ', ' Verified'), '', $data[2])));
$ivr_no = ""; //null
$recording_url = ""; //null
$country = "";
$lead_status = "New";
$dead_reason = ""; //null
$project_name = trim(strip_tags($value[2]));;
$customer_query = " ";
$description = " ";
$lead_owner = "sachin.sharma";
$follow_up_date = date('Y-F-j h:i:s A'); //current date
$city_interested_in = "";
$locality = "";
$upload_date = date('Y-F-j h:i:s A'); //current date
$upload_by_id = 2;
$reffered_by = 0;
$reffered_lead_id = 0;
$sub_broker_detail = 0;
$budget = ""; //max range
$user_enquiry_time = ""; //mailbox time
$lead_type = "";
$insert_status = "";
$processing_status = "";
$updated_at = "";
$lead_stage = "cold";
$valuesArr[] .= "('$lead_source', '$name', '$emailId', '$contactNo', '$ivr_no', '$recording_url', '$country', '$lead_status', '$dead_reason', '$project_name ', '$customer_query', '$description', '$lead_owner', '$follow_up_date', '$city_interested_in', '$locality', '$upload_date', '$upload_by_id', '$reffered_by', '$reffered_lead_id', '$sub_broker_detail' , '$budget' , '$user_enquiry_time', '$lead_type', '$insert_status', '$processing_status', '$updated_at', '$lead_stage')";
}
$sql .= implode(',', $valuesArr);
echo $sql;
//////********Till Here, code is repeated in this page **************///////
}
please tell my how can i break above code into another function so that I can save my code length from same code repetition.
you mean something like this?
elseif ($domain == 1 && $case == 2) {
$result = array();
foreach ($array as $data) {
$result[] = $data;
}
foreach ($result as $index) {
foreach ($index as $value) {
$resultArr[] = explode(' ', $value[0]);
}
}
$valuesArr = array();
_insert($resultArr);
}
function _insert($resultArr){
$sql = "INSERT INTO LEAD_TMP_UPLOAD (LEAD_SOURCE , LAST_NAME , EMAIL , MOBILE , IVR_NUMBER , RECORDING_URL , COUNTRY , LEAD_STATUS , DEAD_REASON , PROJECT_NAME
, CUSTOMER_QUERY , DESCRIPTION , LEAD_OWNER , FOLLOW_UP_DATE , CITY_INTERESTED_IN , LOCALITY , UPLOAD_DATE , UPLOAD_BY_ID , REFERED_BY
, REFERED_LEAD_ID , SUB_BROKER_DETAIL , BUDGET , USER_ENQUIRY_TIME , LEAD_TYPE , INSERT_STATUS , PROCESSING_STATUS , UPDATED_AT , LEAD_STAGE ) values ";
foreach ($resultArr as $data) {
$lead_source = "99Acres";
$name = trim(strip_tags(str_replace('Name : ', '', $data[0]))) ;
$emailId = trim(strip_tags(str_replace(array('Email : ', 'Verified'), '', $data[1])));
$contactNo = trim(strip_tags(str_replace(array('Phone number : ', ' Verified'), '', $data[2])));
$ivr_no = ""; //null
$recording_url = ""; //null
$country = "";
$lead_status = "New";
$dead_reason = ""; //null
$project_name = trim(strip_tags($value[2]));;
$customer_query = " ";
$description = " ";
$lead_owner = "sachin.sharma";
$follow_up_date = date('Y-F-j h:i:s A'); //current date
$city_interested_in = "";
$locality = "";
$upload_date = date('Y-F-j h:i:s A'); //current date
$upload_by_id = 2;
$reffered_by = 0;
$reffered_lead_id = 0;
$sub_broker_detail = 0;
$budget = ""; //max range
$user_enquiry_time = ""; //mailbox time
$lead_type = "";
$insert_status = "";
$processing_status = "";
$updated_at = "";
$lead_stage = "cold";
$valuesArr[] .= "('$lead_source', '$name', '$emailId', '$contactNo', '$ivr_no', '$recording_url', '$country', '$lead_status', '$dead_reason', '$project_name ', '$customer_query', '$description', '$lead_owner', '$follow_up_date', '$city_interested_in', '$locality', '$upload_date', '$upload_by_id', '$reffered_by', '$reffered_lead_id', '$sub_broker_detail' , '$budget' , '$user_enquiry_time', '$lead_type', '$insert_status', '$processing_status', '$updated_at', '$lead_stage')";
}
$sql .= implode(',', $valuesArr);
echo $sql;
}
I have some issues with a dynamic query:
$cond = array();
if (!empty($type_contrat)) {
$cond[] = "job_offers.type_contrat = '$type_contrat'";
}
if (!empty($categorie_poste)) {
$cond[] = "job_offers.cat_poste = '$categorie_poste'";
}
if (!empty($niveau_etudes)) {
$cond[] = "job_offers.qualifications = '$niveau_etudes'";
}
if (!empty($experience)) {
$cond[] = "job_offers.experience >= '$experience'";
}
if (count($cond)) {
$query = $mysqli->query('SELECT
job_offers.ref_org,
job_offers.titre,
job_offers.qualifications,
job_offers.experience,
job_offers.cat_poste,
job_offers.type_contrat,
job_offers.taux_occupation,
job_offers.lieu_affectation,
job_offers.pays,
job_offers.url,
job_offers.date_entered,
job_offers.date_expire,
organisations.ref_org,
organisations.name_organisation
FROM job_offers,organisations
WHERE job_offers.ref_org = organisations.ref_org AND ');
$query .= implode(' AND ', $cond);
}
print_r($query);
--> result: prints only (linebreaks added for readability):
job_offers.type_contrat = '1' AND
job_offers.cat_poste = '3' AND
job_offers.qualifications = '2' AND
job_offers.experience >= '1'
and therefore no result.
You are trying to append a string to a mysqli-result object...
Check the returnvalue of the mysqli->result() function here.
Since someone is keen on removing this answer; here's your solution:
$cond = array();
if (!empty($type_contrat)) {
$cond[] = "job_offers.type_contrat = '$type_contrat'";
}
if (!empty($categorie_poste)) {
$cond[] = "job_offers.cat_poste = '$categorie_poste'";
}
if (!empty($niveau_etudes)) {
$cond[] = "job_offers.qualifications = '$niveau_etudes'";
}
if (!empty($experience)) {
$cond[] = "job_offers.experience >= '$experience'";
}
if (count($cond)) {
$query = $mysqli->query('SELECT
job_offers.ref_org,
job_offers.titre,
job_offers.qualifications,
job_offers.experience,
job_offers.cat_poste,
job_offers.type_contrat,
job_offers.taux_occupation,
job_offers.lieu_affectation,
job_offers.pays,
job_offers.url,
job_offers.date_entered,
job_offers.date_expire,
organisations.ref_org,
organisations.name_organisation
FROM job_offers,organisations
WHERE job_offers.ref_org = organisations.ref_org AND '.implode(' AND ', $cond));
}
print_r($query);
i have a module which executes two functions. the first filters and showsthe latest comments per category. the second one filters and shows the top commenters of all categories. i want to hack it in order to show the top commenters per category. for the first one there is in the backend the option to select category but for the top commenters there is not.
here is the code of the module. forgive me for its length.
class modK2CommentsHelper
{
public static function getLatestComments(&$params)
{
$mainframe = JFactory::getApplication();
$limit = $params->get('comments_limit', '5');
$user = JFactory::getUser();
$aid = $user->get('aid');
$db = JFactory::getDBO();
$cid = $params->get('category_id', NULL);
$jnow = JFactory::getDate();
$now = K2_JVERSION != '15' ? $jnow->toSql() : $jnow->toMySQL();
$nullDate = $db->getNullDate();
$model = K2Model::getInstance('Item', 'K2Model');
$componentParams = JComponentHelper::getParams('com_k2');
$query = "SELECT c.*, i.catid, i.title, i.alias, category.alias as catalias, category.name as categoryname
FROM #__k2_comments as c
LEFT JOIN #__k2_items as i ON i.id=c.itemID
LEFT JOIN #__k2_categories as category ON category.id=i.catid
WHERE i.published=1
AND ( i.publish_up = ".$db->Quote($nullDate)." OR i.publish_up <= ".$db->Quote($now)." )
AND ( i.publish_down = ".$db->Quote($nullDate)." OR i.publish_down >= ".$db->Quote($now)." )
AND i.trash=0 ";
if (K2_JVERSION != '15')
{
$query .= " AND i.access IN(".implode(',', $user->getAuthorisedViewLevels()).") ";
}
else
{
$query .= " AND i.access<={$aid} ";
}
$query .= " AND category.published=1 AND category.trash=0 ";
if (K2_JVERSION != '15')
{
$query .= " AND category.access IN(".implode(',', $user->getAuthorisedViewLevels()).") ";
}
else
{
$query .= " AND category.access<={$aid} ";
}
$query .= " AND c.published=1 ";
if ($params->get('catfilter'))
{
if (!is_null($cid))
{
if (is_array($cid))
{
JArrayHelper::toInteger($cid);
$query .= " AND i.catid IN(".implode(',', $cid).")";
}
else
{
$query .= " AND i.catid=".(int)$cid;
}
}
}
if (K2_JVERSION != '15')
{
if ($mainframe->getLanguageFilter())
{
$languageTag = JFactory::getLanguage()->getTag();
$query .= " AND category.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').") AND i.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').")";
}
}
$query .= " ORDER BY c.commentDate DESC ";
$db->setQuery($query, 0, $limit);
$rows = $db->loadObjectList();
$pattern = "#\b(https?://)?(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+\#)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\.[a-zA-Z]{2,6})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\#&=+$,%#-]+)*/?)#";
if (count($rows))
{
foreach ($rows as $row)
{
if ($params->get('commentDateFormat') == 'relative')
{
$config = JFactory::getConfig();
$now = new JDate();
if (K2_JVERSION == '30')
{
$tzoffset = new DateTimeZone(JFactory::getApplication()->getCfg('offset'));
$now->setTimezone($tzoffset);
}
else
{
$tzoffset = $config->getValue('config.offset');
$now->setOffset($tzoffset);
}
$created = new JDate($row->commentDate);
$diff = $now->toUnix() - $created->toUnix();
$dayDiff = floor($diff / 86400);
if ($dayDiff == 0)
{
if ($diff < 5)
{
$row->commentDate = JText::_('K2_JUST_NOW');
}
elseif ($diff < 60)
{
$row->commentDate = $diff.' '.JText::_('K2_SECONDS_AGO');
}
elseif ($diff < 120)
{
$row->commentDate = JText::_('K2_1_MINUTE_AGO');
}
elseif ($diff < 3600)
{
$row->commentDate = floor($diff / 60).' '.JText::_('K2_MINUTES_AGO');
}
elseif ($diff < 7200)
{
$row->commentDate = JText::_('K2_1_HOUR_AGO');
}
elseif ($diff < 86400)
{
$row->commentDate = floor($diff / 3600).' '.JText::_('K2_HOURS_AGO');
}
}
}
$row->commentText = K2HelperUtilities::wordLimit($row->commentText, $params->get('comments_word_limit'));
$row->commentText = preg_replace($pattern, '<a target="_blank" rel="nofollow" href="\0">\0</a>', $row->commentText);
$row->itemLink = urldecode(JRoute::_(K2HelperRoute::getItemRoute($row->itemID.':'.urlencode($row->alias), $row->catid.':'.urlencode($row->catalias))));
$row->link = $row->itemLink."#comment{$row->id}";
$row->catLink = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($row->catid.':'.urlencode($row->catalias))));
if ($row->userID > 0)
{
$row->userLink = JRoute::_(K2HelperRoute::getUserRoute($row->userID));
$getExistingUser = JFactory::getUser($row->userID);
$row->userUsername = $getExistingUser->username;
}
else
{
$row->userUsername = $row->userName;
}
// Switch between commenter name and username
if ($params->get('commenterName', 1) == 2)
$row->userName = $row->userUsername;
$row->userImage = '';
if ($params->get('commentAvatar'))
{
$row->userImage = K2HelperUtilities::getAvatar($row->userID, $row->commentEmail, $componentParams->get('commenterImgWidth'));
}
$comments[] = $row;
}
return $comments;
}
}
public static function getTopCommenters(&$params)
{
JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'tables');
$limit = $params->get('commenters_limit', '5');
$user = JFactory::getUser();
$aid = $user->get('aid');
$db = JFactory::getDBO();
$query = "SELECT COUNT(id) as counter, userName, userID, commentEmail FROM #__k2_comments WHERE userID > 0 AND published = 1 GROUP BY userID ORDER BY counter DESC";
$db->setQuery($query, 0, $limit);
$rows = $db->loadObjectList();
$pattern = "#\b(https?://)?(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+\#)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\.[a-zA-Z]{2,6})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\#&=+$,%#-]+)*/?)#";
$model = K2Model::getInstance('Item', 'K2Model');
$componentParams = JComponentHelper::getParams('com_k2');
if (count($rows))
{
foreach ($rows as $row)
{
if ($row->counter > 0)
{
$row->link = JRoute::_(K2HelperRoute::getUserRoute($row->userID));
if ($params->get('commenterNameOrUsername', 1) == 2)
{
$getExistingUser = JFactory::getUser($row->userID);
$row->userName = $getExistingUser->username;
}
if ($params->get('commentAvatar'))
{
$row->userImage = K2HelperUtilities::getAvatar($row->userID, $row->commentEmail, $componentParams->get('commenterImgWidth'));
}
if ($params->get('commenterLatestComment'))
{
$query = "SELECT * FROM #__k2_comments WHERE userID = ".(int)$row->userID." AND published = 1 ORDER BY commentDate DESC";
$db->setQuery($query, 0, 1);
$comment = $db->loadObject();
$item = JTable::getInstance('K2Item', 'Table');
$item->load($comment->itemID);
$category = JTable::getInstance('K2Category', 'Table');
$category->load($item->catid);
$row->latestCommentText = $comment->commentText;
$row->latestCommentText = preg_replace($pattern, '<a target="_blank" rel="nofollow" href="\0">\0</a>', $row->latestCommentText);
$row->latestCommentLink = urldecode(JRoute::_(K2HelperRoute::getItemRoute($item->id.':'.urlencode($item->alias), $item->catid.':'.urlencode($category->alias))))."#comment{$comment->id}";
$row->latestCommentDate = $comment->commentDate;
}
$commenters[] = $row;
}
}
if (isset($commenters))
return $commenters;
}
}
}
every help is appreciated. thank you very much
I have problem that my sms messages are imported with csv, then it is checked if number is ok and how long sms is. My problem is that if text messages is longer then 160 it still enters 1 in databse. But it should start counting, if it is less or equal than 160, it is 1 messages, if it is more than 160 but less or equal than 320 it is two messages and if it is more then it is 3 messages.
Page code is here:
<?php
$link = #mysql_connect("localhost", "admin", "") or die("Error: Database offline.");
mysql_select_db("database", $link);
mysql_query("SET NAMES 'utf8' ", $link);
function detect_type($smstext) {
$type = 0;
$dec_codes = array();
for ($i = 0; $i < strlen($smstext); $i++) {
$symbol = substr($smstext,$i,1);
if (!in_array(ord($symbol), $dec_codes)) { $type = 1; }
}
return $type;
}
$result_array = array();
$unic_numbers = array();
$fp = file_get_contents($_FILES['filename']['tmp_name']);
$fp = str_replace("\r\n", "\n", $fp);
$fp = str_replace("\r", "\n", $fp);
$fp = str_replace("\t", "", $fp);
$rows = explode("\n", $fp);
$imported_rows = 0;
$duplicate_rows = 0;
$error_rows = 0;
$long_rows = 0;
for ($i = 0; $i < sizeof($rows); $i++) {
$data = explode(";", $rows[$i]);
$data[1] = sms_formatNumbers($data[1]); // formating number
$userid = 78;
if(strlen($data[1]) > 9){
if($unic_numbers[$data[1]] != true ){ // unic number check
$unic_numbers[$data[1]] = true;
$imported_rows++;
$fullSMS = iconv("ISO-8859-1","UTF-8", trim($data[2])." ".trim($data[3])." ".trim($data[4]));
if(strlen($fullSMS) > 164){
$long_rows++;
}
if($_POST['action'] == 'send'){
// SMS TEXT
$smstext = str_replace("õ", "ò", $fullSMS);
$smstext = str_replace("Õ", "ò", $smstext);
$type = detect_type($smstext);
// servicegroup
$char2 = substr($data[1], 0, 2);
$char3 = substr($data[1], 0, 3);
$c1 = mysql_query("SELECT * FROM zone_info WHERE country_code = '".$char2."'", $link);
$c2 = mysql_query("SELECT * FROM zone_info WHERE country_code = '".$char3."'", $link);
if (mysql_num_rows($c1) == 1) {
$r = mysql_fetch_array($c1);
$price = $r['price'];
$z = mysql_query("SELECT * FROM zone WHERE id = ".$r['up']."", $link);
$zone = mysql_fetch_array($z);
$zone_id = $zone['id'];
$servicegroup = $zone['servicegroup'];
} else if (mysql_num_rows($c2) == 1) {
$r = mysql_fetch_array($c2);
$price = $r['price'];
$z = mysql_query("SELECT * FROM zone WHERE id = ".$r['up']."", $link);
$zone = mysql_fetch_array($z);
$zone_id = $zone['id'];
$servicegroup = $zone['servicegroup'];
}
require_once("../scripts/number.class.php");
$receiver = "00".$data[1];
$obj = new NumberClass($receiver);
$operator = $obj -> operator_code;
$country = $obj -> code;
$operator_name = $obj -> operator_name;
if(strlen($operator) > 0) {
$er = mysql_query("SELECT * FROM zone_exception WHERE country = ".$country." AND operator = ".$operator."", $link);
if (mysql_num_rows($er) == 1) {
$erand = mysql_fetch_array($er);
$price = $erand['price'];
$servicegroup = $erand['servicegroup'];
}
} else $operator_name = "-";
if ($operator_name == "-") { $servicegroup = $servicegroup; }
else {
if ($operator_name == " First Operator") $servicegroup = "90";
else if ($operator_name == "Second Operator") $servicegroup = "91";
else if ($operator_name == "Third Operator") $servicegroup = "92";
else $servicegroup = $servicegroup;
}
require_once("../core/init.mini.inc.php");
$servicegroup = UserBasedRerouting($receiver, $userid, $operator_name, $servicegroup);
$client_type ='corporative';
$sender = $data[0];
$zone_id = 11;
$client_sms_id = '0';
$client_want_report = '0';
$client_report_url = '';
$amount = 1;
$dt_delaysend = '1970-01-01 00:00:00';
$SMSsent = 0;
$SMStotal = 1;
$smstext_old = $smstext;
while($SMSsent < $SMStotal){
$sql = mysql_query("insert into sms_queue (user_id,client_type,dt_entered,sender,receiver,operator,smstext,sms_type,zone_id,client_sms_id,client_want_report,client_report_url,sms_price,amount,servicegroup,dt_delaysend) values ('$userid','$client_type','".date('Y-m-d H:i:s')."','$sender','$receiver','$operator_name','$smstext',0,'$zone_id','$client_sms_id','$client_want_report','$client_report_url','$price','$amount','$servicegroup','$dt_delaysend')", $link);
$SMSsent++;
}
}
}else{
$duplicate_rows ++;
}
}else{
$error_rows++;
}
}
$result_array['success'] = true;
$result_array['long_sms'] = $long_rows;
$result_array['send_sms'] = $imported_rows;
$result_array['error_sms'] = $error_rows;
$result_array['duplicate_sms'] = $duplicate_rows;
$result_array['action'] = $_POST['action'];
echo json_encode($result_array);
function sms_formatNumbers($number){
$number = (int)$number;
$start_code = (int)substr($number,0,4);
if($start_code < 3780 or $start_code == 3785 or $start_code > 3789){
return $number;
}else{
return '';
}
}
?>
Can someone help me out with that?
Thank you
Try
if(strlen($fullSMS) > 164){
$long_rows = ceil(strlen($fullSMS)/160);
}
instead of
if(strlen($fullSMS) > 164){
$long_rows++;
}
I'm working on a script that checks if the url already exists in the database, and if yes adds an additional -1 or -2 etc etc at the end. I found this script
But it 'd need to to check it again after adding-1. Since it may be already existing. How can I do that? I tired i this way
$query = mysql_query("SELECT * FROM posts WHERE url='$url'");
while ( $query ) {
$result = mysql_fetch_assoc($query);
$url = $result['url'];
$urlnew = $result['url'];
$oldurl = $url;
$first = 1;
$separator = '-';
while ( $urlnew == $url ) {
$url = preg_match('/(.+)'.$separator.'([0-9]+)$/', $urlnew, $match);
$urlnew = isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $url.$separator.$first;
$first++;
}
$url = $urlnew;
}
The new code above works just fine. But it checks only once. How can I make it to check untill it dose not exists in the DB?
tried adding a new sql query at the bottom after $url -$urlnew but it only breaks the function.
EDIT
Here's the correct script :D
$query = mysql_query("SELECT * FROM posts WHERE url LIKE '%".$url."%'");
if ( $query ) {
while ( $result = mysql_fetch_assoc($query) ) {
$url = $result['url'];
$urlnew = $result['url'];
$first = 1;
$separator = '-';
while ( $urlnew == $url ) {
preg_match('/(.+)'.$separator.'([0-9]+)$/', $urlnew, $match);
$urlnew = isset($match[2]) ? $match[1].$separator.($match[2] + 1) :$url.$separator.$first;
$first++;
}
}
}
$url = $urlnew;
Your code is likely vulnerable to SQL Injection. You should consider using PDO or MySQLi instead.
Here's an example of how you could do so:
$url = 'www.example.com';
$i = 0;
$max_duplicates = 100;
$query = $pdo->prepare('SELECT COUNT(id) count FROM urls WHERE url=?');
while ($i++ < $max_duplicates) {
$result = $query->execute($url);
if (!$result->fetch(PDO::FETCH_OBJ)->count)
break;
if ($i == 1) {
$url = $url . '-1';
} else {
$n = $i > 10 ? 2 : 1;
$url = substr($url, -$n) . $i;
}
}
Here's what I used for my needs
function checkLink($link, $counter=1){
global $connect;
$newLink = $link;
do{
$checkLink = mysqli_query($connect, "SELECT id FROM table WHERE link = '$newLink'");
if(mysqli_num_rows($checkLink) > 0){
$newLink = $link.'-'.$counter;
$counter++;
} else {
break;
}
} while(1);
return $newLink;
}
$link = 'www.example.com';
$uniquelink = checkLink($link);