Search code examples
phpmysqlprepared-statementbindparam

How to resolve fatal error in bind_param() when executing update statement


I am going to update the user profile details(name, password, contact_no, email). Please help me check how can I improve the code so that I can update successfully.

Here is DbOperations.php updateUser class:

public function updateUser($user_id, $name, $password,$contact_no,$email){
        $stmt = $this->con->prepare("UPDATE `mydb.User` SET `name` = ?, `password`= ? , `contact_no`= ?,`email` = ? WHERE  `user_id` = ? ;");

        $stmt->bind_param("ssisi", $name, $password, $contact_no, $email, $user_id);

        if($stmt->execute()){
                return 1;

        }else{
            return 2;
            }
    }       

Here is updateProfile.php

<?php
require_once'../includes/DbOperations.php';

    $response =array();
        if($_SERVER['REQUEST_METHOD']=='POST'){
            if(isset($_POST['user_id'])and
                isset($_POST['name'])and
                    isset($_POST['password'])and
                        isset($_POST['contact_no'])and
                        isset($_POST['email']))

                {//operate the data further
                    $db = new DbOperations();
                    $result=$db->updateUser(
                                        $_POST['user_id'],
                                        $_POST['name'],
                                        $_POST['password'],
                                        $_POST['contact_no'],
                                        $_POST['email']

                                        );
                    if($result == 1){
                                    $response['error']= false;
                                    $response['message'] = "updated successfully";


                    }elseif($result == 2){
                        $response['error']=true;
                        $response['message'] = "updated failed";
                        }
                    }       
            }else{
                $response['error']=true;
                $response['message'] = "empty fileds";

        }


    echo json_encode($response);

And the error message:

`<br />
<b>Fatal error</b>:  Call to a member function bind_param() on a non-object in
<b>C:\xampp\htdocs\Android\includes\DbOperations.php</b> on line
<b>49</b>
<br />`

Line 49 is :$stmt->bind_param("sssss", $name, $password, $contact_no, $email, $user_id);

And I am using an API developer to POST:

updateProfile-error

Table Structure


Solution

  • There are two things, which I noticed

    1. There is semicolon ; and braces () in your SQL, which shouldn't be part of it. And it should be

      "UPDATE `mydb.User` SET `name` = ?, `password`= ? , `contact_no`= ?,`email` = ? WHERE  `user_id` = ?"
      
    2. Since, userid and contact_no is integer. Then it should be "ssisi" instead of "sssss"

    3. Also, I would suggest to use User instead of mydb.User.