How do I diagnose a MySQL query failure in a PHP page? - php

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.

Related

Filtering XML file by ID

Hello I have a problem when I am trying to parse an XML file
I am trying to display only one song content using id for example
mysongs.php?id=0
It's supposed to show "I left my heart on Europa" song
and if mysongs.php?id=1
It's supposed to show "Oh Ganymede" song
I want use ID instead of the songs numbers
My problem is when I am using [$id] instead of the number [0] didn't work
echo $mysongs->song[$id]->title;
Please how can I fix my problem
This is my XML file content songs.xml
<album>
<song dateplayed="2011-07-24 19:40:26">
<title>I left my heart on Europa</title>
<artist>Ship of Nomads</artist>
</song>
<song dateplayed="2011-07-24 19:27:42">
<title>Oh Ganymede</title>
<artist>Beefachanga</artist>
</song>
</album>
My PHP Code below
<?php
$id = $_GET['id'];
$mysongs = simplexml_load_file('songs.xml');
echo $mysongs->song[0]->title;
?>
It's probably a type issue.
Try to echo the type of your id, unless you parse it somewhere it will be a string:
<?php
$id = $_GET['id'];
echo gettype($id);
Then, when you do $mysongs->song[$id], it's not an equivalent of $mysongs->song[0] but of $mysongs->song['0'] which is not the same index.
So, to have the expected output, you should cast it to int before using it as an index. For that, you can use either a cast ($id = (int) $_GET['id'];) or if it is not available in your PHP version intval ($id = intval($_GET['id']);
Then the final result would look like to...
<?php
$id = (int) $_GET['id'];
$mysongs = simplexml_load_file('songs.xml');
echo $mysongs->song[$id]->title;
You will need to set id as part of the column parameter within the xml files
Try code below
<album>
<song dateplayed="2011-07-24 19:40:26">
<id>1</id>
<title>I left my heart on Europa</title>
<artist>Ship of Nomads</artist>
</song>
<song dateplayed="2011-07-24 19:27:42">
<id>2</id>
<title>Oh Ganymede</title>
<artist>Beefachanga</artist>
</song>
</album>
You can obtain the result using two method below
1.) Using Direct Elements Method
The following example gets the node value of the and element in the first and second elements in the ".xml" file:
<?php
$id = $_GET['id'];
$mysongs = simplexml_load_file('songs.xml')or die("Error: Cannot create object");
//get the first record
echo $mysongs->song[0]->id;
echo $mysongs->song[0]->title;
//get the second record
echo $mysongs->song[1]->id;
echo $mysongs->song[1]->title;
?>
2.) using Element looping method
<?php
$mysongs=simplexml_load_file("songs.xml") or die("Error: Cannot create object");
foreach($mysongs->children() as $song_album) {
echo $song_album->id . ", ";
echo $song_album->title . ", ";
echo $song_album->artist . "<br>";
}
?>

Dynamic Sitemap PHP / XML

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;

php PDO fetchAll with foreach not working

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?

How to get the valid XML notation in php from DB

I have stored below mention XML in a table(MS-SQL DB).
<CUSTOMER>
<CUSTOMERDATA>
<USERID>12691</USERID>
<USERCODE>FFRD991</USERCODE>
<MOBILENO>5645353443</MOBILENO>
<EMAILID>jhfghfghgf#sdf.fh</EMAILID>
<FIRSTNAME>ggdg</FIRSTNAME>
<MIDDLENAME>dfgdfgdf</MIDDLENAME>
<LASTNAME>gdfgdf</LASTNAME>
<ADDRESS></ADDRESS>
<CITY></CITY>
<PINCODE></PINCODE>
<STATENAME></STATENAME>
<SOURCE>Others</SOURCE>
<CREATEDATE>2015-12-01</CREATEDATE>
<STATUS></STATUS>
</CUSTOMERDATA>
</CUSTOMER>
Now I want to fetch this record by php using the following code :
$query = "Select xml_rec from tbl_node where UserId = 12691";
$result = sqlsrv_query($this->db->conn_id, $query);
$row = sqlsrv_fetch_object($result);
//// OR
$row = sqlsrv_fetch_array($result , SQLSRV_FETCH_ASSOC);
echo $row['xml_rec'];
I am getting the following wrong XML . Please note the blank tags.
<CUSTOMER>
<CUSTOMERDATA>
<USERID>12691</USERID>
<USERCODE>FFRD991</USERCODE>
<MOBILENO>5645353443</MOBILENO>
<EMAILID>jhfghfghgf#sdf.fh</EMAILID>
<FIRSTNAME>ggdg</FIRSTNAME>
<MIDDLENAME>dfgdfgdf</MIDDLENAME>
<LASTNAME>gdfgdf</LASTNAME>
<ADDRESS/>
<CITY/>
<PINCODE/>
<STATENAME/>
<SOURCE>Others</SOURCE>
<CREATEDATE>2015-12-01</CREATEDATE>
<STATUS/>
</CUSTOMERDATA>
</CUSTOMER>
How to fix this to show the proper XML ? Thanks for your valuable time.
You don't really use any xml-processing functions here, you simply retrieve a string and display it. The most likely cause of your problem was that some time when you stored this data in your DB, the empty tags got processed from the
<tag></tag>
form into
<tag />
form.
You can check this by connecting to your DB directly (without PHP) and running the query manually.
In any case, as lad2025 pointed out, the two ways of writing empty tags are equivalent so it shouldn't matter for your application.

Creating an XML sitemap with PHP

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

Categories