I'm trying to get my function to display my categories absolute url address for example http://www.example.com/cat/sub-1/sub-2/sub-3/ But I keep getting http://www.example.com/cat//sub-3/ can some one help me correct this problem. Please be detailed as possible since I'm farily new to PHP.
Here is my PHP function
function allCategories(){
global $parent_url;
global $url;
$nodeList = array();
$tree = array();
$query = mysqli_query(database(),"SELECT * FROM categories ORDER BY parent_id, category LIKE '%more%', category ASC");
while($row = mysqli_fetch_assoc($query)){
$nodeList[$row['id']] = array_merge($row, array('children' => array()));
}
mysqli_free_result($query);
foreach($nodeList as $nodeId => &$node) {
if(!$node['parent_id'] || !array_key_exists($node['parent_id'], $nodeList)){
$tree[] = &$node;
$url = $parent_url . $node['url'];
$url = str_replace('?cat=', '', $url);
echo '<li>' . strip_tags($node['category']) . '';
} else {
$nodeList[$node['parent_id']]['children'][] = &$node;
$url = $parent_url . $node['url'];
$cat_num = array('?cat=','&sub1=','&sub2=');
$url = str_replace($cat_num, '/', $url);
echo '<li>' . strip_tags($node['category']) . '';
}
echo '</li>';
}
echo '</ol>';
unset($node);
unset($nodeList);
}
allCategories();
I suspect your query is erroring out at the MySQL level, and you don't have anything set up to tell you so (especially if warnings are turned off in the php.ini file).
Try adding something like this to the line that starts with $query:
or die( "<h1>SELECT query failed!</h1> <p>Error: " . mysqli_error( $dbc ) . "</p>" );
$dbc needs to be replaced with whatever variable holds your database connection.
Obviously, this is for debugging only. You would replace die with some error-handling function on a production server.
Related
I have a Laravel app, which the following PHP code:
public function handle()
{
$post_item->category_id = $source->category_id;
$post_item->featured = 0;
$post_item->type = Posts::TYPE_SOURCE;
$post_item->render_type = $item['render_type'];
$post_item->source_id = $source->id;
$post_item->description = is_array($item['description'])?'':$item['description'];
$post_item->featured_image = $item['featured_image'];
$post_item->video_embed_code = $item['video_embed_code'];
$post_item->dont_show_author_publisher = $source->dont_show_author_publisher;
$post_item->show_post_source = $source->show_post_source;
$post_item->show_author_box = $source->dont_show_author_publisher == 1 ? 0 : 1;
$post_item->show_author_socials = $source->dont_show_author_publisher == 1 ? 0 : 1;
$post_item->rating_box = 0;
$post_item->created_at = $item['pubDate'];
$post_item->views = 1;
$post_item->save();
$this->createTags($item['categories'], $post_item->id);
// This is where I want to add my echo
}
public function createTags($tags, $post_id)
{
$post_tags = PostTags::where('post_id', $post_id)->get();
foreach ($post_tags as $post_tag) {
Tags::where('id', $post_tag->tag_id)->delete();
}
PostTags::where('post_id', $post_id)->delete();
foreach ($tags as $tag) {
$old_tag=Tags::where('title',$tag)->first();
if(isset($old_tag))
{
$pt = new PostTags();
$pt->post_id = $post_id;
$pt->tag_id = $old_tag->id;
$pt->save();
}
else {
$new_tag = new Tags();
$new_tag->title = $tag;
$new_tag->slug = Str::slug($tag);
$new_tag->save();
$pt = new PostTags();
$pt->post_id = $post_id;
$pt->tag_id = $new_tag->id;
$pt->save();
}
}
}
Im trying to echo the the title along with the tags, right after the commented place, but it fails to provide the correct output. I was wondering if Im using the correct way or my workaround is completely wrong.
Im using this code in the commented part:
$tweet = $post_item->title . ' tags: ' . $post_item->tags;
After doing some tests, I realized that if I use
var_dump($tag);
right after
foreach ($tags as $tag)
at my createTags function, it seems that all tags are output correctly.
Im wondering if I can store all $tags inside the createTag function's foreach, under a globally accessed variable that would be used in the initial handle function echoed.
Guessing the post item model has a relation "tags" you could try this:
$tweet = $post_item->title . ' tags: ' . implode(', ', $post_item->tags->toArray());
Also if you would just like to echo the tags on the commented place, try this:
echo implode(',', $item['categories']);
try if $post_item->tags - is array then
$tweet = $post_item->title . ' tags: ' . implode(', ', $post_item->tags);
if - collection then
$tweet = $post_item->title . ' tags: ' . $post_item->tags->join(', ');
I already made my personal single thread proxy checker using php,but I couldnt make it multi-thread,some days ago,I found one checker using multi-thread on github,can someone help to change it to save the good proxies into a file (ip:port format)?
https://raw.githubusercontent.com/samuel-allan/FastProxyChecker/master/checker.php
What i have tried:
original line 91:
echo json_encode($arr);
changed to:
$json = json_decode($arr);
$good_proxie = $json['arr']['result']['proxy']['ip'];
echo "$good_proxie";
I did not checked it, but think it'll work ^_^
function CheckMultiProxy($proxies, $timeout, $proxy_type)
{
$data = array();
foreach($proxies as $proxy)
{
$parts = explode(':', trim($proxy));
$url = strtok(curPageURL(),'?');
$data[] = $url . '?ip=' . $parts[0] . "&port=" . $parts[1] . "&timeout=" . $timeout . "&proxy_type=" . $proxy_type;
}
$results = multiRequest($data);
$holder = array();
foreach($results as $result)
{
$holder[] = json_decode($result, true)["result"];
}
$arr = array("results" => $holder);
foreach ($arr['results'] as $proxy) {
if ($proxy['success']) {
file_put_contents('YOUR_FILE_HERE', $proxy['proxy']['ip'].':'.$proxy['proxy']['port'].' '.$proxy['proxy']['type'].PHP_EOL, FILE_APPEND);
}
}
echo json_encode($arr);
}
I have a database table with two columns for page URL's and URL parents, like this:
URL | Parent
Animal | (null)
Mammal | Animal
Tiger | Mammal
I'm trying to convert it to PDO. This is the original script:
$TopnavTable = 'gz_life';
$TopnavName = 'Taxon';
function get_path($node, $TopnavTable, $TopnavName) {
$result = mysql_query('SELECT Parent FROM ' . $TopnavTable . ' WHERE ' . $TopnavName . '="'.$node.'";');
$row = mysql_fetch_array($result);
$path = array();
if ($row['Parent']!='') {
$path[] = $row['Parent'];
$path = array_merge(get_path($row['Parent'], $TopnavTable, $TopnavName), $path);
}
return $path;
}
switch ($MyPage)
{
case 'ChildPage':
$TopNav = str_replace('Carnivora', '', $TopNav);
break;
default:
break;
}
$mypath = get_path($MyURL, $TopnavTable, $TopnavName);
$MyLink = $mypath;
$MyLink = str_replace('Life', '', $MyLink);
$MyDisplay = $mypath;
for($i=0;$i<count($mypath);$i++){
$TopNav = " ".$MyDisplay[$i]." >";
$That = array('<a href="Life">', '"> ', '>', '<a href="');
$This = array('<a href="/Life/">', '">', '> ', '<a href="/Life/');
$TopNav = str_replace($That, $This, $TopNav);
Someone just helped me upgrade a similar query, where the parent-child relationship is based on URL's. For example, the URL MySite/Topics/Washington/Governor should yield bread crumbs navigation links that look like this:
Topics > Washington > Governor
This is the code:
$TopnavTable = 'pox_topics';
$TopnavName = 'URL';
function get_path($dbh,$node,$TopnavTable, $TopnavName) {
$stmt = $dbh->prepare("SELECT name FROM $TopnavTable WHERE $TopnavName = ?");
$stmt->bindValue(1,$node);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt->fetch();
$path = array_merge(get_path($pdo,$row['Parent'], $TopnavTable, $TopnavName), $path);
return $path ;
}
$Path2 = explode("/", $path);
$arrlength=count($Path2);
$html =''.$Path2[0].' > ';//First Member
for($x=1;$x<$arrlength-1;$x++) {//Between first & last
$html .= ''.$Path2[$x].' > ' ;
}
$html .= '<span class="navHere"><b>'.$Path2[$x].'</b></span>'; //Last member
$html = str_replace('/'.$MySection.'/'.$MySection.'', '/'.$MySection.'', $html);
echo $html ;
I was advised to read up on hierarchical data # http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ In fact, I think that's what my original script posted at the top is based on.
Anyway, I thought I could modify the PDO script above to make it work with my hierarchical DB table, but I've been striking out, as usual.
Can anyone tell me what I need to change? (I deleted $Path2 = explode("/", $path); of course, but I never made any progress beyond that.)
I have a sitemap that's generated with PHP and actually its calling only the table retailers as below:
$query = "select * from retailers WHERE status='active' ORDER BY added DESC";
and construct as:
while ($row = mysql_fetch_array($result))
{
$i_url = SITE_URL.'loja/'.$row['slug_title'];
$year = substr($row['added'],0,4);
$month = substr($row['added'],5,2);
$day = substr($row['added'],8,2);
$i_date = ''.$year.'-'.$month.'-'.$day.'';
// you can assign whatever changefreq and priority you like
// changefreg - optional
// priority - optional
echo
'
<url>
<loc>'.$i_url.'</loc>
<lastmod>'.$i_date.'</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
';
}
The problem is, only retailers page its coming, i need to get some more 3 tables, but i can't think on a way to call and construct more things inside that, maybe a PHP condition?
Thanks to everyone for your time!
I suggest you to create a function to handle the queries or subqueries you need
Like
Main Code
while ($row = mysql_fetch_array($result))
{
$i_url = SITE_URL.'loja/'.$row['slug_title'];
$year = substr($row['added'],0,4);
$month = substr($row['added'],5,2);
$day = substr($row['added'],8,2);
$i_date = ''.$year.'-'.$month.'-'.$day.'';
$data = subquery('what i need here', 'another param');
echo
'
<url>
<loc>'.$i_url.'</loc>
<lastmod>'.$i_date.'</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
';
}
function subquery($firstparam, $secondparam)
{
$myquery = "SELECT * FROM ".$firstparam;
//more code
$result = 'my query result';
return $result;
}
With this you can call a subquery based on the main query, you can create more funcionts or create only one with different types that, can able you to do different queries in one function.
Since the tables all have the same fields we need (slug_name and added), we can just loop through each table with the same procedure, then output to sitemap.xml file.
// Our Echo Buffer
$buffer = array();
// Table Names
$tables = array( 'retailers', 'table2', 'table3', 'table4' );
// Using MySQLi, cause it's Improved.
$conn = new MySqli( 'localhost', 'user', 'pass', 'database' );
// Iterate over $tables
foreach( $tables as $table )
{
// Build Query
$query = "SELECT `slug_name`, `added` FROM $table" .
" WHERE status='active' ORDER BY added DESC";
// Get Result
$result = $conn->mysqli_query( $query );
// Iterate over Result
while( $row = $result->fetch_assoc() )
{
// Chop up the Date
$date = substr($row['added'],0,4) . '-' .
substr($row['added'],5,2) . '-' .
substr($row['added'],8,2);
// Add page details to $buffer
$buffer[] = '<url>' .
'<loc>' . SITE_URL . 'loja/' . $row['slug_title'] . '</loc>' .
'<lastmod>' . $date . '</lastmod>' .
'<changefreq>daily</changefreq>' .
'<priority>0.8</priority>' .
'</url>';
}
// Free MySQLi Result
$result->close();
}
// Output the Buffer to view. Make sure it looks good.
echo implode( "\r\n", $buffer );
// Remove the echo above and uncomment below if it looks good.
// if( ( $xml = fopen( 'sitemap.xml', "w" ) ) !== FALSE )
// {
// fwrite( $xml, implode( "\r\n", $buffer ) );
// }
The XML feed is located at: http://xml.betclick.com/odds_fr.xml
I need a php loop to echo the name of the match, the hour, and the bets options and the odds links.
The function will select and display ONLY the matchs of the day with streaming="1" and the bets type "Ftb_Mr3".
I'm new to xpath and simplexml.
Thanks in advance.
So far I have:
<?php
$xml_str = file_get_contents("http://xml.betclick.com/odds_fr.xml");
$xml = simplexml_load_string($xml_str);
// need xpath magic
$xml->xpath();
// display
?>
Xpath is pretty simple once you get the hang of it
you basically want to get every match tag with a certain attribute
//match[#streaming=1]
will work pefectly, it gets every match tag from underneath the parent tag with the attribute streaming equal to 1
And i just realised you also want matches with a bets type of "Ftb_Mr3"
//match[#streaming=1]/bets/bet[#code="Ftb_Mr3"]
This will return the bet node though, we want the match, which we know is the grandparent
//match[#streaming=1]/bets/bet[#code="Ftb_Mr3"]/../..
the two dots work like they do in file paths, and gets the match.
now to work this into your sample just change the final bit to
// need xpath magic
$nodes = $xml->xpath('//match[#streaming=1]/bets/bet[#code="Ftb_Mr3"]/../..');
foreach($nodes as $node) {
echo $node['name'].'<br/>';
}
to print all the match names.
I don't know how to work xpath really, but if you want to 'loop it', this should get you started:
<?php
$xml = simplexml_load_file("odds_fr.xml");
foreach ($xml->children() as $child)
{
foreach ($child->children() as $child2)
{
foreach ($child2->children() as $child3)
{
foreach($child3->attributes() as $a => $b)
{
echo $a,'="',$b,"\"</br>";
}
}
}
}
?>
That gets you to the 'match' tag which has the 'streaming' attribute. I don't really know what 'matches of the day' are, either, but...
It's basically right out of the w3c reference:
http://www.w3schools.com/PHP/php_ref_simplexml.asp
I am using this on a project. Scraping Beclic odds with:
<?php
$match_csv = fopen('matches.csv', 'w');
$bet_csv = fopen('bets.csv', 'w');
$xml = simplexml_load_file('http://xml.cdn.betclic.com/odds_en.xml');
$bookmaker = 'Betclick';
foreach ($xml as $sport) {
$sport_name = $sport->attributes()->name;
foreach ($sport as $event) {
$event_name = $event->attributes()->name;
foreach ($event as $match) {
$match_name = $match->attributes()->name;
$match_id = $match->attributes()->id;
$match_start_date_str = str_replace('T', ' ', $match->attributes()->start_date);
$match_start_date = strtotime($match_start_date_str);
if (!empty($match->attributes()->live_id)) {
$match_is_live = 1;
} else {
$match_is_live = 0;
}
if ($match->attributes()->streaming == 1) {
$match_is_running = 1;
} else {
$match_is_running = 0;
}
$match_row = $match_id . ',' . $bookmaker . ',' . $sport_name . ',' . $event_name . ',' . $match_name . ',' . $match_start_date . ',' . $match_is_live . ',' . $match_is_running;
fputcsv($match_csv, explode(',', $match_row));
foreach ($match as $bets) {
foreach ($bets as $bet) {
$bet_name = $bet->attributes()->name;
foreach ($bet as $choice) {
// team numbers are surrounded by %, we strip them
$choice_name = str_replace('%', '', $choice->attributes()->name);
// get the float value of odss
$odd = (float)$choice->attributes()->odd;
// concat the row to be put to csv file
$bet_row = $match_id . ',' . $bet_name . ',' . $choice_name . ',' . $odd;
fputcsv($bet_csv, explode(',', $bet_row));
}
}
}
}
}
}
fclose($match_csv);
fclose($bet_csv);
?>
Then loading the csv files into mysql. Running it once a minute, works great so far.