Current Location: Home> Function Categories> mysqli_stmt::attr_set

mysqli_stmt::attr_set

(mysqli_stmt_attr_set) is used to modify the behavior of prepared statements
Name:mysqli_stmt::attr_set
Category:MySQLi
Programming Language:php
One-line Description:Set properties of preprocessing statement objects

Function name: mysqli_stmt::attr_set()

Applicable version: PHP 8.0.0 and above

Usage: This method is used to set the properties of the preprocessed statement object.

Syntax: bool mysqli_stmt::attr_set(int $attr, mixed $mode)

parameter:

  • $attr: represents the attribute to be set, which can be one of the following constants:
    • MYSQLI_STMT_ATTR_CURSOR_TYPE: Sets the cursor type of the preprocessing statement. Optional values ​​include:
      • MYSQLI_CURSOR_TYPE_NO_CURSOR: No cursor is used.
      • MYSQLI_CURSOR_TYPE_READ_ONLY: Read-only cursor.
      • MYSQLI_CURSOR_TYPE_FOR_UPDATE: The cursor can be updated.
      • MYSQLI_CURSOR_TYPE_SCROLLABLE: Scrollable cursor.
    • MYSQLI_STMT_ATTR_PREFETCH_ROWS: Sets the number of prefetched rows for the preprocessing statement. The optional value is a positive integer.
  • $mode: represents the value of the property to be set.

Return value: Return true on success, and false on failure.

Example:

 // 创建数据库连接$mysqli = new mysqli("localhost", "username", "password", "database"); // 准备预处理语句$stmt = $mysqli->prepare("SELECT id, name FROM my_table WHERE age > ?"); // 设置预处理语句的游标类型为可滚动游标$stmt->attr_set(MYSQLI_STMT_ATTR_CURSOR_TYPE, MYSQLI_CURSOR_TYPE_SCROLLABLE); // 设置预处理语句的预取行数为100 $stmt->attr_set(MYSQLI_STMT_ATTR_PREFETCH_ROWS, 100); // 绑定参数并执行查询$age = 18; $stmt->bind_param("i", $age); $stmt->execute(); // 获取结果集$result = $stmt->get_result(); // 遍历结果集并输出数据while ($row = $result->fetch_assoc()) { echo "ID: " . $row['id'] . ", Name: " . $row['name'] . "<br>"; } // 关闭预处理语句和数据库连接$stmt->close(); $mysqli->close();

In the above example, we first create a database connection object $mysqli, and use the object to prepare a preprocessing statement $stmt. Then, we use the mysqli_stmt::attr_set() method to set the cursor type of the preprocessing statement to scrollable cursor and the number of prefetched rows to 100 respectively. Next, we bind the parameters and execute the query, and then output the query result by getting the result set and traversing it. Finally, we closed the preprocessing statement and the database connection.

Note that the preprocessing statement object must be prepared before using the mysqli_stmt::attr_set() method.

Similar Functions
Popular Articles