开发者

PHP generating a phantom warning for code that is not executed

In an effort to tidy up my code, I've encapsulated my database reads into its own function, which accepts a SQL command for the argument, as well as an optional $getArray argument which specifies whether I am returning an array as the result (true for SELECT, false for UPDATE, etc).

function readDB($sql, $getArray = false)
{
    $conn = odbc_connect('myAccessDataBase', '', '');
    if (!$conn)
        return exit('Connection Failed: '.$conn);
    if ($getArray = false)
        odbc_exec($conn, $sql);
    else
    {
        $res = odbc_exec($conn, $sql);
        if (!$res)
            return exit('Error in SQL');
        return odbc_fetch_array($res);
    }
    odbc_close($conn);
}

The code above works as expected except for one small caveat. If I am performing an UPDATE vs a SELECT, I get a warning due to $getArray being set to false:

Warning: odbc_fetch_array() [function.odbc-fetch-array]: No tuples available at this result index in C:...\functions.php on line 14

I understand the warning, which makes sense if that line were to actually be executed, however it is not. My question is in regards as to why PHP is evaluating the contents of the else portion of my if statement, which is not even being hit during runtime. I understand that the 开发者_运维知识库UPDATE cannot return an array, hence why I am evaluating $getArray to determine whether I expect such a return. What can I do to circumvent this warning? Regardless, I am still pretty fresh with my PHP, and am probably going about this the wrong way anyhow. Cheers!


You're setting the variable TO FALSE instead of evaluating it FOR FALSE If you change this line:

if ($getArray = false)

to

if ($getArray == false)

It should work.

edit

On another note, you should do your test in reverse. Instead of testing for false, test for true and THEN have an else. It makes a little more sense logically for anyone coming in to look at your code later.

Instead of If this IS NOT the case then do this it makes more sense to say if this is the case, do this

So switch your code blocks around and test:

if ($getArray)


The line

if ($getArray = false)

must be

if ($getArray == false)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜