views:

101

answers:

3

I get this error when I use this code for people to input data. The submit form won't be listed cause it's not useful in this circumstance:

function some_more_custom_content() {

$output="<BR>";

ob_start();

if ($_REQUEST['code'] != "") {
    $code = $_REQUEST['code'];
    $query="INSERT INTO `fc` (`code`,`datetime`) values ('" . mysql_real_escape_string($code) . "', now())";
    $result=mysql_query($query);

    while ($fetch_array = mysql_fetch_array($result)) {
        $seconds = time() - strtotime($fetch_array["datetime"]);

        if ((time() - $entry['datetime']) < 60*60) {
            echo ("The code " . htmlentities($code) ." was updated less than an hour ago.");
        } else {
            echo ("Inserted " . htmlentities($code) ." into the top.");
        }
 }
}

Any idea why? ;\

+4  A: 

INSERT statements don't return a resource, they return TRUE on success or FALSE on failure. Thus there is no resource for mysql_fetch_array() to operate on.

(This is one of the main reasons why people complain about PHP -- its semantics are inconsistent at best.)

Meredith L. Patterson
So, how can I fix t his and make it more clean?
Well, first off, what are you trying to do with that while block? If you just want to find out whether the insert succeeded or failed, The Disintegrator's response below will take care of it.
Meredith L. Patterson
I agree that there are inconsistencies in php, but in this case? What kind of (useful) resource should mysql_query() return for an INSERT operation?
VolkerK
In this case I'd suggest a more consistent approach for the semantics of `mysql_query()`, i.e., having it return the same kind of result for all queries. Python's `.execute()` (method of a cursor) returns the number of rows affected, which is consistent for INSERT, SELECT, UPDATE and DELETE; the `.fetchone()` and `.fetchall()` methods may subsequently be called if the query was a SELECT.
Meredith L. Patterson
Then it would have to return an object, which is what the mysql extension does not, it's an "old" procedural module. You can do if(!$result) { errorhandling(); } for all types of statements. If you want "more" use another module like pdo, http://php.net/pdo
VolkerK
+2  A: 

Adding to Meredith Answer. You shoul use

if($result!==FALSE) {
    // the insert was ok
} else {
    //the inser failed
}
The Disintegrator
A: 

change:

$result=mysql_query($query);

with:

$result=mysql_query($query) or die(mysql_error());

you will see the error.

inakiabt