So I have a simple query that checks a mySQL database for articles and echos the HTML code to generate my blog dynamically. The query works when I run it directly with phpMyAdmin, but when it's called from the .php file, it show "No Results". Here is the query:
SELECT * FROM article ORDER BY article_timestamp DESC LIMIT 4;
Runs fine when tested on phpMyAdmin. But when it's in my php code it doesn't. PHP code below:
<?php
// establish connection
function connect() {
$connection = mysql_connect ("localhost", "user", "password", "dbname") or die(mysql_error);
return $connection;
}
$connection = connect();
// define article variables
$article_id;
$article_title;
$article_headline;
$article_image_path;
$article_body;
$article_author;
$article_tags;
$article_timestamp;
$myquery = "SELECT * FROM article ORDER BY article_timestamp DESC LIMIT 4";
$result = mysql_query($connection, $myquery);
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_array($result)) {
$article_id = $row['article_id'];
$article_title = $row['article_title'];
$article_headline = $row['article_headline'];
$article_image_path = $row['article_image_path'];
$article_body = $row['article_body'];
$article_author = $row['article_author'];
$article_tags = $row['article_tags'];
$article_timestamp = $row['article_timestamp'];
echo "<!-- Blog Post -->
<h2>
<a href=\"post.php?id=$article_id\">$article_title</a>
</h2>
<p class=\"lead\">
by $article_author
</p>
<p>Posted on $article_timestamp</p>
<hr>
<img class=\"img-responsive\" src=\"$article_image_path\" alt=\"\">
<hr>
<p class=\"lead\">$article_headline</p>
<a class=\"btn\" style=\"border-color: #4c044d;\" href=\"post.php?id=$article_id\">Read More</a>
<hr>";
}
}
else {
echo 'No Results found';
}
mysql_close ($connection);
?>
DB connection should be working fine. I added this code:
if ($connection == false) {
echo 'whoops';
}
And the condition is never met when it's placed at various checkpoints. Can someone give me a hand? Spent hours on this and no dice. Thanks in advance.
Please change your connect function like below
$connection = mysql_connect ("localhost", "root", "redhat") or die(mysql_error());
mysql_select_db('test');
Also please use mysqli as mysql is deprecated in new versions of php
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments