/    Sign up×
Community /Pin to ProfileBookmark

read MySQL data into array – Fatal Error: Allowed memory size exhausted

Hey I have a script which is attempting to read data from a mysql query into an array.

This array will then be looped through and each value output.

However I’m running into the following error:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 35 bytes) in C:wampwwwblogtester.php on line 14

Can anyone help me out.

Here is my code:

[code]
<?php
include (“config.php”); // includes db connection info and creates connection

$query = “SELECT name, email, comment FROM comments”;
$result = mysql_query($query) or die (“MySQL Error: Can’t run query: $query”);

$row = mysql_fetch_assoc($result);

$commentArray = array(); // Initialise array

while ($row ) // While $row exists read value into array $commentArray
{
$comment = $row[‘name’];
array_push($commentArray, $comment);
}

return $commentArray;

foreach ($commentArray as $value) { // Output each value in array.

echo $value . ‘<br />’;
}

?>
[/code]

to post a comment
PHP

8 Comments(s)

Copy linkTweet thisAlerts:
@scragarOct 26.2008 — Don't store details into an array unless necessary, your running out of ram for the script, 2 solutions:
[list=1]
  • [*]don't use so much ram, try getting rid of your 2 loops and replace them with a single loop, unset variables you don't need(especially if they have global scope) and generally clean things up.

  • [*]edit php.ini and increase the ram limit, restart apache and see if that solves your problem.
  • [/list]


    I recommend the first one, but if you can't do the second.
    Copy linkTweet thisAlerts:
    @keeps21authorOct 27.2008 — The problem was here:

    <i>
    </i>while ($row )


    It caused an infinite loop
    Copy linkTweet thisAlerts:
    @jim_kellerOct 27.2008 — Even though you identified the immediate problem of the infinite loop, following what the poster above me said, your code is still very memory inefficient. Rather than reading everything into an array, only to loop through that same array and output its values, just do the echo call right in your while ( $row = mysql_fetch_array($result) ) loop. You can get rid of the second array altogether, and it will prevent PHP from having to store all of the comments (imagine if there are 300+) in another array.
    Copy linkTweet thisAlerts:
    @keeps21authorOct 27.2008 — Just to explain why I'm creating the array. I'm trying to get my head around OOP & MVC.

    The code shown is part of a method belonging to the Comment class, which gets the info from the database.

    The function reads this info into the array

    The reason I'm storing the data in an array is so that the array can be returned by the method to be used elsewhere.

    For example it can be used by the View (in MVC) to display certain parts of the information.

    Is there a better way to do it?
    Copy linkTweet thisAlerts:
    @jim_kellerOct 27.2008 — to pass the data to another function or method, just return the $result of the mysql query. This way you're passing a reference to an object (or a resource) rather than copying all the data and sending it around. When you need to act on the result, just call mysql_fetch_array() on the returned $result.
    Copy linkTweet thisAlerts:
    @keeps21authorOct 27.2008 — Thanks for your help, however I'm still struggling with this.

    I know I'm not passing the $result variable correctly, or perhaps $result is not what I think it is.

    What i'm trying to do is return $result, the results of a query. and then loop through the results and output them onto the screen.

    Here is my revised code.
    [code=php]
    <?php
    /**
    * Filename: class.comment.php
    * Date: 22 October 2008
    **/

    // Include config.php - allows access to database.
    include('config.php');

    class Comment {

    private $in_CommentId;
    private $in_Name;
    private $in_Email;
    private $in_Comment;


    public function __construct() {

    $this->in_Comment = $comment;
    $this->in_Name = $name;
    $this->in_Email = $email;

    }

    public function addComment()
    {
    $query = "INSERT INTO comments (name, email, comment) VALUES ( '{$this->in_Name}', '{$this->in_Email}', '{$this->in_Comment}')";
    $result = mysql_query($query) or die ("MySQL Error");

    if ($result) {
    echo 'Success!';
    } else {
    echo 'Failed to add comment!';
    }
    }

    public function getComments()
    {
    $query = "SELECT name, email, comment FROM comments";
    $result = mysql_query($query) or die ("MySQL Error: Can't run query: $query");

    return $result;
    }
    }


    // call get comments function and loop through result of query.
    $in_comment = new Comment();
    $in_comment->getComments();

    while ($row = $result)
    {
    echo $row['name'] . $row['email'] . $row['comment'] ;
    }


    ?>
    [/code]
    Copy linkTweet thisAlerts:
    @scragarOct 27.2008 — huh.:
    [code=php]while (false !== ($row = mysql_fetch_assoc($result)))

    {
    echo $row['name'] . $row['email'] . $row['comment'] ;
    }[/code]

    personaly I would have not done it that way and had the class keep the reference itself, returning 1 line at a time from it's own function(or even pass a function into it using the create function method, that would be very inefficient, but it's such a cool method)
    Copy linkTweet thisAlerts:
    @keeps21authorOct 29.2008 — If anyone is interested here is what I've come up with.

    Any advice on how to improve it is very welcome.

    [code=php]
    <?php
    /**
    * Filename: class.comment.php
    * Date: 22 October 2008
    * Description: Allows you to add and display comments
    **/

    // Include config.php - allows access to database.
    include('config.php');

    class Comment {

    private $in_CommentId;
    private $in_Name;
    private $in_Email;
    private $in_Comment;

    public function __construct()
    {
    $this->in_Name = $name;
    $this->in_Email = $email;
    $this->in_Comment = $comment;
    }


    /**
    * Method: addComment()
    * Performs an sql query to insert a new comment into the database
    **/
    public function addComment()
    {
    $query = "INSERT INTO comments (name, email, comment) VALUES ( '{$this->in_Name}', '{$this->in_Email}', '{$this->in_Comment}')";
    $result = mysql_query($query) or die ("MySQL Error");

    if ($result) {
    echo 'Success!';

    } else {
    echo 'Failed to add comment!';

    }

    }


    /**
    * Method: getComments()
    * Performs an sql query to get all comments from the database
    * Comments are then added into an array and returned as $in_Comments to be displayed however you wish.
    **/
    public function getComments()
    {
    $query = "SELECT name, email, comment FROM comments";
    $result = mysql_query($query);

    $this->in_Comments = array(); // Initialise array

    while ($row = mysql_fetch_assoc($result)) // Loop through query results and add rows into array
    {
    $this->in_Comments[] = array ($row['name'], $row['email'], $row['comment']);
    }

    return $this->in_Comments;
    }

    }

    // Call get comments function and output result.
    $in_comment = new Comment;
    $in_comment->getComments();

    $comment_array = $in_comment->getComments(); // Get array from method

    $size = count($comment_array); // Get size of array

    for ($row = 0; $row < $size; $row++) // Loop through array and output values
    {
    echo $comment_array[$row][0] . $comment_array[$row][1].$comment_array[$row][2];

    echo "<br />";
    }

    ?>
    [/code]
    ×

    Success!

    Help @keeps21 spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.18,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...