将帐户信息更新到数据库不起作用,PHP 错误:“调用成员函数”

Posted

技术标签:

【中文标题】将帐户信息更新到数据库不起作用,PHP 错误:“调用成员函数”【英文标题】:Updating account info into database not working, PHP error: "Call to a member function" 【发布时间】:2020-04-05 15:50:23 【问题描述】:

我正在开发一个使用 SharedPreferences 登录的应用程序。如果用户想从应用程序中更新他的信息,下一步是添加一个更新数据库的活动。我已经编写了代码,但是当我运行它时,似乎 JSON 有问题。我用断点检查过,值没问题,但是“s=”部分说Error: Call to a member function bind_param() on bool in C:\Users\wamp64\www\App.php on line <i>189</i>所以,我进入我的php并检查了第189行,但我没有发现任何问题。我使用了登录/注册的确切语法,它就像一个魅力。谢谢!

首先,我将添加 .php 中的第 189 行:

$stmt->bind_param("ssss", $nume, $prenume, $email, $telefon);

UpdateInfo.java

class ActualizareUser extends AsyncTask<Void, Void, String> 

        @Override
        protected String doInBackground(Void... voids) 
            //creating request handler object
            RequestHandler requestHandler = new RequestHandler();

            //creating request parameters
            HashMap<String, String> params = new HashMap<>();
            params.put("nume", Nume);
            params.put("email", Email);
            params.put("prenume", Prenume);
            params.put("telefon", Telefon);
            params.put("id", id);

            //returing the response
            return requestHandler.sendPostRequest(URLs.URL_UPDATE_USER, params);
        

        @Override
        protected void onPreExecute() 
            super.onPreExecute();
            //displaying the progress bar while user registers on the server
        

        @Override
        protected void onPostExecute(String s) 
            super.onPostExecute(s);
            //hiding the progressbar after completion
            try 
                //converting response to json object
                JSONObject objs = new JSONObject(s);

                //if no error in response
                if (!objs.getBoolean("error")) 
                    Toast.makeText(getApplicationContext(), objs.getString("message"), Toast.LENGTH_SHORT).show();

                    //getting the user from the response
                    JSONObject userJson = objs.getJSONObject("user");

                    //creating a new user object
                    User user = new User(
                            userJson.getString("Nume"),
                            userJson.getString("Prenume"),
                            userJson.getString("Adresa_mail"),
                            userJson.getString("Numar_telefon"),
                            userJson.getString("Parola"),
                            userJson.getInt("ID_UTILIZ")
                    );

                    //storing the user in shared preferences
                    SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
                    finish();
                    startActivity(new Intent(getApplicationContext(), Profil.class));
                 else 
                    Toast.makeText(getApplicationContext(), "A aparut o eroare", Toast.LENGTH_SHORT).show();
                
             catch (JSONException e) 
                e.printStackTrace();
            
        
     

App.php,更新部分:

case 'updateuser':


if(isTheseParametersAvailable(array('nume','email','prenume', 'telefon', 'id')))
                    $prenume = $_POST["prenume"];
                    $nume =$_POST["nume"];
                    $email =$_POST["email"];
                    $telefon =$_POST["telefon"];
                    $id =$_POST["id"];

                    $stmt = $conn->prepare("SELECT ID_UTILIZ FROM informatii_persoane WHERE ID_UTILIZ = ?");
                $stmt->bind_param("s", $id);
                $stmt->execute();
                $stmt->store_result();

                if($stmt->num_rows < 1)
                    $response['error'] = true;
                    $response['message'] = 'Nu se poate identifica un cont';
                    $stmt->close();
                else
                    $stmt = $conn->prepare("UPDATE INTO informatii_persoane (Nume, Prenume, Adresa_mail, Numar_telefon) VALUES (?, ?, ?, ?)");
                    $stmt->bind_param("ssss", $nume, $prenume, $email, $telefon);

                    if($stmt->execute())
                        $stmt = $conn->prepare("SELECT ID_UTILIZ, Nume, Prenume, Adresa_mail, Numar_telefon, Parola FROM informatii_persoane WHERE Adresa_mail = ?"); 
                        $stmt->bind_param("s",$email);
                        $stmt->execute();
                        $stmt->bind_result($id, $nume, $prenume, $email, $telefon, $parola);
                        $stmt->fetch();

                        $user = array(
                            'Nume'=>$nume, 
                            'Prenume'=>$prenume,
                            'Adresa_mail'=>$email,
                            'Numar_telefon'=>$telefon,
                            'Parola'=>$parola,
                            'ID_UTILIZ'=>$id
                        );

                        $stmt->close();

                        $response['error'] = false; 
                        $response['message'] = 'Date actualizate cu success'; 
                        $response['user'] = $user; 
                    
                

            else
                $response['error'] = true; 
                $response['message'] = 'A aparut o eroare'; 
            

        break; 

更新的.php:

case 'updateuser':
            if(isTheseParametersAvailable(array('nume','email','prenume', 'telefon', 'id')))
                $prenume = $_POST["prenume"];
                $nume =$_POST["nume"];
                $email =$_POST["email"];
                $telefon =$_POST["telefon"];
                $id =$_POST["id"];

                $stmt = $conn->prepare("SELECT ID_UTILIZ FROM informatii_persoane WHERE ID_UTILIZ = ?");
                $stmt->bind_param("s", $id);
                $stmt->execute();
                $stmt->store_result();
                $rows = $stmt->num_rows;
                $stmt->close();

                if($rows < 1)
                    $response['error'] = true;
                    $response['message'] = 'Nu se poate identifica un cont';

                else
                    $stmt = $conn->prepare("UPDATE INTO informatii_persoane (Nume, Prenume, Adresa_mail, Numar_telefon) VALUES (?, ?, ?, ?)");
                    $stmt->bind_param("ssss", $nume, $prenume, $email, $telefon);

                    if($stmt->execute())
                        $stmt1 = $conn->prepare("SELECT ID_UTILIZ, Nume, Prenume, Adresa_mail, Numar_telefon, Parola FROM informatii_persoane WHERE Adresa_mail = ?"); 
                        $stmt1->bind_param("s",$email);
                        $stmt1->execute();
                        $stmt1->bind_result($id, $nume, $prenume, $email, $telefon, $parola);
                        $stmt1->fetch();
                        $stmt1->close();
                        $user = array(
                            'Nume'=>$nume, 
                            'Prenume'=>$prenume,
                            'Adresa_mail'=>$email,
                            'Numar_telefon'=>$telefon,
                            'Parola'=>$parola,
                            'ID_UTILIZ'=>$id
                        );


                        $response['error'] = false; 
                        $response['message'] = 'Date actualizate cu success'; 
                        $response['user'] = $user; 
                    
                    $stmt->close();
                

            else
                $response['error'] = true; 
                $response['message'] = 'A aparut o eroare'; 
            

        break; 

informatii_persoane 结构:

   create table if not exists informatii_persoane (
ID_utiliz int auto_increment primary key,
Nume varchar(50),
Prenume varchar(50),
Adresa_mail varchar (50) unique ,
Numar_telefon text ,
Notificare_SMS enum('Da','Nu'),
Notificari_aplicatie enum('Da','Nu'),
Parola varchar(50),
nr_alerte_semnalizate int,
nr_alerte_corecte int,
nr_alerte_partial_corecte int,
nr_lerte_incorecte int,   -- vezi aici cum faci %
scor float   -- il facem din cele doua de mai sus
);

【问题讨论】:

这个错误告诉你你的 $stmt 变量是布尔类型的,但是你试图访问它,就像它是一个对象一样。 你在 bind_param 行之前尝试过w3resource.com/php/function-reference/mysqli_error.php 吗? @Costin,分享informatii_persoane Table的结构 @AmanjotKaur 我试图在 bind_param 之前添加$stmt-&gt; error; ,但我得到了另一个错误。我认为我没有正确使用它。我用表的结构更新问题 @Costin 你试过我最新更新的答案吗..我答案的前两行? 【参考方案1】:
$stmt = $conn->prepare("Update informatii_persoane set Nume = ?, Prenume = ?, Adresa_mail = ?, Numar_telefon = ?  where ID_UTILIZ = ?");
$stmt->bind_param("ssssi", $nume, $prenume, $email, $telefon, $id);

问题出在$stmt->close();

您尚未关闭 select 语句,然后启动 insert 语句。 您可以同时打开多个语句。但是您最终必须关闭它们。

另外,你的 INSERT 查询写错了。

检查一下

UPDATE INTO informatii_persoane (Nume, Prenume, Adresa_mail, Numar_telefon) VALUES (?, ?, ?, ?)

改成

INSERT INTO informatii_persoane (Nume, Prenume, Adresa_mail, Numar_telefon) VALUES (?, ?, ?, ?)

/**************************************************** **************/

重要提示

另外,如果你想找出查询中的错误, 在给出错误的行下方和上方添加echo $conn-&gt;error;

【讨论】:

我已经尝试过这个解决方案,但同样的错误仍然存​​在 我已经更新了代码。错误仍然是$stmt-&gt;bind_param("ssss", $nume, $prenume, $email, $telefon); 我将尝试在 MySQL 中运行查询 情况是一样的,即使我切换到INSERT。 我已经在我的本地机器上尝试过你的代码。它工作正常。 @Costin 数据已插入数据库【参考方案2】:

您的查询存在问题。 prepare() 可能返回 FALSE。

你能检查一下吗:

error_reporting(E_ALL);

注意:

如果表名或列​​名不正确意味着会抛出错误

【讨论】:

我已经仔细检查了列名和表名,它们是一样的【参考方案3】:

我给你的建议是尝试使用 ORM,它极大地简化了这些过程。对于您的情况,我总是使用redbean,您需要像这样配置数据库:

class ADXdbConfig

private $db;

private $host;

private $db_user;

private $pass_phrase;

public function __construct()

    if (! isset($this->host) || ! isset($this->db_user) || ! isset($this->db) || ! isset($this->pass_phrase)) 
        if (null !== getenv("OPTS_ENV") && "live" == getenv("OPTS_ENV")) 
            $url = parse_url(getenv("DATABASE_URL"));
            if (isset($url) && isset($url["host"]) && isset($url["user"])) 
                $this->host = $url["host"];
                $this->db_user = $url["user"];
                $this->pass_phrase = $url["pass"];
                $this->db = substr($url["path"], 1);
            
         else if (null !== getenv("OPTS_ENV") && "local" == getenv("OPTS_ENV")) 
            $this->host = getenv("PGQL_HOST");
            $this->db_user = getenv("PGQL_DB_USER");
            $this->pass_phrase = getenv("PGQL_DB_PASS");
            $this->db = getenv("PGQL_DB_NAME");
         else 
            error_log("ERROR(ADXdbConfig):Unable to determine the environment(live/local)");
            throw new Exception("Unable to determine the environment(live/local)");
        
    


/**
 * This method connects to the database.
 */
public function connect()

    if (null !== $this->host && null !== $this->db && null !== $this->db_user && null !== $this->pass_phrase) 
        $isConnected = R::testConnection();
        if ($isConnected === FALSE) 
            R::setup("pgsql:host=$this->host;dbname=$this->db", $this->db_user, $this->pass_phrase);
            // to allow underscores in table creation
            R::ext('xdispense', function ($type) 
                return R::getRedBean()->dispense($type);
            );
        
     else 
        error_log("ERROR(MDBconnection:connect): Undefined DB settings---------------");
        throw new Exception("Error connecting to the database.");
    

当您必须在不同的环境中进行部署时,Env var 会非常有用。 然后你可以像这样连接到数据库:

 $dbConnection = new ADXdbConfig();
 $dbConnection->connect();

然后你可以像这样更新:

 $userProfileBean = R::load($tableName, $userProfile->getId());
        $userProfileBean->first_name = $userProfile->getFirstName() ?? $userProfileBean->first_name;
        $userProfileBean->last_name = $userProfile->getLastName() ?? $userProfileBean->last_name;
        $userProfileBean->phone_number = $userProfile->getPhoneNumber() ?? $userProfileBean->phone_number;
        $userProfileBean->address = $userProfile->getAddress() ?? $userProfileBean->address;
        $userProfileBean->last_update_by = $userProfile->getLastUpdatedBy();
        $userProfileBean->last_update_on = date("Y-m-d h:d:s");
        $userProfileId = R::store($userProfileBean);

有关更多详细信息,您可以查看 redbean 文档的更多信息。我希望这可以帮助您解决问题。

【讨论】:

【参考方案4】:

@Amanjot Kaut 提供的答案也是正确的。该错误已通过更改更新查询来解决:

$stmt = $conn->prepare("UPDATE INTO informatii_persoane (Nume, Prenume, Adresa_mail, Numar_telefon) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $nume, $prenume, $email, $telefon);

到:

$stmt = $conn->prepare("Update informatii_persoane set Nume = ?, Prenume = ?, Adresa_mail = ?, Numar_telefon = ?  where ID_UTILIZ = ?");
$stmt->bind_param("ssssi", $nume, $prenume, $email, $telefon, $id);

【讨论】:

以上是关于将帐户信息更新到数据库不起作用,PHP 错误:“调用成员函数”的主要内容,如果未能解决你的问题,请参考以下文章

ckeditor插入或更新在第一次尝试时不起作用

使用 ajax、jquery 和 PHP 从数据库更新图像不起作用

PHP/MYSQL:更新数据不起作用请看一下[重复]

MySQL的更新命令在PHP中不起作用

PHP标头重定向不起作用并停留在login.php上

带有帐户激活检查的 PHP 登录页面 [重复]