【问题标题】:how to close connection using prepare statement in php?如何在php中使用prepare语句关闭连接?
【发布时间】:2015-09-25 21:11:15
【问题描述】:

我正在使用 php 在服务器数据库上创建用户帐户。我已使用准备语句创建用户帐户。我想知道如何使用准备语句关闭我的 sql 连接,或者我不需要关闭连接?是否自动完成。

这是我的代码

public function createUser($name, $email, $password,$file_path,$phone,$address,$profession,$language)
    {


        $response = array();

        // First check if user already existed in db
        if (!$this->isUserExists($email)) {

            // Generating API key
            $api_key = $this->generateApiKey();

            // insert query
            $stmt = $this->conn->prepare("INSERT INTO users(name, email, password, api_key,profile_pic,phone,address,profession,language,date) values(?, ?, ?, ?, ?, ?, ?, ?,?,now())");
            $stmt->bind_param("sssssssss", $name, $email, $password, $api_key,$file_path,$phone,$address,$profession,$language);

            $result = $stmt->execute();

            $stmt->close();

            // Check for successful insertion
            if ($result)
            {
                // User successfully inserted
                return USER_CREATED_SUCCESSFULLY;
            }
            else
            {
                // Failed to create user
                return USER_CREATE_FAILED;
            }
        }
        else
        {
            // User with same email already existed in the db
            return USER_ALREADY_EXISTED;
        }

        return $response;
    }

我是 php 新手,所以我对此一无所知。

【问题讨论】:

  • 你已经在使用 $stmt->close(),所以一切都很好。
  • 好的。这意味着我不必像 conn->close();或 mysqli->close();
  • 你的代码让我想知道 $this->conn 在哪里打开,在对象生命周期结束的类似位置,你必须关闭连接
  • 我不明白你在说什么。告诉我我做错了吗?如果是,那么解决方案是什么。
  • 重复:stackoverflow.com/questions/9083341/when-to-call-mysqliclose - 你只需要使用 $conn->close();如果您想在脚本完成之前终止连接。

标签: php mysql sql prepared-statement php-5.3


【解决方案1】:

$stmt->close();

就够了。

检查这个 http://www.w3schools.com/php/php_mysql_prepared_statements.asp

【讨论】:

  • 但是在你的链接中他们也在使用 $conn->close();@Manu
【解决方案2】:
$stmt->close(); // Closes the prepared statement

$this->conn->close(); // Closes the mysql connection

【讨论】:

  • 在我的代码中,我没有使用关键字 $conn 我只是在使用 conn。@Mallik.somebody 刚刚回答 $stmt>close() 就足够了。
  • 不关闭mysql连接会出现什么问题?
  • 检查here
猜你喜欢
  • 2017-01-31
  • 2018-05-19
  • 1970-01-01
  • 1970-01-01
  • 2011-05-22
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多