|
Posted by Darko on 11/21/07 17:02
On Nov 21, 5:43 pm, bruno_guedesav <bruno_guede...@yahoo.com.br>
wrote:
> I've made a function to fetch all results as an array of result-
> arrays. Getting the result arrays is easy, via mysql_fetch_array, and
> function itself is quite simple, as follows:
>
> function db_query($db, $query)
> {
> $result = mysql_query($query, $db);
> $res_array = array();
>
> if ($result) //it is a search
> {
> while($data = mysql_fetch_array($result,MYSQL_ASSOC))
> array_push($res_array,$data);
> }
>
> return $res_array;
>
> }
>
> But there's a slight problem: when the query in question is an INSERT,
> UPDATE or DELETE query, PHP will show me a warning saying:
>
> Warning: mysql_fetch_array(): supplied argument is not a valid MySQL
> result resource in /home/grad/ccomp/06/guedesav/public_html/PbBlog/inc/
> db.php on line 28
> (line 28 is "while($data = mysql_fetch_array($result,MYSQL_ASSOC))")
>
> and havingthis warning on the HTML output leads to be impossible to
> use header() to, for instance, go back to the post removal page. Is
> there any way to know prior to fetching if my result is of and INSERT/
> UPDATE/DELETE instead of a SELECT query?
Hello, Bruno.
I don't think it is a good idea to include a fetch_array into a
db_query() type
of function, first of all. If you really want to do that, however,
then make a
db_select_query() function that will do that, and do the rest with a
db_query function.
If you really want to stick with the idea, or if you have already done
a lot of code
with this function, then try this - mysql_fetch_array() will return
FALSE if no rows
are available in the result. Put an 'at' sign in front of the name of
the function (like
@mysql_fetch_array(...)). This will prevent it from echoing any
warnings, and the function
should still return FALSE if 1. no rows are available in the result 2.
(probably) if the
resource argument isn't compatible with the fetch function.
I don't find it a good idea, though. For instance, I do it like this
(for different
db compatibility): I have a function db_query, which executes a query,
and have a function
db_fetch() which fetches a row from a result returned by db_query. Of
course, I don't use
exact function names db_fetch and db_query, but you got the point. So,
I don't use db_fetch
unless I know exactly that I gave a SELECT statement to db_query.
Generally, when writing functions, try to stick with their exact
purposes - if it's executing
a statement, then it should do only that. If it's fetching a result,
it should do only that. When
including one into another, sooner or later you'll have to write
another function that doesn't
include others and the code will get messy. A -function- should have
its -function- not -functions-.
This way the code is cleaner and more easily understood.
Cheers,
Darko
[Back to original message]
|