PDOstatement not displaying fetched results - php

Alright so I have created a blog from scratch and mistakenly started to write it with mysql_ statements so I have gone back and rewritten it with PDO statements. I have now encountered a problem with displaying my blog post from my database.
<?php
include 'includes.php';
echo '<h3>-----------------------------------------------------</h3>';
$blogIndex = 'SELECT * FROM blog_post ORDER BY date_posted DESC';
$blogIndexstmt = $DBH->prepare($blogIndex);
$blogIndexRows = $blogIndexstmt->fetchAll();
if(!$blogIndexRows) {
echo 'No Post Yet.';
}
else {
while($blogIndexRows->nextRowset()) {
echo '<h2>' . $row['title'] . '</h2>';
$datePosted = $row['date_posted'];
echo '<p>' . gmdate('F j, Y, g:i a', $datePosted) . '</p>';
$body = substr($row['post'], 0, 300);
echo nl2br($body) . '...<br/>';
echo 'Read More | ';
echo '<a href="post_view.php?id=' . $row['id'] . '#comments">' .
$row['num_comments'] . ' comments</a>';
echo '<hr/>';
}
}
$DBH = null;
echo <<<HTML
+ New Post
HTML;
?>
It does not display anything, not even an error code. I was able to do it correctly with the mysql_ statement but I really want to learn how to do this correctly. I am just looking for a nudge in the right direction, you do now have to code it for me. Thanks for you help in advance!

Let's start from the beginning.
You don't use a prepared statement if you are not passing any parameters.
What does that mean? Simply issue PDO's query function.
It would be like this:
$query = $DBH->query('SELECT * FROM blog_post ORDER BY date_posted DESC');
If something went wrong, $DBH->query will return FALSE or PDOStatement on success. So next line is to check whether it's false:
if($query === false)
{
echo $DBH->errorCode();
}
else
{
// Everything went fine, let's fetch results
$results = $query->fetchAll(PDO::FETCH_ASSOC);
// If there are any records returned, our array won't be empty.
if(count($results))
{
// $results contains all of your records. You can now loop it with for, foreach and you don't need a while loop anymore
foreach($results as $row)
{
print_r($row);
}
}
else
{
echo "There are no records in the database table :(";
}
}

Related

Returning multiple rows from a function -- MySQL Database -- PDO

I'm working on a blog site, and over the past few days I've been cleaning it up so it uses a lot more included functions rather than inline php. So far it's been really helpful.
Right now I'm trying to use a function to get all the blogposts in the database, which are stored like this:
Previously I was doing this right in my main blog.php file, which includes all the html. That looked like this:
$stmt = $db->prepare("SELECT * FROM blog_posts ORDER BY id DESC");
$stmt->execute();
foreach($stmt as $blogPost)
{
$dateTime = date("j F, Y g:i a", (strtotime($blogPost['date_posted'])));
echo "<div class='blog-main-preview'>";
echo "<p class='blog-preview-title'>" . $blogPost['title'] . "</p>";
echo "<p id='blog-preview-date'>" . $dateTime . "</p><br>";
$post = $blogPost['post'];
$post = strip_tags($post);
$post = substr($post, 0, 200);
echo "<p id='blog-preview-post'>" . $post . "...</p><br>";
echo "<a href='blog-post.php?postid=" . $blogPost['id'] . "' id='read-more'><p>Read More</p></a><br>";
echo "</div>";
}
This worked great but I was looking to move it to a function too. I realize I could just move the whole thing to a function, I was just hoping there was a solution where I didn't have to have any of the html in the function, and it could return something with which I could run the foreach loop in the main blog.php file. Can I do this?
Edit: So to clarify, what I'm looking for is to have my blog.php page look like:
$blogPosts = getBlogPosts($db);
foreach($blogPosts as $blogPost)
{
$dateTime = date("j F, Y g:i a", (strtotime($blogPost['date_posted'])));
echo "<div class='blog-main-preview'>";
echo "<p class='blog-preview-title'>" . $blogPost['title'] . "</p>";
echo "<p id='blog-preview-date'>" . $dateTime . "</p><br>";
$post = $blogPost['post'];
$post = strip_tags($post);
$post = substr($post, 0, 200);
echo "<p id='blog-preview-post'>" . $post . "...</p><br>";
echo "<a href='blog-post.php?postid=" . $blogPost['id'] . "' id='read-more'><p>Read More</p></a><br>";
echo "</div>";
}
And the functions file will contain the function which retrieves and returns the blogPosts.
<?php
function getBlogPosts($db) {
$stmt = $db->prepare("SELECT * FROM blog_posts ORDER BY id DESC");
$stmt->execute();
// Get all results from the query as an array of associative arrays
$rows = $sth->fetchAll();
// Post-process results
// Use `&` to get a reference to each row to prevent the default
// "copy on write" behavior of PHP's arrays from detaching our
// changes from the $rows array. Without this, the updated $row[X]
// values would only be visible inside the foreach loop.
foreach ($rows as &$row) {
$row['date_posted'] = date("j F, Y g:i a", strtotime($row['date_posted']));
$row['post'] = strip_tags($row['post']);
$row['post'] = substr($row['post'], 0, 200);
}
return $rows;
}
$blogPosts = getBlogPosts($db);
foreach($blogPosts as $blogPost)
{ ?>
<div class="blog-main-preview">
<p class="blog-preview-title"><?= htmlspecialchars($blogPost['title']) ?></p>
<p id="blog-preview-date"><?= htmlspecialchars($blogPost['date_posted']) ?></p><br>
<p id="blog-preview-post"><?= htmlspecialchars($blogPost['post']) ?>...</p><br>
<p>Read More</p><br>
</div>
<?php } ?>
You can simply return $stmt from the function.
function getBlogPosts($db) {
$stmt = $db->prepare("SELECT * FROM blog_posts ORDER BY id DESC");
$stmt->execute();
return $stmt;
}
function getBlogPosts($db){
$stmt = $db->prepare("SELECT * FROM blog_posts ORDER BY id DESC");
$stmt->execute();
return $stmt->fetchAll();
}

Nested while doesn't work in PHP

I have problem with my code.
I use nested while in my code and the nested while doesn't work, only the outer while is work
I don't know where is the bug of my code.
This is the piece of my code :
$database = new mysqli('127.0.0.1', 'user', 'user', 'mini_email');
$query = 'SELECT * FROM mails';
$query2 = 'SELECT * FROM users';
$result_set = $database->query($query);
$result2 = $database->query($query2);
while ($row2 = $result2->fetch_assoc()) {
if ($row2['username'] == $_SESSION['user']) {
$id_email = $row2['id'];
}
}
if (isset($_SESSION['is_logged_in'])) {
echo('<center><font size="10">Mailing List</font></center><br><br>');
echo('<center><table border="3" bgcolor="#f0cdfa">');
echo('<tr>');
echo ('<td>No</td>');
echo ('<td>ID</td>');
echo ('<td>From</td>');
echo('<td>Subject</td>');
echo ('<td>Message</td>');
echo ('<td>Action</td>');
echo ('</tr>');
$i = 1;
while ($row = $result_set->fetch_assoc()) {
if ($row['to_user_id'] == $id_email) {
echo('<tr>');
echo ('<td>' . $i . '</td>');
echo ('<td>' . $row['id'] . '</td>');
while($row2 = $result2->fetch_assoc()){
if($row2['id']== $row['from_user_id']){
echo ('<td>' . $row2['username'] . '</td>');
}
}
echo ('<td>' . $row['subject'] . '</td>');
echo ('<td>' . $row['message'] . '</td>');
echo ('<td>View</td>');
echo ('</tr>');
$i++;
}
}
Your initial
while ($row2 = $result2->fetch_assoc()) {
is looping through all the records to the end of the set,
so looping a second time won't retrieve any further records because you're already at the end of the resultset
Resultset pointers aren't automatically reset when you initiate a new loop, but you can reset them manually using
$result2->data_seek(0);
before each subsequent loop
But iterating the point made in the comments by #Sirko you'd be better using a JOIN to make a single query
If I may help, I think you shouldn't even perform the queries when your if statement with the session returns false.
In the first lines or your script you should define a function with all this code, and write it like this :
function YourFunction()
{
if (isset($_SESSION['is_logged_in'])) {
return false;
}
// Database connection and queries
// your business
}
This will be more clean.
Next, your query doesn't seem to be correct. You get all the mails of your website, and then in a loop you check if the mail user id is the user id you have in session. Imagine the lack of performance if you have 35 000 mails in your database.
Improve your query with a WHERE statement : http://www.w3schools.com/sql/sql_where.asp
then, are you sure that $_SESSION['user'] contains an id ? I think your second if statement never returns true because of that.

How to ckeck and display an image if there is one

I would like to ask for some help because I am stuck at that problem. I have a MySQL DB and I am trying to create some kind of a blog system. The problem which occure to me is this:
I would like to check is there is an image tag if not not to display it. The system works perfect without images but it would be nice if I new where I messed it up. Here is my code up to now:
function outputStory($article, $only_snippet = FALSE){
global $conn;
if($article){
$sql = "SELECT ar.*, usr.name FROM cms_articles ar LEFT OUTER JOIN cms_users usr ON ar.author_id = usr.user_id WHERE ar.article_id = " . $article;
$result = mysql_query($sql, $conn);
if($row = mysql_fetch_array($result)){
echo "<h2>" . htmlspecialchars($row['title']) . "</h2>\n";
echo"<h5><div class='byLine'>От:" . htmlspecialchars($row['name']) . "</div>";
echo "<div class='pubdate'>";
if($row['is_published'] == 1){
echo date("F j, Y",strtotime($row['date_published']));
} else {
echo "No articles are published yet!";
}
echo "</div></h5>\n";
if ($only_snippet){
echo "<p>\n";
echo nl2br(trimBody($row['body']));
// I think I messed this statement alot but don't know how to make it work properly :S
if(hasPostImage() == true){
$getPostImage = "SELECT * FROM cms_images";
$getImgResult = mysql_query($getPostImage,$conn);
$rowImg = mysql_fetch_array($getImgResult);
echo"<img src='".$rowImg['img_src']."' alt='".$rowImg['img_desc']."'>";
} else {
echo '<img style="display:none">';
}
echo "</p>\n";
echo "<h4>More...</h4><br>\n";
} else {
echo "<p>\n";
echo nl2br($row['body']);
echo "</p>\n";
}
}
}
}
I hope the question is not silly or something else and thank you for the help in advance.
There are many ways for doing this, my first approach is to first check you are getting file in $_FILES is its okay then there is functions available in PHP to check file size means this will give you files size in bytes and height and width as well. File Size()
also getimagesize() if this criteria matches your criteria then proceed further

creating a page that displays ID info on a template

Updated with suggestion by others but still seem to be stuck.
I'm using this php code here to display info from my database using the ID. I created a link on my main page that looks like this.
<h1><?php echo $row_getDisplay['title']; ?></a></h1>
I have so when they click on the title of the article that it takes them to my php fiel which I named fetch.php and the code below is what is in there. I have built this around someone else's work. For some reason I can't get passed the first "else" statement. so I keep getting "you must select a valid location" I'm fairly new to php so I don't really understand why the code is failing.
<?php require_once('Connections/XXXXXX.php'); ?>
<?php
if (isset($_GET['id']) == false) // check if id has been set
{
echo "You must select a location"; // if not, display this error
exit;
} else {
$id = (int) $_GET['id'];
if (is_numeric($id) == false)
**{
echo "You must select a valid location.";
} else {**
mysql_select_db($database_XXXXXX, $XXXXXX);
$query = MYSQL_QUERY("SELECT * FROM news WHERE post_id ");
if (MYSQL_NUM_ROWS($query) == "1")
{
$fetch = MYSQL_FETCH_ARRAY($query); // set $fetch to have the values from the table
echo "Title: " . $fetch['title'] . "<BR>"; // output the info
echo "Blog: " . $fetch['blog_entry'] . "<BR>"; // etc...
echo "Author: " . $fetch['author'] . "<BR>"; // etc...
} else {
echo "No match in database found."; // if no match is found, display this error
}
}
}
Any help is appreciated. If you are able to find a better solution for me that would be great.
You shouldnt use $HTTP_GET_VARS its deprecated and unless its turned on it wont be populated. use $_GET instead.
if (isset($_GET['id']) == false)
Use $_GET for your if statement:
if (isset($_GET['id']) == false)
Also, you need to convert your $_GET value to an integer, because it is currently a string.
Right after that if statement above, in the else, put this:
$id = (int) $_GET['id'];
That way your is_numeric() will work properly.
Try this;
<?php
require_once('Connections/XXXXXX.php');
if (isset($_GET['id'])) // check if id has been set
{
$id = $_GET['id'];
if (is_numeric($id) == false)
{
echo "You must select a valid location.";
} else {
mysql_select_db($database_XXXXXX, $XXXXXX);
$query = MYSQL_QUERY("SELECT * FROM news WHERE locationid = 'news.post_id' ");
if (MYSQL_NUM_ROWS($query) == "1")
{
$fetch = MYSQL_FETCH_ARRAY($query); // set $fetch to have the values from the table
echo "Title: " . $fetch['title'] . "<BR>"; // output the info
echo "Blog: " . $fetch['blog_entry'] . "<BR>"; // etc...
echo "Author: " . $fetch['author'] . "<BR>"; // etc...
} else {
echo "No match in database found."; // if no match is found, display this error
}
}
}
else{
echo "You must select a location"; // if not, display this error
exit;
}
?>
Also, I need a clarification about news.post_id, from where are you grabbing this?

MySQL select works in phpMyAdmin but my PHP returns no rows with the same call

Heres my code
<?php
session_start();
include('config.php');
if(isset($_GET['search_word']))
{
// echo $_GET['search_word'] . '<br />'; // debugging
$search_word = $_GET['search_word'];
$search_word = mysql_escape_string($search_word);
$search_word_fix = str_replace(" ","%",$search_word);
$query = "SELECT * FROM article WHERE article_title LIKE '%" . $search_word . "%' AND article_live = '1' ORDER BY article_id DESC";
// echo $query . '<br />'; // debugging
$sql = mysql_query($query);
$count = mysql_num_rows($sql);
// echo $count . '<br />'; // debugging
// echo mysql_num_rows($sql) . '<br />'; // debugging
if($count > 0)
{
while($row=mysql_fetch_array($sql))
{
$msg=$row['article_title'];
$bold_word='<b>'.$search_word.'</b>';
$final_msg = str_ireplace($search_word, $bold_word, $msg);
echo $final_msg;
}
}
else
{
echo "No Results";
}
}?>
Can anyone see an issue with it? I cant pick out what is not working with this script and ive been staring at it for a while. It never makes it to the WHILE loop only the "No Results" and the count returns blank when i uncomment my debugging.
Count returning blank means your query failed for some reason.
Are you connecting to the db properly? Try using mysql_error() right after your query:
$error_msg = mysql_error();
Use mysql_real_escape_string() instead of mysql_escape_string() - it respects the character set so that you don't have UTF8 issues
If you're using this publicly, you may want to learn about using binds to eliminate the possibility of SQL injection via a library like PDO.
Here's a pretty good tutorial/introduction to PDO explaining why it's important!

Categories