I'm having some problems with PDO selecting from Database in order to generate dynamic Sitemap file based on articles (essentially pages). PHP is not throwing any errors as I don't see any errors in the error log. Here is the code.
SELECT STATEMENT SNIPPET
$q = $db->prepare("SELECT * FROM articles ORDER BY aid ASC");
$r = $q->fetchAll(PDO::FETCH_ASSOC);
FOR EACH SNIPPET + XML
foreach($r as $row) {
$format_date = date('Y-m-d', $row['date']);
$format_slug = strtolower($row['slug']);
echo '
<url>
<loc>'.$format_slug.'</loc>
<lastmod>'.$format_date.'</lastmod>
<changefreq>monthly</changefreq>
</url>
';
}
XML DATA BEFORE "FOREACH"
echo '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc></loc>
<lastmod>2017-01-27</lastmod>
<changefreq>weekly</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>contact-us</loc>
<lastmod>2017-01-27</lastmod>
<changefreq>yearly</changefreq>
</url>
';
XML DATA AFTER "FOREACH"
echo '</urlset>';
And I am using proper PHP header for the XML output at the very top of the page which is
header('Content-Type: text/xml');
So ones I navigate to the Sitemap url, the predefined data in the echo statements is returned, in this case the 2 data snippets in the BEFORE "FOREACH" part and of course the AFTER "FOREACH" is returned.
However for some odd reason no data is being fetched from the database even truth the script seems to work. Am I missing something?
You need to execute the statement.
$q = $db->prepare("SELECT * FROM articles ORDER BY aid ASC");
$q->execute();
$r = $q->fetchAll(PDO::FETCH_ASSOC);
Alternatively you can use PDO::query http://php.net/manual/en/pdo.query.php.
Have you forgotten to call Execute on statement?
Related
I'm having a trouble with SimpleXML and addChild().
I am trying to generate an order-file in XML from data in a mysql database.
I want the file to be formed like so:
<Ordreimport>
<Kunde>
<..>
<Orderline>
<data>
</orderline>
<orderline>
<data>
</orderline>
</kunde>
</ordreimport>
The problem is that the following code
$OrderXML = new SimpleXMLElement('<?xml version="1.0" encoding="ISO-8859-1"?><OrdreImport></OrdreImport>');
While ($kunderad = mysql_fetch_array($HentKunde)) {
$OrderXML->addChild('Kunde');
$KundeInfo = $OrderXML->Kunde->addChild('KundeID',''); //BD60 - Kundekort - Kundenr
$OrdreHode = $OrderXML->Kunde->addChild('OrdreHode'); //OF14 - Ordrehode
$OrdreHode= $OrderXML->Kunde->OrdreHode->addChild('OrdreLinje');
while ($olrader = mysql_fetch_array($HentOrdrelinje)) {
$OrdreLinje = $OrderXML->Kunde->OrdreHode->OrdreLinje->addChild('StatusHB'); //se over.
}
Header('Content-type: text/xml');
echo $OrderXML->asXML();
Gives the following result:
<Ordreimport>
<Kunde>
<..>
<Orderline>
<data>
<data>
</orderline>
</kunde>
</ordreimport>
Also having $OrdreHode= $OrderXML->Kunde->OrdreHode->addChild('OrdreLinje'); inside the loop, like I initually though, gives the same result, except that it also creates an empty <orderline> tag for each additional orderline in the database. Which is ALMOST correct, except all the data ends up in the first <orderline> tag.
You are using the entire XML tree for adding nodes. So the first one will be selected. Use the current generated node instead.
Further more write headers and the XML outside the loop.
while ($kunderad = mysql_fetch_array($HentKunde))
{
$Kunde = $OrderXML->addChild('Kunde');
$KundeInfo = $Kunde->addChild('KundeID', ''); //BD60 - Kundekort - Kundenr
$OrdreHode = $Kunde->addChild('OrdreHode'); //OF14 - Ordrehode
$OrdreLinje = $OrdreHode->addChild('OrdreLinje');
// execute statement to query related data rows here
while ($olrader = mysql_fetch_array($HentOrdrelinje))
{
$OrdreLinje = $OrdreLinje->addChild('StatusHB'); //se over.
}
}
Header('Content-type: text/xml');
echo $OrderXML->asXML();
Note that mysql_ functions are unsafe and obsolete in newer PHP versions. Use mysqli_ or PDO instead.
You do not show how you query the results of the line:
while ($olrader = mysql_fetch_array($HentOrdrelinje))
Without executing the statement related to the current $kunderad within each iteration of the outer loop the inner loop won't query any new datasets. I assume you actually did and cutted this out from the minimal example.
I need a Dynamic Sitemap for my Dynamic PHP SQL Website, than I searched and followed a tutorial.
But when I submit it, there is an error:
"error on line 1 at column 6: XML declaration allowed only at the start of the document"
I search about ii and I realized that this is because of the short tags of PHP
But I can´t take the Short Tags Function off, because I use that in my whole website.
Then I need another solution;
That´s my code:
<?php
header('Content-type: application/xml; charset=UTF-8');
error_reporting(0);
include "connection.php";
$hoje = date('Y-m-d');
$output = '<?xml version="1.0" encoding="UTF-8"?>';
echo $output
?>
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
// Here goes my Normal Sitemap //
// Here goes my Dynamic Sitemap //
<?php
$sql_tabela = mysql_query("SELECT * FROM imovel WHERE codigoImovel != '1' ORDER BY idImovel DESC");
$sql_tabela1 = mysql_query("SELECT * FROM prontomorar WHERE idPronto != '1' ORDER BY idPronto DESC");
$sql_tabela2 = mysql_query("SELECT * FROM construcao WHERE idConstrucao != '1' ORDER BY idConstrucao DESC");
?>
</urlset>
I tried to use that:
echo file_get_contents( "data.txt" );
with this content in "data.txt":
<?xml version="1.0" encoding="UTF-8"?>
But, this didn´t help me at all;
So, anyone can help me????
I discovered in another Forum how to solve it;
I have saved my file in a different type of file.
It should be just UTF-8 and I saved something else;
So, just save it as UTF-8 your PHP File;
I have a database driven website that I add to every day & I want to make an xml sitemap for google with php but I'm really unsure of how to do this. Using the code that I'm used to I created this:
<?php
$get_articles_sql = "SELECT * FROM articles ORDER BY added DESC";
$get_articles_res = mysqli_query($con, $get_articles_sql);
while($article = mysqli_fetch_assoc($get_articles_res)){
$article_id = $article["id"];
$article_title = $article["title"];
$article_added = $article["added"];
$article_date = date('Y-M-D', strtotime($article_added));
$article_url_title = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $article_title);
$article_url_title = strtolower(str_replace(" ","-",$article_url_title));
$list_articles .= "
<url>
<loc>http://www.website.com/article.php?id=$article_id&title=$article_url_title</loc>
<lastmod>$article_date</lastmod>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
";
?>
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.website.com</loc>
<lastmod>2005-01-01</lastmod>
<changefreq>daily</changefreq>
<priority>1.0</priority>
</url>
<?php echo $list_articles; ?>
</urlset>
However, this returns an error on the <?xml line. Is there a correct way of doing it using the code method that I'm using?
Your server probably has short tags enabled which causes the <? in the XML declaration to throw a parse error. The easiest work around is to just echo that line out.
echo '<?xml version="1.0" encoding="UTF-8"?>'
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
It also looks like you're missing the closing bracket to your while loop but I am assuming that is merely a typo.
I am trying to create sitemap.xml file and get all brands from my database. I have following code:
<?php
header("Content-type: text/xml");
echo'<?xml version=\'1.0\' encoding=\'UTF-8\'?>';
echo'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
include 'includes/modules/connections/db.php'; //database connection
$brands = mysql_query("SELECT * FROM brands WHERE brand_status = 1"); //Select all brands
$row_brands = mysql_fetch_assoc($brands);
do { ?>
<url>
<?php
//Check when brand pages was last time updated
$brand_update = mysql_query("SELECT * FROM user_history WHERE brand_id = ".$row_brands['brand_id']." ORDER BY uh_date DESC");
$row_brand_update = mysql_fetch_assoc($brand_update)
?>
<loc>http://www.example.com/brand/<? echo $row_brands['brand_url']; ?>/</loc>
<lastmod><?php echo $row_brand_update['uh_date']; ?></lastmod>
<changefreq>daily</changefreq>
<priority>0.7</priority>
</url>
<?php } while ($row_brands = mysql_fetch_assoc($brands)); ?>
</urlset>
however I get below errors. I tried many changes but always come up with different error. Anyone sees a problem in above code that cause below error?
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<br/>
<b>Warning</b>
: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in
<b>
/hermes/bosoraweb060/b2763/ipg.example/sitemap-brands.php
</b>
on line
<b>8</b>
<br/>
<url>
<br/>
<b>Warning</b>
: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in
<b>
/hermes/bosoraweb060/b2763/ipg.example/sitemap-brands.php
</b>
on line
<b>15</b>
<br/>
<loc>http://www.example.com/brand//</loc>
<lastmod/>
<changefreq>daily</changefreq>
<priority>0.7</priority>
</url>
<br/>
<b>Warning</b>
: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in
<b>
/hermes/bosoraweb060/b2763/ipg.example/sitemap-brands.php
</b>
on line
<b>22</b>
<br/>
</urlset>
Thanks a lot got help!
SWITCH TO SOMETHING BESIDES mysql_ ! Keep using mysql and the intertoobz wil pwn ur w3bs1te, srsly. That being said, I will answer your question in the context you asked it.
Your first error message, when you untangle the HTML from it, says this:
Warning : mysql_fetch_assoc(): supplied argument is not a valid MySQL
result resource in
/hermes/bosoraweb060/b2763/ipg.example/sitemap-brands.php on line 8
You can look at line 8 of your code and see that there's only one argument passed to that function. That argument was produced by this line in your code:
$brands = mysql_query("SELECT * FROM brands WHERE brand_status = 1");
So, this thing $brands that you're trying to get back from mysql_query is no good (it's not a valid MySQL result resource).
What could be wrong? Your SELECT statement has failed.
That could be because your database doesn't contain a brands table, or because it does contain a brands table but that table has no brand_status column.
It also could be because you need to call mysql_select_db("database") before you run a query. Look at this: http://www.php.net/manual/en/function.mysql-select-db.php
You should probably adjust your code to include the following lines right after your call to mysql_query(). This will cause your program to show you the error messages from MySQL itself, not just the PHP, so you can figure out what's going wrong in your SELECT.
if (0 != mysql_errno()) {
echo mysql_errno() . ": " . mysql_error(). "<br/>\n";
exit ("MySQLfailure.<br/>\n");
}
You can put this right after every query, and leave it in your production code.
I'm trying to create a sitemap that will automatically update. I've done something similiar with my RSS feed, but this sitemap refuses to work. You can view it live at http://designdeluge.com/sitemap.xml I think the main problem is that its not recognizing the PHP code. Here's the full source:
<?php
include 'includes/connection.php';
header("Content-type: text/xml");
echo '<?xml version="1.0" encoding="UTF-8" ?>';
?>
<urlset xmlns="http://www.google.com/schemas/sitemap/0.84" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/sitemap.xsd">
<url>
<loc>http://designdeluge.com/</loc>
<lastmod>2010-04-20</lastmod>
<changefreq>weekly</changefreq>
<priority>1.00</priority>
</url>
<url>
<loc>http://designdeluge.com/about.php</loc>
<lastmod>2010-04-20</lastmod>
<changefreq>never</changefreq>
<priority>0.5</priority>
</url>
<?php
$entries = mysql_query("SELECT * FROM Entries");
while($row = mysql_fetch_assoc($entries)) {
$title = stripslashes($row['title']);
$date = date("Y-m-d", strtotime($row['timestamp']));
echo "
<url>
<loc>http://designdeluge.com/".$title."</loc>
<lastmod>".$date."</lastmod>
<changefreq>never</changefreq>
<priority>0.8</priority>
</url>";
} ?>
</urlset>
The problem is that the dynamic URL's (e.g. the ones pulled from the DB) aren't being generated and the sitemap won't validate. Thanks!
EDIT: Right now, I'm just trying to get the code itself working. I have it set up as a PHP file on my local testing server. The code above is being used. Right now, nothing displays nothing on screen or in the source. I'm thinking I made a syntax error, but I can't find anything. Any and all help is appreciated!
EDIT 2: Ok, I got it sorted out guys. Apparently, I had to echo the xml declaration with PHP. The final code is posted above. Thanks for your help!
If you take a look at the sitemap.xml that's generated (using view source, in your browser, for example), you'll see this :
<?php header('Content-type: text/xml'); ?>
<?xml version="1.0" encoding="UTF-8" ?>
<urlset xmlns="http://www.google.com/schemas/sitemap/0.84" xmlns:xsi="http:/
...
The <?php, present in that output, shows that PHP code is not interpreted.
This is probably because your webserver doesn't recognize .xml as an extension of files that should contain PHP code.
At least two possible solutions :
Re-configure your server, so XML files go through the PHP interpreter (might not be such a good idea : that can cause problems with existing files ! )
Change the extension of your sitemap, to sitemap.php for example, so it's interpreted by your server.
I would add another solution :
Have a sitemap.php file, that contains the code
And use a RewriteRule so the sitemap.xml URL actually points to the sitemap.php file
With that, you'll have the sitemap.xml URL, which is nice (required ? ), but as the code will be in sitemap.php, it'll get interpreted.
See Apache's mod_rewrite.
The simplest solution is to add to your apache .htaccess file the following line after RewriteEngine On
RewriteRule ^sitemap\.xml$ sitemap.php [L]
and then simply having a file sitemap.php in your root folder that would be normally accessible via http://yoursite.com/sitemap.xml, the default URL where all search engines will firstly search.
The file sitemap.php shall start with
<?php header('Content-type: application/xml; charset=utf-8') ?>
<?php echo '<?xml version="1.0" encoding="UTF-8"?>' ?>
I've used William's code (thanks) and with a few small modifications it worked for me.
I think the line:
header("Content-type: text/xml");
should be the second line after the top <?php
Incidentally, just a small point to anyone else that copies it, but there is a single space character before the <?php in the first line - if you inadvertantly copy it as I did, you will spend a bit of time trying to figure out why the code won't work for you!
I had to tweak the MySql select statement a little bit too.
Finally, in the output, I have used a variable $domain so that this piece of code can be used as a template without the need to think about it (provided you use the same table name each time). The variabe is added to the connectdb.php file which is included to connect to the database.
Here is my working version of the William's code:
<?php
header("Content-type: text/xml");
echo '<?xml version="1.0" encoding="UTF-8" ?>';
include 'includes/connectdb.php';
?>
<urlset xmlns="http://www.google.com/schemas/sitemap/0.84" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/sitemap.xsd">
<url>
<loc>http://www.DOMAIN.co.uk/</loc>
<priority>1.00</priority>
</url>
<?php
$sql = "SELECT * FROM pages WHERE onshow = 1 ORDER BY id ASC";
$result = mysql_query($sql,$conn);
while($row = mysql_fetch_array($result))
{
$filename = stripslashes($row['filename']);
?>
<url>
<loc>http://www.<?php echo "$domain"; ?>/<?php echo "$filename" ?></loc>
<changefreq>monthly</changefreq>
<priority>0.5</priority>
</url>
<?php } ?>
</urlset>
Here is the easiest way to creating and updating sitemap.xml file.
$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
require_once('database.php');
$sitemapText = '<?xml version="1.0" encoding="UTF-8"?>
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<url>
<loc>http://ajkhub.com/</loc>
<lastmod>2021-08-18T18:32:09+00:00</lastmod>
<priority>1.00</priority>
</url>
<url>
<loc>http://ajkhub.com/includes/about.php</loc>
<lastmod>2021-08-18T18:32:09+00:00</lastmod>
<priority>0.80</priority>
</url>
<url>
<loc>http://ajkhub.com/includes/privacy-policy.php</loc>
<lastmod>2021-08-18T18:32:09+00:00</lastmod>
<priority>0.80</priority>
</url>
<url>
<loc>http://ajkhub.com/includes/termsandcondition.php</loc>
<lastmod>2021-08-18T18:32:09+00:00</lastmod>
<priority>0.80</priority>
</url>';
$sql = "SELECT * FROM page ORDER BY id DESC LIMIT 4";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$sitemapText .= ' <url>
<loc>'.$actual_link."/".$row['page'].'</loc>
<lastmod>'.date(DATE_ATOM,time()).'</lastmod>
<priority>0.80</priority>
</url>';
}
}
$sitemapText .= '</urlset>';
$sitemap = fopen("sitemap.xml", "w") or die("Unable to open file!");
fwrite($sitemap, $sitemapText);
fclose($sitemap);