Dynamic query php/ mysql - php

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);

Related

PHP PDO Prepare select where ? Query Error

public function listeFilitreAltKategoriId($filitre,$limit,$offset) {
$sorgu = self::$db->prepare( "SELECT * FROM urun WHERE (?) LIMIT ?,?" );
$sorgu->execute(array($filitre,$limit,$offset));
return $sorgu;
}
$limit=0;
$offset=10;
$strSemt= implode(',',$semt);
$where=[];
$where[]="altkategoriid={$sorguAltMenu[ 'id' ]}";
if($strSemt!=""){
$where[]="semt IN ($strSemt)";
}
if(!empty($min) || !empty($max)){
if(!empty($min) && empty($max)){
$where[]="fiyat >= $min ";
}
if(!empty($max) && empty($min)){
$where[]="fiyat <= $max";
}
if(!empty($max) && !empty($min)){
$where[]="fiyat BETWEEN $min AND $max";
}
}
if($kur!=""){
$where[]="kur=$kur";
}
$filitre = implode(" AND ",$where);
$UrunList = ( new UrunModel() )->listeFilitreAltKategoriId($filitre,$limit,$offset);
I Use Similar to This And The Result Freezes To Zero.
This Is The Way The Query Works.
But I Wanna Make It Work Like The Master.
I know you have received a question similar to this, but I haven't solved it for 2 hours.
//$db=(new UrunModel())->database();
// $UrunList = $db->prepare( "SELECT * FROM urun WHERE ".implode(" AND ",$where)." LIMIT $limit,$offset" );
// $UrunList->execute();
$value = [
"min_limit" => $min,
"max_limit" => $max
];
$where[] = "altkategoriid = :id";
$value["id"] = $sorguAltMenu['id'];
if( !empty($min) && empty($max) ){
$where[] = "fiyat >= :min";
$value["min"] = $min;
}
if( !empty($max) && empty($min) ){
$where[] = "fiyat <= :max";
$value["max"] = $max;
}
if( !empty($max) && !empty($min) ){
$where[] = "fiyat BETWEEN :min AND :max";
$value["min"] = $min;
$value["max"] = $max;
}
if( !empty($kur) ){
$where[] = "kur = :kur";
$value["kur"] = $kur;
}
if( count($semt) ){
$place_holders = [];
$count = 1;
foreach($semt as $semt_value){
$place_holders[] = ":semt_{$count}";
$value["semt_{$count++}"] = $semt_value;
}
$place_holder_string = implode(", ", $place_holders);
$where[] = "semt IN ({$place_holder_string})";
}
$where_clause = implode(" AND ", $where);
$sql = "
SELECT *
FROM urun
WHERE {$where_clause}
LIMIT :min_limit, :max_limit
";
$query = $pdo->prepare($sql);
$query->execute($value);
while( $row = $query->fetchObject() ){
// Do something...
}

my php code is secure? php to pdo over eval function

i'm writing a php web script with mvc, but i'm concerned about code is safe.
i fear most "eval($str)", but i try a lot of php function string but nothing happened.
$a = func_get_args();
if((func_num_args()-1)%2 == 0){
$str = "";
array_shift($a);
for($i = 0;$i<sizeof($a);$i++){
if($i%2==0){
if(!is_numeric($a[$i])){
if($a[$i] == 'filter'){
$filter=1;
}
$str.= "$".stripslashes($a[$i])." = ";
}else{
$str.= 'page';
}
}else{
if($filter != 1){
if(is_numeric($a[$i])){
$str.= stripslashes($a[$i]).";";
}else{
$str.=1;
}
}else{
$arr = explode("-",$a[$i]);
$dizz = 'array(';
for($j=0;$j<sizeof($arr);$j++){
if(($j%2)==0){
$dizz .= '\''.stripslashes($arr[$j]).'\'=>';
}else{
$dizz .= '\''.stripslashes($arr[$j]).'\',';
}
}
$dizz = rtrim($dizz,',');
$dizz .= ');';
$str.= $dizz;
}
}
}
eval($str);
}
$filter = isset($filter) ? $filter : false;
$page= isset($page) ? $page: '';
$count= isset($count) ? $count: '';
if($count == ''){
switch ($process) {
case 'table':
$count = 40;
break;
case 'detailed':
$count = 3;
break;
case 'mobile':
$count = 12;
break;
default:
$count = '';
break;
}
}
if($count != ''){
if(is_numeric($count )){
if($count <=200 && $count >0){
$count = $count ;
}else{
$count = 40;
}
}else{
$count = 1;
}
}
if(!is_numeric($page)){
$page= 1;
}
to sql query->
$new_filter = "Where ";
if($filter){
foreach ($filteras $key => $value) {
$new_filter .= 'k.'.$key.'='.$value.' and ';
}
$new_filter = rtrim($new_filter,' and ');
$filter= $new_filter;
}else{
$filter= '';
}
$limit = ($limit) ? 'LIMIT 30' : '';
if($id == ''){
$where = $filter;
}else{
$where = $id;
}
$query = 'select * from kullanici as k join kisiler as ki on k.id = ki.kullanici_id join iletisim as i on k.id = i.kullanici_id '.$where.' '.$siralama.' '.$limit;
$query = $this->_db->prepare($query);
$query->execute();
example url:
profile/show/mobile/page/4/count/5/filter/echo-"'xzcxza'"-sadas-asdxc
this results:
$page = 4;$count= 5;$filter= array('echo'=>'%22%27xzcxza%27%22','sadas'=>'asdxc');

modify a query of a joomla module

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

Previous/next button in PHP

I´m pretty much entirely new to PHP, so please bear with me.
I´m trying to build a website running on a cms called Core. I'm trying to make it so that the previous/next buttons cycle through tags rather than entries. Tags are stored in a database as core_tags. Each tag has it own tag_id, which is a number. I've tried changing the excisting code for thep previous/next buttons, but it keeps giving me 'Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/core/functions/get_entry.php on line 50'.'
Any help would be greatly appreciated.
Get_entry.php:
<?php
$b = $_SERVER['REQUEST_URI'];
if($entry) {
$b = substr($b,0,strrpos($b,"/")) . "/core/";
$id = $entry;
$isPerma = true;
} else {
$b = substr($b,0,mb_strrpos($b,"/core/")+6);
$id = $_REQUEST["id"];
}
$root = $_SERVER['DOCUMENT_ROOT'] . $b;
$http = "http://" . $_SERVER['HTTP_HOST'] . substr($b,0,strlen($b)-5);
require_once($root . "user/configuration.php");
require_once($root . "themes/".$theme."/configuration.php");
require_once($root . "functions/session.php");
if(is_numeric($id)) {
$type = "entry";
} else {
$type = "page";
}
$id = secure($id);
if($type == "page") {
$data = mysql_query("SELECT p.* FROM core_pages p WHERE p.page_title = \"$id\"");
$page_clicks = 0;
while($p = mysql_fetch_array($data)) {
$url = $p["page_url"];
$path = $root . "user/pages/" . $url;
$page_clicks = $p['hits']+1;
require($path);
}
mysql_query("UPDATE core_pages p SET
p.hits = $page_clicks
WHERE p.page_title = $id");
}
if($type == "entry") {
// queries the dbase
$data_tags = mysql_query("SELECT entry_id,entry_title FROM core_entries WHERE entry_show = 1 ORDER BY entry_position DESC") or die(mysql_error());
$navArr=array();
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
function array_next_previous($array, $value) {
$index = array_search($value,$array);
//if user clicked to view the very first entry
if($value == reset($array)){
$return['prev'] = end($array);
$return['next'] = $array[$index + 1];
//if user clicked to view the very last entry
}else if($value == end($array)){
$return['prev'] = $array[$index - 1];
reset($array);
$return['next'] = current($array);
}else{
$return['next'] = $array[$index + 1];
$return['prev'] = $array[$index - 1];
}
return $return;
}
$data = mysql_query("SELECT e.* FROM core_entries e WHERE e.entry_id = $id AND e.entry_show = 1");
$entry_clicks = 0;
if(#mysql_num_rows($data) < 1) {
die("Invalid id, no entry to be shown");
}
while($e = mysql_fetch_array($data)) {
$nextPrevProject = array_next_previous($navArr,$id);
$entry_id = $e['entry_id'];
$entry_title = $e['entry_title'];
// DATE
$t = $e["entry_date"];
$y = substr($t,0,4);
$m = substr($t,5,2);
$d = substr($t,8,2);
$entry_date = date($date_format,mktime(0,0,0,$m,$d,$y));
$entry_text = $e['entry_text'];
$entry_extra1 = $e['entry_extra1'];
$entry_extra2 = $e['entry_extra2'];
$entry_client = $e['entry_client'];
$entry_position = $e['entry_position'];
$entry_hits = $e['hits']+1;
$entry_new = $e['entry_new'];
if($entry_new == 1) {
$isNew = true;
} else {
$isNew = false;
}
if($nice_permalinks) {
$entry_perma = "$http".$entry_id;
} else {
$entry_perma = "$http"."?entry=$entry_id";
}
$data_e2t = #mysql_query("SELECT e2t.tag_id FROM core_entry2tag e2t WHERE e2t.entry_id = $entry_id");
$tag_str = "";
while($e2t = #mysql_fetch_array($data_e2t)) {
$tag_id = $e2t["tag_id"];
$data_tags = #mysql_query("SELECT t.tag_text FROM core_tags t WHERE t.tag_id = $tag_id");
while($t = #mysql_fetch_array($data_tags)) {
$tag_text = $t["tag_text"];
$tag_str = $tag_str . "<a class=\"tag-link\" name=\"tag".$tag_id."\" href=\"#tag-"._encode($tag_text)."\">".$tag_text."</a>".$separator_tags;
}
}
$entry_tags = substr($tag_str,0,strlen($tag_str)-strlen($separator_tags));
$layout_path = $root . "user/uploads/" . treat_string($entry_title) . "/layout.php";
if(is_file($layout_path) && (#filesize($layout_path) > 0)) {
require($layout_path);
} else {
require($theme_path . "parts/entry.php");
}
}
mysql_query("UPDATE core_entries e SET
e.hits = $entry_hits
WHERE e.entry_id = $id");
}
if($isPerma) {
echo "<a class=\"index-link\" href=\"$http\">back to index</a>";
}
?>
You have not defined $data_entries, before using it here:
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
That is why you get the very descriptive error message.
Did you mean to use $data_tags?
Use: "SELECT p.* FROM core_pages p WHERE p.page_title = '".$id."'
Note: mysql_connect is not sql-injection save. If you use mysql_connect, change to PDO.
$data_entries is not defined on line 50, then mysql_fetch_array return an exception of null value given.
Try to change $tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC) to $tmparray = mysql_fetch_array($data_tags,MYSQL_ASSOC).
Hope this help!

How to disable this search.php file from inserting MYSQL entries?

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);

Categories