Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

AJAX , jquery, Multi-Level Comments narrow results per page and replys 2

Status
Not open for further replies.

MAWarGod

Programmer
Feb 15, 2002
352
US
Hi I have been working with a script I found on a tutorial.

I would like to learn how to limit the parent posts per page..

and use a collapsed link to the reply after 3.. I have attached the script, I did find a tutorial that was more or less just a source code using livejquery.. but I can not seem to manage a relationship between the two scripts.


I would think I need a function some what like I found on this other scripting

Code:
<script type="text/javascript">

	// <![CDATA[	

	$(document).ready(function(){	
	
		$('.ViewComments').livequery("click",function(e){
			
			var parent  = $(this).parent();
			var getID   =  parent.attr('id').replace('collapsed-','');
			
			var total_comments = $("#totals-"+getID).val();
						
			$("#loader-"+getID).html('<img src="loader.gif" alt="" />');
			
			$.post("view_comments.php?postId="+getID+"&totals="+total_comments, {
	
			}, function(response){
				
				$('#CommentPosted'+getID).prepend($(response).fadeIn('slow'));
				$('#collapsed-'+getID).hide();
				
			});
		});




MA WarGod

I believe if someone can think it, it can be programmed
 
what does the response variable look like?
and also you are prepending some div with an element somehow identified by the response. if you are sure that that bit works (i.e. that the response string identifies an existing dom element, then please let us know.

if the response string is intended to be html that forms the basis of a new node, then best to specify the htm data type. you will also have to attach the node first.

Code:
var newnode = $(response);
newnode.prependTo(somediv);
newnode.fadeIn('slow');
 
comments.php
Code:
<?php
/**
 * @author Marijan Å uflaj <msufflaj32@gmail.com>
 * @link [URL unfurl="true"]http://www.php4every1.com[/URL]
 */

require_once './db.php';
require_once './lib/walker.php';

class commentWalker extends walker {

    function buildComments($comments = null, $lv = 0)
    {

        if (is_null($comments))
            $comments = $this->_traced;

        if (count($comments) < 1) {

            ob_start();
?>
There are no comments to display.
<?php
            return ob_get_clean();
        }

        $lv += 1;

        $commentHtml = '';

        if ($lv <= 3)
            $commentHtml .= '<ul>';

        foreach ($comments as $comment) {

            ob_start();
?>
<div class="commentWrap">
    <p class="userTime">User <?php if (!empty($comment->self->url)) : ?>
        <a href="<?php echo $comment->self->url; ?>"><?php echo $comment->self->name; ?></a>
        <?php else : echo $comment->self->name; endif; ?> wrote on <?php echo date('F, j Y', $comment->self->date); ?>
        in <?php echo date('g:i a', $comment->self->date); ?>
    </p>
    <p class="message">
        <?php echo $comment->self->message; ?>
    </p>
    <p>
        <a href="post.php?id=<?php echo $comment->self->id; ?>" class="replayLink">Reply</a>
    </p>
</div>
<?php
            $html = ob_get_clean();

            if (!empty($comment->childs)) {
                $commentHtml .= '<li>';
                $commentHtml .= $html;
                $commentHtml .= $this->buildComments($comment->childs, $lv);
                $commentHtml .= '</li>';
            }
            else {
                $commentHtml .= '<li>';
                $commentHtml .= $html;
                $commentHtml .= '</li>';
            }
        }
        if ($lv <= 3)
            $commentHtml .= '</ul>';

        return $commentHtml;
    }
}

$sql = 'SELECT `id`, `name`, `url`, `message`, `parent`, UNIX_TIMESTAMP(`date`) '
. 'AS `date` '
. 'FROM `comments_tutor` '
. 'ORDER BY `date`';

$comments = new commentWalker($con);
echo $comments->loadResults($sql)->trace()->buildComments();
post.php
Code:
<?php
/**
 * @author Marijan Å uflaj <msufflaj32@gmail.com>
 * @link [URL unfurl="true"]http://www.php4every1.com[/URL]
 */

require_once './db.php';

$response = array(
    'error' => true,
    'msg'   => ''
);

while (true) {

    if (!isset($_POST['type'])) {
        $response['msg'] = 'You did not provide type.';
        break;
    }

    switch ($_POST['type']) {
        case 'reply' :

            if (!isset($_GET['id'])) {
                $response['msg'] = 'You did not provide comment ID.';
                break 2;
            }

            $sql = 'SELECT `name`, `id` '
            . 'FROM `comments_tutor` '
            . 'WHERE `id` = %d '
            . 'LIMIT 1';

            if (($result = mysql_query(sprintf($sql, $_GET['id']), $con)) === false) {
                $response['msg'] = 'Could not retrieve comment author.';
                break 2;
            }

            if (mysql_num_rows($result) < 1) {
                $response['msg'] = sprintf('There is not comment with ID `%s`.', $_GET['id']);
                break 2;
            }

            $name = mysql_fetch_object($result);

            $response['name'] = $name->name;
            $response['id'] = $name->id;

            break;

        case 'post' :

            if (!isset($_POST['name'])) {
                $response['msg'] = 'You did not provide name.';
                break 2;
            }

            if (!isset($_POST['email'])) {
                $response['msg'] = 'You did not provide e-mail.';
                break 2;
            }

            if (!isset($_POST['url'])) {
                $response['msg'] = 'You did not provide url.';
                break 2;
            }

            if (!isset($_POST['msg'])) {
                $response['msg'] = 'You did not provide message.';
                break 2;
            }

            if (!isset($_POST['parent'])) {
                $response['msg'] = 'You did not provide comment ID.';
                break 2;
            }

            if (!preg_match('/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/', $_POST['email'])) {
                $response['msg'] = 'E-mail not valid.';
                break 2;
            }

            if (!empty($_POST['url']) && !preg_match('#^((http|ftp|https)\:\/\/)(www\.)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?$#i', $_POST['url'])) {
                $response['msg'] = 'Url not valid.';
                break 2;
            }

            if ($_POST['parent'] > 0) {
                $sql = 'SELECT `id` '
                . 'FROM `comments_tutor` '
                . 'WHERE `id` = %d '
                . 'LIMIT 1';

                if (($result = mysql_query(sprintf($sql, $_POST['parent']), $con)) === false) {
                    $response['msg'] = 'Could not check if comment exists.';
                    break 2;
                }

                if (mysql_num_rows($result) < 1) {
                    $response['msg'] = sprintf('There is not comment with ID `%s`.', $_POST['parent']);
                    break 2;
                }
            }

            $sql = 'INSERT INTO `comments_tutor` ( '
            . '`name`, `email`, `url`, `parent`, `message`'
            . ') VALUES ( '
            . "'%s', '%s', '%s', %d, '%s'"
            . ')';

            if (mysql_query(sprintf(
                $sql,
                mysql_real_escape_string($_POST['name']),
                mysql_real_escape_string($_POST['email']),
                mysql_real_escape_string($_POST['url']),
                $_POST['parent'],
                mysql_real_escape_string($_POST['msg'])
            )) === false) {
                $response['msg'] = 'Could not insert comment.';
                break 2;
            }

            break;

        default :
            $response['msg'] = 'Invalid type.';
            break 2;
    }

    $response['error'] = false;
    $response['msg'] = 'Comment saved.';

    break;
}

echo json_encode($response);

index.php
Code:
<?php
/**
 * @author Marijan Å uflaj <msufflaj32@gmail.com>
 * @link [URL unfurl="true"]http://www.php4every1.com[/URL]
 */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Multilevel Comments</title>
        <link href="css/main.css" type="text/css" media="screen, projection" rel="stylesheet" />
    </head>

    <body>
        <div id="wrapper">
            <div id="message" style="display: none;">
            </div>
            <div id="waiting" style="display: none;">
                Please wait<br />
                <img src="images/ajax-loader.gif" title="Loader" alt="Loader" />
            </div>
            <div id="form">
                <fieldset>
                    <legend>Write your comment</legend>
                    <p>
                        <label for="name"><span class="required">*</span> Name:</label>
                        <input type="text" name="name" class="text" id="name" />
                    </p>
                    <p>
                        <label for="email"><span class="required">*</span> E-mail:</label>
                        <input type="text" name="email" class="text" id="email" />
                    </p>
                    <p>
                        <label for="url">Url:</label>
                        <input type="text" name="url" class="text" id="url" />
                    </p>
                    <p>
                        <label for="msg"><span class="required">*</span> Message:</label>
                        <textarea rows="1" cols="1" id="msg" name="msg"></textarea>
                    </p>
                    <p>
                        <input type="hidden" name="parent" id="parent" value="0" />
                        <input type="button" name="submit" id="submit" value="Post" />
                    </p>
                </fieldset>
            </div>
            <div id="comments">
            </div>
        </div>
        <script type="text/javascript" src="js/jquery/jquery-1.3.2.js"></script>
        <script type="text/javascript" src="js/ajaxSubmit.js"></script>
    </body>
</html>

walker.php
Code:
<?php
/**
 * Walker class used to build levels from provided table.
 *
 * @author Marijan Å uflaj <msufflaj32@gmail.com>
 * @link [URL unfurl="true"]http://php4every1.com[/URL]
 */
class walker
{
    /**
     * Holds results retreived from database.
     *
     * @var array
     */
    private $_results               = array();

    /**
     * MySQL connection resource
     *
     * @var resource
     */
    protected $_con                 = null;

    /**
     * Array used to map relations betwean entries.
     *
     * @var array
     */
    private $_refMap                = array();

    /**
     * Array used to save traced entries.
     *
     * @var array
     */
    protected $_traced              = array();

    /**
     * Parent field name.
     *
     * @var string
     */
    protected $_parent              = 'parent';

    /**
     * Id field name.
     *
     * @var string
     */
    protected $_id                  = 'id';




    /**
     * Constructor.
     *
     * @param resource $db MySQL database connection resource
     * @throws Exception If $db is not valid MySQL connection resource
     * @return walker Class itself
     */
    public function __construct($db)
    {
        //Is valid resource?
        if (!is_resource($db) || get_resource_type($db) !== 'mysql link')
            throw new Exception('This is not valid MySQL connection resource.');

        $this->_con = $db;
    }

    /**
     * Loads results from database.
     *
     * @param string $sql Sql to execute
     * @throws Exception If could not load results
     * @return walker Class itself
     */
    public function loadResults($sql)
    {
        $this->_results = mysql_query($sql);

        if (!$this->_results)
        	throw new Exception('Could not load result.');


        return $this;
    }

    /**
     * Creates traced entries. Constructs multidimensional array with entries and its childs/parents.
     * Each array key is an object containing two variables ($sefl and $childs). $self contains current
     * entry object retrieved from function mysql_fetch_object. $childs is new array containing what i previously said.
     *
     * @return walker Class itself
     */
    public function trace()
    {
        $temp = array();

        while (($object = mysql_fetch_object($this->_results)) !== false) {
            if ($object->{$this->_parent} > 0) {
                $trace = $this->_traceOrgin($object->{$this->_parent});
                $temp = $this->_place($trace, $object, $temp);
                $this->_refMap[$object->{$this->_id}] = $object->{$this->_parent};
            }
            else {
                $tmpObject = new stdClass();
                $tmpObject->self = $object;
                $tmpObject->childs = array();
                $temp[$object->{$this->_id}] = $tmpObject;
            }
        }

        $this->_traced = $temp;

        return $this;
    }

    /**
     * Finds orgins of an entry (build tree of ID-s so we can find where it goes.
     *
     * @param string $parent Parent ID
     * @param array $array Temp array with ID-s
     * @return array Temp array with ID-s
     */
    private function _traceOrgin($parent, $array = array())
    {
        //If ID exists in our $_refMap
        if (isset($this->_refMap[$parent])) {
        	return array_merge(
        	    array($parent),
        	    $this->_traceOrgin($this->_refMap[$parent], $array)
        	);
        }

        return array($parent);
    }

    /**
     * Finds place for comment (its dimension) and inserts it in a row.
     *
     * @param array $trace Array with entry parents ID-s
     * @param stdClass $object Entry object
     * @param array $temp Temp array
     * @return array Array with inserted row
     */
    private function _place($trace, $object, $temp = array())
    {

        //If there is no more traced ID-s then this is our spot to insert entry
        if (count($trace) === 0) {
            $tmpObject = new stdClass();
            $tmpObject->self = $object;
            $tmpObject->childs = array();
            $temp[$object->{$this->_id}] = $tmpObject;
            return $temp;
        }
        else {
            $key = array_pop($trace);
            $temp[$key]->childs = $this->_place($trace, $object, $temp[$key]->childs);
        }

        return $temp;
    }

    /**
     * Returns traced entries.
     *
     * @return array Traced entries
     */
    public function returnTraced()
    {
        return $this->_traced;
    }

    /**
     * Sets name of filds that is ID of an entry.
     *
     * @param string $field Field name
     * @throws Exception If $field is not string
     * @return walker Class itself
     */
    public function setIdField($field)
    {
        if (!is_string($field))
            throw new Exception('Field must be string.');

        $this->_id = $field;

        return $this;
    }

    /**
     * Sets name of field that is parent of an entry.
     *
     * @param string $field Field name
     * @throws Exception If $field is not string
     * @return walker Class itself
     */
    public function setParentField($field)
    {
        if (!is_string($field))
            throw new Exception('Field must be string.');

        $this->_parent = $field;

        return $this;
    }
}

main.css
Code:
@CHARSET "UTF-8";

body {
    background-color: #f0f0f0;
}

#wrapper {
    margin: 100px auto;
    width: 600px;
}

#message {
	margin-bottom: 15px;
}

#waiting {
    color: #767676;
    text-align: center;
}

.success {
    background: #a5e283;
    border: #337f09 1px solid;
    padding: 5px;
}

.error {
    background: #ea7e7e;
    border: #a71010 1px solid;
    padding: 5px;
}

/* Form */

#form fieldset {
    border: none;	
}

#form legend {
    font-weight: bold;
}

#form label {
    display: inline-block;
    width: 70px;
    vertical-align: top;
    padding-top: 1px;	
}

#form .text, #form textarea {
    width: 300px;   
}

#form textarea {
    height: 100px;	
}

#form .required {
    color: red;
    font-weight: bold;	
}

/* Comments */

#comments ul {
    margin: 0px;
    padding: 0px;
}

#comments li {
    list-style: none;
}

#comments .commentWrap p {
    margin: 0px;
    padding: 0px;	
}

#comments .userTime {
    color: #777575;	
}

#comments li ul {
    margin: 0px;
    padding: 0px;	
}

#comments li ul {
    border-left: 1px solid #ced0d0;
}

#comments li li {
    background: url('../images/connect.gif') no-repeat transparent 0px 25px;
    padding-left: 25px;
}

#comments .commentWrap {
    border: solid 1px #ccc;
    padding: 10px;
    margin: 7px 7px 7px 0px;
    background-color: #f2f2f2;
}

#comments li li .commentWrap {
    background-color: #e6e4e4;
}

#comments p.message {
    margin-top: 13px;
    margin-bottom: 15px;
}
ajaxsubmit.js
Code:
/**
 * @author Marijan Å uflaj <msufflaj32@gmail.com>
 * @link [URL unfurl="true"]http://www.php4every1.com[/URL]
 */

$(document).ready(function(){
	
	ajax = false;	
	
	loadComments();
	
	$('#submit').click(function() {
		
		if (ajax)
			return false;
		
		$('#waiting').show(500);
		$('#demoForm').hide(0);
		$('#message').hide(0);
		
		ajax = true;
		
		$.ajax({
			'type' 		: 'POST',
			'url' 		: 'post.php',
			'dataType'  : 'json',
			'data' 		: {
				'type' 		 : 'post',
				'name'		 : $('#name').val(),
				'email'		 : $('#email').val(), 
				'url'		 : $('#url').val(), 
				'msg'	 	 : $('#msg').val(), 
				'parent'	 : $('#parent').val()
			},
			'success' 	: function(data){
				$('#waiting').hide(500);
				$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
					.text(data.msg).show(500);
				
				if (data.error === false) {
					ajax = false;
					loadComments();
				}
			},
			'error' 	: function(XMLHttpRequest, textStatus, errorThrown) {
				$('#waiting').hide(500);
				$('#message').removeClass().addClass('error')
					.text('There was an error.').show(500);
				$('#demoForm').show(500);
			}
		});
		
		ajax = false;
		
		return false;
	});
	
	$('.replayLink').live('click', function() {
		
		if (ajax)
			return false;
		
		$('#waiting').show(500);
		$('#demoForm').hide(0);
		$('#message').hide(0);
		
		ajax = true;
		
		$.ajax({
			'type' 		: 'POST',
			'url' 		: $(this).attr('href'),
			'dataType'  : 'json',
			'data' 		: {
				'type' : 'reply'
			},
			'success' 	: function(data){
				$('#waiting').hide(500);
				if (data.error === true)
					$('#message').removeClass().addClass('error')
						.text(data.msg).show(500);
				else { 
					$('#form legend').text('Write reply to comment posted by ' + data.name + '.');
					$('#parent').val(data.id);
				}
			},
			'error' 	: function(XMLHttpRequest, textStatus, errorThrown) {
				$('#waiting').hide(500);
				$('#message').removeClass().addClass('error')
					.text('There was an error.').show(500);
				$('#demoForm').show(500);
			}
		});
		
		ajax = false;
		
		return false;
	});
});

function loadComments()
{
	
	$('#waiting').show(500);
	$('#message').hide(0);
	
	ajax = true;
	
	$.ajax({
		'type' 		: 'POST',
		'url' 		: 'comments.php',
		'dataType'  : 'html',
		'data' 		: {},
		'success' 	: function(data){
			$('#waiting').hide(500);
			$('#comments').html(data);
		},
		'error' 	: function(XMLHttpRequest, textStatus, errorThrown) {
			$('#waiting').hide(500);
			$('#message').removeClass().addClass('error')
				.text('There was an error.').show(500);
		}
	});
	
	ajax = false;
}

The only thing in this I am trying to use, I see that could be a existing string identifier is $lv where in the use here controls
the tag ul making the properties on the css..

Code:
<?php
            return ob_get_clean();
        }

        $lv += 1;

        $commentHtml = '';

        if ($lv <= 3)
            $commentHtml .= '<ul>';

        foreach ($comments as $comment) {

            ob_start();
?>




MA WarGod

I believe if someone can think it, it can be programmed
 
if you load up firebug you can see what the response variable looks like. add
Code:
console.log(response)
to the receiver function to get a better look at the data.

i would rather have that information before making the assumption that the tutorial code is itself incorrect.
 
also if you are planning to use this as a wp plugin then i would advise against it. some very basic wp coding constraints are fundamentally broken in the core walker class.

instead if you can say what you are trying to achieve in general then we may be able to provide more apposite help.
 
No I am not trying to use it as a wp (wordpress) plugin (I take that as), I have it plugged in to My site that started as dutch/osdate and now has become a total custom package of its own..
I do have it running on homepage of my site after I tweaked allot but I can see where if I have allot of users posting I would need to limit the results shown per page.. to save on load times and space.. let me see if I can load up firebug on it, this will be something new to Me..

My tweaks where really the input of username, email, URL, (that leads to user profile) and I added Pic that's click-able that leads to user profile.. and some changes in main.css layout.

MA WarGod

I believe if someone can think it, it can be programmed
 
here is the url of the script separated
I have firebug loaded up and am looking also.

and thank you for showing Me firebug I can see where I can use this allot!!!

MA WarGod

I believe if someone can think it, it can be programmed
 
I am finding it difficult to debug your code as your page keeps failing.

I do, however, have an ajax comments solution of my own that I could share. It does not (yet) support nested comments.
 
Yeah I think I understand your getting a email error, I have it setup for logged in users, I have now set it up so none logged in users can use it.. and Yes if you feel like sharing your work I would be interested in learning from it.. it should not fail on you, this time I am sorry I over looked that..

MA WarGod

I believe if someone can think it, it can be programmed
 
ok. I can see that the javascript is a bit screwy. it is firing off ajax requests in an unnecessary manner. and also reloading the complete comment list every submission.

i can also see that the css is a bit odd, in that the only distinguishing feature of a reply to a comment is a change in colour.

These I am sure you can fix and I don't think were the subject of your initial question.

So ... now what was the question?

I would like to learn how to limit the parent posts per page..

ok.
1. decide how many posts per page you want. Let's say 10.
2. add this to your php script
Code:
if(session_id() == '') session_start();
3. add this to your sql select
Code:
LIMIT 10 OFFSET " . $_SESSION['curpage'] * 10;
4. on delivery of the first page set the $_SESSION['curpage'] value to 1;
5. add a 'retrieve more' button to your comments section.
6. add this code to your javascript
Code:
$('#retrievemore').bind('click', function(e){
e.preventDefault();
$.getJSON( myurl, {action: 'moreposts'}, function (d) { if(d.error == false) { addComments(d.data);}});
});
7. add a check for the action variable in your receiving script and, if there and equal to moreposts, then run your sql again to deliver another 10 comments and increment your counter. output the posts either as html or, better, as json variables.
8. in your receiving javascript build new li items on to the bottom of your list ($('mycommentlist').append....) and insert the incoming data as appropriate.

 
Code:
$sql = 'SELECT `id`, `name`, `url`, `pic`, `message`, `parent`, UNIX_TIMESTAMP(`date`) '
. 'AS `date` '
. 'FROM `mydb_table`LIMIT 10 OFFSET " . $_SESSION['curpage'] * 10'
. 'ORDER BY `date`';
$comments = new commentWalker($con);
echo $comments->loadResults($sql)->trace()->buildComments();
Parse error: syntax error, unexpected T_STRING in /thepath/comments.php on line 88

MA WarGod

I believe if someone can think it, it can be programmed
 
You have no space between the offset and the order by.
I do not believe that you can reference a column by it's alias in an order by clause. But may be mistaken. Try ordering by the commentid which should always be the same as time based anyway.
You have no space between the table name and the limit clause.

But probably none of these relate to the syntax error which will have been introduced b something you have done. We do not know what line 88 is. However in php often the warning given in relation to a line is actually in relation to the line before.
 
I would guess the mismatched quotes would be causing the issue:

Code:
$sql = 'SELECT `id`, `name`, `url`, `pic`, `message`, `parent`, UNIX_TIMESTAMP(`date`) '
. 'AS `date` '
. [COLOR=white red]'[/color]FROM `mydb_table`LIMIT 10 OFFSET [COLOR=white red]"[/color] . $_SESSION['curpage'] * 10[COLOR=white red]'[/color]
. 'ORDER BY `date`';

You open with a single quote, but close with a double, and then you have a lingering single quote that neither o-ens nor closes anything.

This id very basic string construction in PHP, balance quotes, and check mismatches.


----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Code:
$sql = 'SELECT `id`, `name`, `url`, `pic`, `message`, `parent`, UNIX_TIMESTAMP(`date`) '
. 'AS `date` '
. 'FROM `mydb_table`LIMIT 10 OFFSET ' . $_SESSION['curpage'] * 10
. 'ORDER BY `date`';
$comments = new commentWalker($con);
echo $comments->loadResults($sql)->trace()->buildComments();
Fatal error: Uncaught exception 'Exception' with message 'Could not load result.' in /home/snaffa/public_html/lib/walker.php:83 Stack trace: #0 /home/snaffa/public_html/comments.php(91): walker->loadResults('SELECT `id`, `n...') #1 {main} thrown in /home/snaffa/public_html/lib/walker.php on line 83

Code:
 /**
     * Loads results from database.
     *
     * @param string $sql Sql to execute
     * @throws Exception If could not load results
     * @return walker Class itself
     */
    public function loadResults($sql)
    {
        $this->_results = mysql_query($sql);

        if (!$this->_results)
        	throw new Exception('Could not load result.');


        return $this;
    }
line 83
Code:
        	throw new Exception('Could not load result.');

its not loading from the db? or have I yet done something wrong?



MA WarGod

I believe if someone can think it, it can be programmed
 
Phil AKA Vacunita thank you so much for helping Me learn here..
trust Me I played with that for hours trying to made it work before I posted.. when I listened and saw what you posted I think I figured it out not sure if the way I phased it is making this error in walker.php or not..

MA WarGod

I believe if someone can think it, it can be programmed
 
Looks like the query isn't returning any results which throws the exception with the message.

Try echoing out the query to see how its being sent to the db.

If it looks o.k try running it directly in the DB just to make sure the generated query does in fact return results.

Code:
$sql = 'SELECT `id`, `name`, `url`, `pic`, `message`, `parent`, UNIX_TIMESTAMP(`date`) '
. 'AS `date` '
. 'FROM `mydb_table`LIMIT 10 OFFSET ' . $_SESSION['curpage'] * 10
. 'ORDER BY `date`';
[red]echo $sql;[/red]
[green]/*$comments = new commentWalker($con);
echo $comments->loadResults($sql)->trace()->buildComments();*/[/green]

I commented out the executing functions just so you don;t get the exception while debugging the query.

You can un-comment once you know the query looks and works as expected.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
do make sure that you have started the session at the start of the script
Code:
if(session_id() == '') session_start();
and as an extra step from Phil's advice do check my points above. there are errors in your sql syntax caused by lack of spaces and the fact that your limit clause is before your order clause.

Code:
$offset = isset($_SESSION['curpage]) ? $_SESSION['curpage'] * 10 : 0;
$sql = <<<SQL

SELECT 
    `id`, 
    `name`, 
    `url`, 
    `pic`, 
    `message`, 
    `parent`, 
    UNIX_TIMESTAMP(`date`) AS `date` 
FROM mydb_table
ORDER BY UNIX_TIMESTAMP(`date`) ASC
LIMIT 10 OFFSET $offset
SQL;
 
So if the result is empty? even if I just limit it with no offset or $_SESSION, ok I am stuck..

MA WarGod

I believe if someone can think it, it can be programmed
 
jpadie just saw your post hold on let Me follow your lead.. Thank You

MA WarGod

I believe if someone can think it, it can be programmed
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top