Fatal Error with fetch_assoc inside a function

2019-09-19 01:56发布

问题:

I truly need your help. I have seen answers and even followed advice as previously posted but NO SOLUTIONS SHOW how to use fetch associated array using PREPARED STATEMENTS so I am not trying to submit an already answered question. I have followed suggestions to others questions but I am still getting:

Fatal error: Call to a member function fetch_assoc() on a non-object in /xxx/xxxxxx.php on line 75

I am showing you the old code using MySQL and how I have changed it to MySQLi using prepared statements, but I am still getting the same Fatal Error. Can someone please help me, I am going crazy and I truly need to find out what I am doing wrong. Thanks for your help.

//*******************************************************************
//      OLD CODE: 
//          Called by: $theme=$log->get_theme(); 
//*******************************************************************
class redirect
{
    function __construct()
    {

    }

    function get_theme()
    {
        $rs=mysql_query("select * from theme where status='yes'");
        if(mysql_num_rows($rs)>0)
        {
            $data=mysql_fetch_array($rs);
            return $data['theme_name'];
        }

    }
}

//*********************************************************************
//      OLD CODE: 
//          Called by: $theme=$log->get_theme($cn);
//*********************************************************************

class redirect
{
    public $cn;

    function __construct()
    {

    }
    function get_theme($cn)
    {
        $themeStatus = 'yes';

        if ($stmt = $cn->prepare("SELECT * FROM theme WHERE status = ? "))
            {
                $stmt->bind_param("s", $themeStatus);
                $result = $stmt->execute();
                $stmt->store_result();
                if ($stmt->num_rows >= "1")
                {
                    $data = $result->fetch_assoc();     // ERROR LINE
                    return $data['theme_name'];
                }
            }
        else
            {
                echo "Failed to execute prepared statement: " . mysqli_connect_error();
            }       
    }
}

回答1:

The mysqli_stmt::execute method returns only bool by definition. So calling $result->any_method_name() will fail because $result is a boolean value.

To get the values from a prepared statement using the MySQLi library you bind your target variables with $stmt->bind_result(...) and then use $stmt->fetch() in a while loop to get the result of your query in your bound variables. And after that you switch from MySQLi to PDO because it has a better API regarding this…



标签: php mysql mysqli