Previous/next button in PHP - 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!

Related

While loop doesn't wait before displaying

In this code section, the query gets all the teachers and appends their assigned classes within the object
The weird thing is it works perfectly on local but not online, it is almost it doesn't wait for the while loop
<?php
$SID = mysqli_real_escape_string($con, htmlspecialchars($_POST["SID"], ENT_QUOTES));
$allTeachersArr = [];
$test = [];
$q = "SELECT onderwysers.*,klasse.Klas,klasse.Datum,klasse.Vak FROM `onderwysers` LEFT JOIN klasse ON onderwysers.ID = klasse.Teacher WHERE `SID` = '$SID'";
// echo $q;
$result = $con->query($q);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$subjectItem = new stdClass();
$filtered_array = [];
$isIn = false;
$var1 = $row['ID'];
$var2 = $row['Teacher'];
if (count($allTeachersArr) > 0)
foreach ($allTeachersArr as $item) {
if ($item->ID == $var1 && $item->Teacher == $var2) {
// do something
$filtered_array = $item;
$isIn = true;
}
}
if ($isIn == true) {
$notAdd = false;
// echo "updates";
$subjectItem->Klas = $row["Klas"];
$subjectItem->Datum = $row["Datum"];
$subjectItem->Vak = $row["Vak"];
foreach ($filtered_array->displaySubjects as $item) {
if ($item->Klas == $row["Klas"] && $item->Vak == $row["Vak"] && $item->Datum == $row["Datum"]) {
// do something
$filtered_array = $item;
$notAdd = true;
}
}
if ($notAdd == false) {
$temp = $filtered_array->displaySubjects;
array_push($temp, $subjectItem);
$filtered_array->displaySubjects = $temp;
}
} else {
//add new entry
$subjectItem->ID = $row["ID"];
$subjectItem->Title = $row["Title"];
$subjectItem->Name = $row["Name"];
$subjectItem->Surname = $row["Surname"];
$subjectItem->Afkorting = $row["Afkorting"];
$subjectItem->IdentityNumber = $row["IdentityNumber"];
$subjectItem->Geslag = $row["Geslag"];
$subjectItem->ContactDetails = $row["ContactDetails"];
$subjectItem->Email = $row["Email"];
$subjectItem->RegKlas = $row["RegKlas"];
$subjectItem->Status = $row["Status"];
$subjectItem->UID = $row["UID"];
$subjectItem->displaySubjects = [];
array_push($allTeachersArr, $subjectItem);
}
}
}
echo json_encode($allTeachersArr);
$con->close();
THE EXPECTED RETURNED DATA(This is local, online returns nothing)

Does not display the result of parsing

Good afternoon, please help me. At me when parsing the result of parsing is not displayed.
link my php file https://dropmefiles.com/cv4Q2
Please correct where I was wrong. Or help to rewrite a little code so that it displays the result of the parser.
Already tried all the options, it does not work in any way. My knowledge here is not enough.
1 file
part 1
function getForecastXML($cid='579432') {
$cid = "579432";
$hoffset = "4";
$appid= "d86ad74d22ce9cc528d8baee65acd408";
$lang= "ru";
$days = array();
$xml = #file_get_contents("http://api.openweathermap.org/data/2.5/forecast?id=$cid&mode=xml&appid=$appid&lang=$lang&type=like");
if ($xml===false) { return;} else {
$xml = simplexml_load_string($xml);
$cityname = (string)$xml->location->name;
$weekdays[0] = "Воскресенье";
$weekdays[1] = "Понедельник";
$weekdays[2] = "Вторник";
$weekdays[3] = "Среда";
$weekdays[4] = "Четверг";
$weekdays[5] = "Пятница";
$weekdays[6] = "Суббота";
if (count($xml->forecast->time)>0){
foreach ($xml->forecast->time as $fpart) {
$forecast = array();
$attr = $fpart->attributes();
$forecast['t']['min'] = (string)round(($fpart->temperature->attributes()->min)-273,15,PHP_ROUND_HALF_UP);
$forecast['t']['min'] = $forecast['t']['min'] > 0 ? "+".$forecast['t']['min'] : $forecast['t']['min'];
$forecast['t']['max'] = (string)round(($fpart->temperature->attributes()->max)-273,15,PHP_ROUND_HALF_UP);
$forecast['t']['max'] = $forecast['t']['max'] > 0 ? "+".$forecast['t']['max'] : $forecast['t']['max'];
$forecast['p']['min'] = (string)round($fpart->pressure->attributes()->value,0,PHP_ROUND_HALF_UP);
// $forecast['p']['max'] = (string)$fpart->PRESSURE->attributes()->max;
$forecast['w']['min'] = (string)round($fpart->windSpeed->attributes()->mps,0,PHP_ROUND_HALF_UP);
//$forecast['w']['max'] = (string)$fpart->WIND->attributes()->max;
//$forecast['w']['rumb'] = (string)$fpart->WIND->attributes()->direction;
$forecast['h']['min'] = (string)$fpart->humidity->attributes()->value;
//$forecast['h']['max'] = (string)$fpart->RELWET->attributes()->max;
$forecast['symb'] = (string)$fpart->symbol->attributes()->name;
$forecast['pict'] = (string)$fpart->symbol->attributes()->var;
$date = date('c',strtotime($hoffset.' hours',strtotime($attr['from'])));
$hour = date('H',strtotime($date));
$forecast['timestamp'] =strtotime($date);
$date = strtotime($date);
$dayofweek = date('w',$date);
$date = $weekdays[$dayofweek]." ".date('d.m',$date);
if ($forecast['timestamp'] > time()){
$days[$date][$hour] = $forecast;
}
}
} else {$days=array();}
}
//return array($cityname,$days);
return [$cityname => $days];
//echo [$cityname => $days];
}
part 2
$outputData = array();
if (count($this->forecast) > 0) {
foreach ($this->forecast as $date => $daypart) {
$outputData[] = $date;
foreach ($daypart as $dp => $data) {
$outputData[] = str_pad($dp, 2, '0', STR_PAD_LEFT);
$outputData[] = $data['symb'];
$outputData[] = $data['t']['min'];
$outputData[] = $data['t']['max'];
if (($data['p']['min']) > 0) {
$outputData[] = "Давление " . round($data['p']['min'] * 0.75006375541921) . "мм. рт. ст.";
}
}
}
} else {
$outputData[] = "В данный момент информация о погоде отсутствует";
}
echo implode(' ', $outputData);

Split results into variables after mysqli query

I have following:
if($broj_podstanica != "" && $broj_podstanica != 0) {
$uzmi_podstanice = "SELECT * FROM objekt WHERE vrsta_objekta = '2' ORDER BY sifra ASC LIMIT $broj_podstanica";
$pronasao_sve_podstanice = $db->query($uzmi_podstanice);
while($sifrePodstanica = $pronasao_sve_podstanice->fetch_assoc()) {
$sifreIzbrojane = $sifrePodstanica['sifra'] . ",";
$izbaci_zarez = explode(",", $sifreIzbrojane);
if (!isset($izbaci_zarez[0])) {
$izbaci_zarez[0] = "";
$pods0 = "";
} else {
$pods0 = $izbaci_zarez[0];
}
if (!isset($izbaci_zarez[1])) {
$izbaci_zarez[1] = "";
$pods1 = "";
} else {
$pods1 = $izbaci_zarez[1];
}
if (!isset($izbaci_zarez[2])) {
$izbaci_zarez[2] = "";
$pods2 = "";
} else {
$pods2 = $izbaci_zarez[2];
}
}
echo "1:" . $pods0;
echo "2:" . $pods1;
echo "3:" . $pods2;
echo "4:" . $pods3;
echo "5:" . $pods4;
}
Query gives me results: 30313233.
After while loop I tried to control variables $pods0, $pods1, $pods2, $pods3 and $pods4 but It gives me result for first variable only; $pods0 is 30..
Is it possible to get other values from variables?
You have some problems with your code, first of all, you do not need use isset() function, it always returns true because of the variable is exists. Secondly, if $izbaci_zarez[1] is empty you do not need to set it again with an empty value. The last thing, store the data in an array instead of a variable and it will not limit your variables count (Because of it will hard to follow) and set the values to their correct index.
if($broj_podstanica != "" && $broj_podstanica != 0) {
$uzmi_podstanice = "SELECT * FROM objekt WHERE vrsta_objekta = '2' ORDER BY sifra ASC LIMIT $broj_podstanica";
$pronasao_sve_podstanice = $db->query($uzmi_podstanice);
$i = 1;
$pods = array();
while($sifrePodstanica = $pronasao_sve_podstanice->fetch_assoc()) {
$sifreIzbrojane = $sifrePodstanica['sifra'] . ",";
$izbaci_zarez = explode(",", $sifreIzbrojane);
$pods[$i] = $izbaci_zarez[0];
$i++;
}
echo "1:" . $pods[1];
echo "2:" . $pods[2];
echo "3:" . $pods[3];
echo "4:" . $pods[4];
echo "5:" . $pods[5];
// and etc...
}

Add a number after a string, if it already exists

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

List images from directory by function

I'm using this function:
function getmyimages($qid){
$imgdir = 'modules/Projects/uploaded_project_images/'. $qid .''; // the directory, where your images are stored
$allowed_types = array('png','jpg','jpeg','gif'); // list of filetypes you want to show
$dimg = opendir($imgdir);
while($imgfile = readdir($dimg))
{
if(in_array(strtolower(substr($imgfile,-3)),$allowed_types))
{
$a_img[] = $imgfile;
sort($a_img);
reset ($a_img);
}
}
$totimg = count($a_img); // total image number
for($x=0; $x < $totimg; $x++)
{
$size = getimagesize($imgdir.'/'.$a_img[$x]);
// do whatever
$halfwidth = ceil($size[0]/2);
$halfheight = ceil($size[1]/2);
$mytest = 'name: '.$a_img[$x].' width: '.$size[0].' height: '.$size[1].'<br />'. $a_img[$x]. '';
}
return $mytest;
}
And I call this function between a while row as:
$sql_select = $db->sql_query('SELECT * from '.$prefix.'_projects WHERE topic=\''.$cid.'\'');
OpenTable();
while ($row2 = $db->sql_fetchrow($sql_select)){
$qid = $row2['qid'];
$project_query = $db->sql_query('SELECT p.uid, p.uname, p.subject, p.story, p.storyext, p.date, p.topic, p.pdate, p.materials, p.bidoptions, p.projectduration, pd.id_duration, pm.material_id, pbo.bidid, pc.cid FROM ' . $prefix . '_projects p, ' . $prefix . '_projects_duration pd, ' . $prefix . '_project_materials pm, ' . $prefix . '_project_bid_options pbo, ' . $prefix . '_project_categories pc WHERE p.topic=\''.$cid.'\' and p.qid=\''.$qid.'\' and p.bidoptions=pbo.bidid and p.materials=pm.material_id and p.projectduration=pd.id_duration');
while ($project_row = $db->sql_fetchrow($project_query)) {
//$qid = $project_row['qid'];
$uid = $project_row['uid'];
$uname = $project_row['uname'];
$subject = $project_row['subject'];
$story = $project_row['story'];
$storyext = $project_row['storyext'];
$date = $project_row['date'];
$topic = $project_row['topic'];
$pdate = $project_row['pdate'];
$materials = $project_row['materials'];
$bidoptions = $project_row['bidoptions'];
$projectduration = $project_row['projectduration'];
//Get the topic name
$topic_query = $db->sql_query('SELECT cid,title from '.$prefix.'_project_categories WHERE cid =\''.$cid.'\'');
while ($topic_row = $db->sql_fetchrow($topic_query)) {
$topic_id = $topic_row['cid'];
$topic_title = $topic_row['title'];
}
//Get the material text
$material_query = $db->sql_query('SELECT material_id,material_name from '.$prefix.'_project_materials WHERE material_id =\''.$materials.'\'');
while ($material_row = $db->sql_fetchrow($material_query)) {
$material_id = $material_row['material_id'];
$material_name = $material_row['material_name'];
}
//Get the bid methode
$bid_query = $db->sql_query('SELECT bidid,bidname from '.$prefix.'_project_bid_options WHERE bidid =\''.$bidoptions.'\'');
while ($bid_row = $db->sql_fetchrow($bid_query)) {
$bidid = $bid_row['bidid'];
$bidname = $bid_row['bidname'];
}
//Get the project duration
$duration_query = $db->sql_query('SELECT id_duration,duration_value,duration_alias from '.$prefix.'_projects_duration WHERE id_duration =\''.$projectduration.'\'');
while ($duration_row = $db->sql_fetchrow($duration_query)) {
$id_duration = $duration_row['id_duration'];
$duration_value = $duration_row['duration_value'];
$duration_alias = $duration_row['duration_alias'];
}
}
echo '<br/><b>id</b>--->' .$qid. '<br/><b>uid</b>--->' .$uid. '<br/><b>username</b>--->' .$uname. '<br/><b>subject</b>--->'.$subject. '<br/><b>story1</b>--->'.$story. '<br/><b>story2</b>--->'.$storyext. '<br/><b>postdate</b>--->'.$date. '<br/><b>categorie</b>--->'.$topic_title . '<br/><b>project start</b>--->'.$pdate. '<br/><b>materials</b>--->'.$material_name. '<br/><b>bid methode</b>--->'.$bidname. '<br/><b>project duration</b>--->'.$duration_alias.'<br /><br /><br/><b>image url</b>--->'.getmyimages($qid).'<br /><br />';
}
CloseTable();
The result outputs only the "last" file from the directories.
If I do an echo instead of a return $mytest;, it reads the whole directory but ruins the output.
You are always overwriting $mytest in your loop:
for($x=0; $x < $totimg; $x++)
{
$size = getimagesize($imgdir.'/'.$a_img[$x]);
// do whatever
$halfwidth = ceil($size[0]/2);
$halfheight = ceil($size[1]/2);
$mytest = 'name: '.$a_img[$x].' width: '.$size[0].' height: '.$size[1].'<br />'. $a_img[$x]. '';
}
return $mytest;
So after the loop, $mytest contains the last value that was generated in the loop. You might want to return an array instead:
$mytest = array();
for($x=0; $x < $totimg; $x++)
{
$size = getimagesize($imgdir.'/'.$a_img[$x]);
// do whatever
$halfwidth = ceil($size[0]/2);
$halfheight = ceil($size[1]/2);
$mytest[] = 'name: '.$a_img[$x].' width: '.$size[0].' height: '.$size[1].'<br />'. $a_img[$x]. '';
}
return $mytest;
But of course you also have to change your other function in order to deal with the returned array.

Categories