-3

I'm writing some CRUD functions in PHP (not object oriented), and I ran into a little trouble. The function works just fine as is. Please review and read ahead for the actual issue I'm having. Here's the function:

<?php
function db_s(
            $table,
            $condition = array(),
            $limit = '',
            $order = array(),
            $group = array(),
            $return_query_string = false
) {
    $sql = '
        SELECT
            *
        FROM
            `'. $table .'`
    ';
    if (is_array($condition)) {
        if (count($condition) > 1) {
            $sql .= '
                    WHERE
                ';
            $sql .= implode(' AND ', $condition);
        }
        elseif (count($condition > 0)) { $sql .= ' WHERE '. $condition[0] .' '; }
    }
    elseif ($condition != '' && is_string($condition)) { $sql .= ' WHERE '. $condition .' '; }

    if (!empty($group)) {
        $sql .= '
                GROUP BY
            ';
        $sql .= implode(', ', $group);
    }
    if (!empty($order)) {
        $sql .= '
                ORDER BY
            ';
        $sql .= implode(', ', $order);
    }
    if ($limit != '') {
        $sql .= '
                LIMIT
                    '. $limit .'
            ';
    }
    //print '<pre>'. $sql .'</pre>';
    $query = mysql_query($sql) OR die(mysql_error() .'<p><pre>'. $sql .'</pre></p>');
    if ($return_query_string) { return $sql; }
    else { return $query; }
} // end db_s() function
?>

And here are some examples of how you would use it:

<?php
$results = db_s('users', 'active = 1');
while($row = mysql_fetch_assoc($results)) {
    // do cool stuff here
}
?>

<?php
$results = db_s('messages', array('user_id = 1512', 'date < "2014-05-01"'), 10);
while($row = mysql_fetch_assoc($results)) {
    // do cool stuff here
}
?>

<?php
$results = db_s('messages', array('user_id = 1512', 'date < "2014-05-01"'), 10, 'date DESC');
while($row = mysql_fetch_assoc($results)) {
    // do cool stuff here
}
?>

<?php
$results = db_s('posts', 'unread = 1', '', 'date ASC', 'user_id', true);
print '<pre>'; print_r($results); print '</pre>';
?>

All of this works just fine (pending any syntax errors above but the function works fine). The problem is in the way I want to use the function. As you can see above, I must first establish the $results variable. Then I have to put the whole thing into a while loop with $row = mysql_fetch_assoc($results). That seems like too much work for me. In order to really make this function useful to me, I'd really like to rewrite it so I can use it like this:

<?php
while ($row = db_s('messages', array('user_id = 1512', 'date < "2014-05-01"'), 10, 'date DESC')) {
    // do cool stuff here
}
?>

Or like this:

<?php
while ($row = db_s('users', 'active = 1')) {
    // do cool stuff here
}
?>

In order to do that, I've tried rewriting the end of the function (the part that actually returns the query), but I can't seem to get it to work correctly. I've tried something like this

    }
    //print '<pre>'. $sql .'</pre>';
    $query = mysql_query($sql) OR die(mysql_error() .'<p><pre>'. $sql .'</pre></p>');
    if ($return_query_string) { return $sql; }
    else { return mysql_fetch_array($query); }  //<--- this line is modified
} // end db_s() function
?>

But it just doesn't work like that. Unfortunately the results are... spotty... when used like this. Often it returns more results than it should, and it only spits out the first result several times... I did rewrite the while() loop so it would use the function db_s() correctly. Can anyone provided me any insight as to why it wouldn't work like this? Or perhaps, how to return the results so I can use the function as I intend to? Any help is greatly appreciated. Thanks in advance!

Armin
  • 1,736
  • 4
  • 19
  • 35
  • "results are... spotty" - What does that mean? – vascowhite Feb 06 '14 at 21:42
  • @vascowhite - Often it returns more results than it should, and it only spits out the first result several times. Can't make heads-or-tails of it. – Armin Feb 06 '14 at 21:43
  • If you can't, how are we supposed to with woolly descriptions like that? Please provide an example of expected output and an example of actual output to give us something to go on. – vascowhite Feb 06 '14 at 21:45
  • @vascowhite - you copy the code, and try it yourself on one of your own database tables. That's what you're supposed to do. I believe I've put more than enough information in this question (a lot more than most care to submit here) and should be entirely sufficient if you really want to help. If not, please move on and stop complaining that there's not enough information. There's more than enough information, you just don't want to do any work. – Armin Feb 06 '14 at 21:47
  • 2
    Actually, I did want to help and have been setting up to run your code and trying to reproduce your problem. I don't have your DB remember. However, you can get help elsewhere now. – vascowhite Feb 06 '14 at 21:50
  • 2
    @robotsushi This isn't your own private support channel. It sounds like **you** don't want to do any work. Also, please read this - [Why shouldn't I use mysql_* functions in PHP?](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – Phil Feb 06 '14 at 21:53
  • @Phil - did you see the length and detail of my question? – Armin Feb 06 '14 at 21:54
  • @robotsushi I see a bunch of code using unsupported / deprecated functions and absolutely zero examples of expected vs actual results. – Phil Feb 06 '14 at 21:54
  • 1
    "That's what you're supposed to do." Entitled much? – Paul Dessert Feb 06 '14 at 21:55
  • @relentless - I didn't think I had to explain "How to help on StackOverflow", but the guy seemed confused as to how to help. – Armin Feb 06 '14 at 21:57
  • 2
    I think you're confused as to how this works... – Paul Dessert Feb 06 '14 at 21:58
  • @Phil - You can always try it on your own table to see the expected/actual results. It's a simple copy/paste job, however, the results for me would have required me to show you all the database table structure with sample data, then the real results, then the expected results. I think I've already provided enough data for you guys to sift through. – Armin Feb 06 '14 at 21:59
  • @relentless - No, I'm not confused. – Armin Feb 06 '14 at 21:59
  • 1
    @robotsushi 'The guy' wasn't confused at all. I've been providing help here for over four years, you've been here for 3 months. I was asking for more information, so that I could help. It is usually a good idea to provide it so that you get the help you have come here looking for. Most of the detail you have given is in how you currently use the function. Expected and actual results would have helped me set up the code and a test database in my dev env to try and get you a function that works. Still it looks like you have an answer below. – vascowhite Feb 06 '14 at 22:00

1 Answers1

0

You need to get on PDO or MySQLI now. The solution would be similar or you could use the *_fetch_all() for those libraries.

For the function return:

$query = mysql_query($sql) OR die(mysql_error() .'<p><pre>'. $sql .'</pre></p>');

if($return_query_string) {
    return $sql;
} else { 
    while($result[] = mysql_fetch_array($query)) {}
    return $result;
}

Then use it like this:

foreach(db_s('users', 'active = 1') as $row) {
    //do cool stuff here
}

I'm not endorsing the function or the code concept, just answering the question.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • THANK YOU FOR HELPING! :) Hmmm, I'm not sure I fully understand the suggestion. Would I need to install MySQLi or PDO on my server? Is it necessary with your code suggestions? Or do you not recommend I use my db_s() function at all and fully utilize PDO or MySQLi? – Armin Feb 06 '14 at 21:52
  • What I posted is for mysql, however, read the big red WARNING: http://us2.php.net/manual/en/function.mysql-query.php – AbraCadaver Feb 06 '14 at 21:54
  • Thanks for your help! This was just a small part of a PHP Framework I built years ago, I have since moved on to Mobile App development and have not used PHP in a while. That explains all the new PDO and MySQLi! Thanks for the insight! You were very helpful! – Armin Feb 06 '14 at 21:56