如何使用bind_param php mysqli选择行?

2024-04-04

通常我使用此代码来回显页面行。做工很好啊

$query = "SELECT * FROM table WHERE id = '$id' ";
$result = mysqli_query($db_mysqli, $query);
$row = mysqli_fetch_assoc($result);
$page = $row['page'];
echo $page;

.....

现在我用bind_param此代码用于回显页面行。但没有工作,我该怎么办?

$stmt = $db_mysqli->prepare("SELECT * FROM table WHERE id = ?");
$stmt->bind_param("s", $id);
$stmt->execute();
$result = $stmt->get_result();
$page = $row['page'];
echo $page;

问题描述:

The mysqli_result方法返回的对象get_result看起来像这样:

mysqli_result Object
(
    [current_field] => 0
    [field_count] => 3
    [lengths] => 
    [num_rows] => 1
    [type] => 0
)

正如您所看到的,该对象仅公开有关您需要从中引用数据的记录集的一些属性(字段数、行数等)。因此,您不能直接从中引用字段值。

解决方案:

为了获取所需的数据,您必须调用中定义的方法之一mysqli_result class (fetch_all, fetch_array, fetch_assoc, etc):

//...
$result = $stmt->get_result();
$row = $result->fetch_array(MYSQLI_ASSOC);
$page = $row['page'];
//...

with $row代表获取的记录并且是一个像这样的数组:

Array
(
    [id] => 13
    [page] => 21
    ...
)

欲了解更多详情,请阅读The mysqli_result class https://secure.php.net/manual/en/class.mysqli-result.php.

关于错误和异常处理:

请注意,适当的错误和异常处理 https://secure.php.net/manual/en/book.errorfunc.php系统在开发过程中至关重要。本文 https://phpdelusions.net/articles/error_reporting描述了以优雅且彻底的方式激活它所需的步骤。

广泛的例子:

为了清楚起见,我准备了一个广泛的示例,其中包含使用访问数据库所需的所有组件mysqli扩大。它呈现了必须从用户列表中获取一条或多条记录的情况 - 保存在名为的数据库表中users。每个用户都由其描述id, name and age.

由您来实现错误/异常处理系统 - 如上述文章中所述。

索引.php:

选项 1) 仅获取一条记录:

<?php

require 'connection.php';

// Assign the values used to replace the sql statement markers.
$id = 10;

/*
 * The SQL statement to be prepared. Notice the so-called markers, 
 * e.g. the "?" signs. They will be replaced later with the 
 * corresponding values when using mysqli_stmt::bind_param.
 * 
 * @link http://php.net/manual/en/mysqli.prepare.php
 */
$sql = 'SELECT 
            id,
            name,
            age 
        FROM users 
        WHERE id = ?';

/*
 * Prepare the SQL statement for execution - ONLY ONCE.
 * 
 * @link http://php.net/manual/en/mysqli.prepare.php
 */
$statement = $connection->prepare($sql);

/*
 * Bind variables for the parameter markers (?) in the 
 * SQL statement that was passed to prepare(). The first 
 * argument of bind_param() is a string that contains one 
 * or more characters which specify the types for the 
 * corresponding bind variables.
 * 
 * @link http://php.net/manual/en/mysqli-stmt.bind-param.php
 */
$statement->bind_param('i', $id);

/*
 * Execute the prepared SQL statement.
 * When executed any parameter markers which exist will 
 * automatically be replaced with the appropriate data.
 * 
 * @link http://php.net/manual/en/mysqli-stmt.execute.php
 */
$statement->execute();

/*
 * Get the result set from the prepared statement.
 * 
 * NOTA BENE:
 * Available only with mysqlnd ("MySQL Native Driver")! If this 
 * is not installed, then uncomment "extension=php_mysqli_mysqlnd.dll" in 
 * PHP config file (php.ini) and restart web server (I assume Apache) and 
 * mysql service. Or use the following functions instead:
 * mysqli_stmt::store_result + mysqli_stmt::bind_result + mysqli_stmt::fetch.
 * 
 * @link http://php.net/manual/en/mysqli-stmt.get-result.php
 * @link https://stackoverflow.com/questions/8321096/call-to-undefined-method-mysqli-stmtget-result
 */
$result = $statement->get_result();

/*
 * Fetch data and save it into an array:
 * 
 *  Array
 *  (
 *      [id] => 10
 *      [name] => Michael
 *      [age] => 18
 *  )
 * 
 * @link https://secure.php.net/manual/en/mysqli-result.fetch-array.php
 */
$user = $result->fetch_array(MYSQLI_ASSOC);

/*
 * Free the memory associated with the result. You should 
 * always free your result when it is not needed anymore.
 * 
 * @link http://php.net/manual/en/mysqli-result.free.php
 */
$result->close();

/*
 * Close the prepared statement. It also deallocates the statement handle.
 * If the statement has pending or unread results, it cancels them 
 * so that the next query can be executed.
 * 
 * @link http://php.net/manual/en/mysqli-stmt.close.php
 */
$statement->close();

/*
 * Close the previously opened database connection.
 * 
 * @link http://php.net/manual/en/mysqli.close.php
 */
$connection->close();

// Reference the values of the fetched data.
echo 'User id is ' . $user['id'] . '<br/>';
echo 'User name is ' . $user['name'] . '<br/>';
echo 'User age is ' . $user['age'] . '<br/>';

选项2)获取多条记录:

<?php

require 'connection.php';

$id1 = 10;
$id2 = 11;

$sql = 'SELECT 
            id,
            name,
            age 
        FROM users 
        WHERE 
            id = ? 
            OR id = ?';

$statement = $connection->prepare($sql);

$statement->bind_param('ii', $id1, $id2);

$statement->execute();
$result = $statement->get_result();

/*
 * Fetch data and save it into an array:
 * 
 *  Array
 *  (
 *      [0] => Array
 *          (
 *              [id] => 10
 *              [name] => Michael
 *              [age] => 18
 *          )
 *  
 *      [1] => Array
 *          (
 *              [id] => 11
 *              [name] => Harry
 *              [age] => 59
 *          )
 *  )
 * 
 * @link http://php.net/manual/en/mysqli-result.fetch-all.php
 */
$users = $result->fetch_all(MYSQLI_ASSOC);

$result->close();
$statement->close();
$connection->close();

// Reference the values of the fetched data.
foreach ($users as $key => $user) {
    echo 'User id is ' . $user['id'] . '<br/>';
    echo 'User name is ' . $user['name'] . '<br/>';
    echo 'User age is ' . $user['age'] . '<br/>';

    echo '<hr/>';
}

连接.php:

<?php

// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'tests');
define('USERNAME', 'root');
define('PASSWORD', 'root');

/*
 * Error reporting.
 * 
 * Also, define an error handler, an exception handler and, eventually, 
 * a shutdown handler function to handle the raised errors and exceptions.
 * 
 * @link https://phpdelusions.net/articles/error_reporting Error reporting basics
 * @link http://php.net/manual/en/function.error-reporting.php
 * @link http://php.net/manual/en/function.set-error-handler.php
 * @link http://php.net/manual/en/function.set-exception-handler.php
 * @link http://php.net/manual/en/function.register-shutdown-function.php
 */
error_reporting(E_ALL);
ini_set('display_errors', 1); /* SET IT TO 0 ON A LIVE SERVER! */

/*
 * Enable internal report functions. This enables the exception handling, 
 * e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions 
 * (mysqli_sql_exception).
 * 
 * MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
 * MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings. 
 * 
 * @link http://php.net/manual/en/class.mysqli-driver.php
 * @link http://php.net/manual/en/mysqli-driver.report-mode.php
 * @link http://php.net/manual/en/mysqli.constants.php
 */
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Create a new db connection.
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);

// Set the desired connection charset
$connection->set_charset('utf8mb4');

测试数据:

id  name    age
---------------
9   Julie   23
10  Michael 18
11  Harry   59

创建表语法:

CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(100) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用bind_param php mysqli选择行? 的相关文章

  • 如何使用 php 将 *.xlsb 转换为数组或 *.csv

    我正在尝试转换 xlsb文件到php array or csv文件 或至少 xls 我尝试使用PHPExcel 但看起来它无法识别该文件中的内容 我注意到 你可以重命名 xlsb文件到 zip文件 然后使用命令行解压缩unzip zip 之
  • 使用 PHP 将 latin1_swedish_ci 转换为 utf8

    我有一个数据库 里面充满了类似的值 Dhaka 应该是 Dhaka 因为我在创建数据库时没有指定排序规则 现在我想修复它 我无法从最初获取数据的地方再次获取数据 所以我在想是否可以在 php 脚本中获取数据并将其转换为正确的字符 我已将数据
  • ZipArchive 提取 - 单个文件

    我有以下代码 ipaFile path file ipa iconFilePath Payload myapp app email protected cdn cgi l email protection the pathway to my
  • 克隆和引用传递问题

    所以在过去的几天里 我一直在绞尽脑汁地试图让一个类能够正确克隆 问题是克隆不会删除 重做任何引用传递 结果是 主数据对象仍然作为引用传递 从而完全抵消了克隆的效果 这是问题的简化版本 class my class private data
  • PHP 换行符 (\n) 不起作用

    由于某种原因我无法使用 n使用 PHP 输出到文件时创建换行符 上面只写着 n 到文件 我尝试使用 n 同样 它只写 n 如预期 但我一生都无法弄清楚为什么在字符串中添加 n 不会创建新行 我也尝试过 r n但它只是附加 r n 到文件中的
  • 如何在 Laravel 5 中对合并集合进行分页?

    我正在创建一个包含两种类型的对象的流 BluePerson 和 RedPerson 为了创建流 我获取所有这两个对象 然后将它们合并到一个集合中 这样做之后 我需要对它们进行分页 但是分页似乎是针对雄辩的模型和数据库查询 而不是集合 我见过
  • 如何使用 jquery ajax 将锚点的值发送到 php

    我正在尝试使用 jquery 将几个锚点的值发送到 php 文件 但我没有从 php 脚本中得到回调 div class result div a href value class star Star 5 a a href value cl
  • php exec 返回的结果比直接进入命令行要少

    我有一个 exec 命令 它的行为与通过 Penguinet 给 linux 的相同命令不同 res exec cd mnt mydirectory zcat log file gz echo res 当将命令直接放入命令行时 我在日志文件
  • filter_input() 何时删除 POST 变量的斜杠?

    我创建了一个小型 PHP 脚本 它在 PHP 5 2 17 的服务器上运行magic quotes gpc指令已启用 我没有对 php ini 文件的写访问权限 并且我想从用户输入中删除所有斜杠 即使magic quotes gpc指令被关
  • 维护 HttpUrlConnection 调用之间的会话(Native/Webview)

    让我从我做的开始desire 我想制作一个应用程序part native and part webviews Problem 维护本机和 webview 部分之间的会话 My 处理方法 this 我打算实现一个本机登录 其中我向用户展示两个
  • 无法显示由 Fine-uploader 上传到 Amazon s3 的图像

    我现在尝试设置fineuploader s3以显示在aws服务器上成功上传的文件的图像 如示例页面上所做的那样 http fineuploader com s3 demo http fineuploader com s3 demo 我 仍然
  • 如何使用php在mysql数据库中添加照片? [关闭]

    这个问题不太可能对任何未来的访客有帮助 它只与一个较小的地理区域 一个特定的时间点或一个非常狭窄的情况相关 通常不适用于全世界的互联网受众 为了帮助使这个问题更广泛地适用 访问帮助中心 help reopen questions 我对 PH
  • Laravel 上传前如何压缩图像?

    我正在制作一个图片库网站 用户可以在其中上传任何图像 它们将显示在前端 我需要在不影响图像质量的情况下压缩图像 以减小图像大小 以便页面加载速度不会影响那么大 我使用以下代码来上传图像 rules array file gt require
  • 无法在 PHPUnit 中使用数据提供程序运行单个测试

    使用命令行运行测试时遇到问题 如果我像这样运行 phpunit phpunit no configuration filter testAdd DataTest DataProviderTest php 效果很好 但是我们使用正则表达式来准
  • PHP:展平数组-最快的方法? [复制]

    这个问题在这里已经有答案了 是否有任何快速方法可以在不运行 foreach 循环的情况下展平数组并选择子键 在本例中为 键 和 值 或者 foreach 始终是最快的方法 Array 0 gt Array key gt string val
  • PHP函数返回值到html标签

    我想获取函数的返回值并将其显示到特定的id 在我的 Class php 中 我有一个名为 login 的函数 用于验证密码是否正确 不正确
  • 如何检查一个值是否已经存在以避免重复?

    我有一个 URL 表 但我不想要任何重复的 URL 如何使用 PHP MySQL 检查给定 URL 是否已在表中 如果您不想重复 可以执行以下操作 添加唯一性约束 use REPLACE http dev mysql com doc ref
  • phpstorm xdebug 与 symfony2 项目

    我正在尝试使用 xdebug 和 phpstorm 调试 symfony2 应用程序 我的本地开发环境是Ubuntu 14 04 with apache2 Xdebug版本是2 2 7 我在另一个 php 不是 symfony2 项目上使用
  • 如何使用xquery查找节点并向其添加子节点?

    是否可以使用xpath xquery查询特定的xml节点 然后向其导入 添加子节点 示例 代码取自http codepad org gJ1Y2LjM http codepad org gJ1Y2LjM 这是在类似的问题中提出的 但不相同 1
  • 有关于 PHP 中的 V8JS 的文档吗?

    有没有关于V8JS的文档 我是否只需要标准 PHP 或一些扩展即可使用 V8JS 我将非常感谢有关 PHP 中的 V8JS 的任何信息 要求 PHP 5 3 3 和 V8 库和标头安装在正确的路径中 Install http www php

随机推荐

  • Java:计算两点之间的角度(以度为单位)

    我需要计算我自己的 Point 类的两点之间的角度 以度为单位 点 a 应为中心点 Method public float getAngle Point target return float Math toDegrees Math ata
  • Django REST Framework 自定义字段验证

    我正在尝试为模型创建自定义验证 以检查其start date在其之前end date事实证明这几乎是不可能的 我尝试过的东西 内置 Django 验证器 没有对此进行检查 我自己写的 就像这样 def validate date self
  • 更新 flutter 和 Xcode 后,Xcode 14.3 中缺少文件“libarclite_iphoneos.a”

    我有 flutter 项目 我正在尝试运行 iOS 版本 但在将 flutter 和 Xcode 更新到最新版本后出现错误 我使用 firebase core 插件 error Could not build the precompiled
  • 爱国者导弹浮动指向误差

    从计算机系统 程序员的角度http csapp cs cmu edu http csapp cs cmu edu 练习题2 51 我们在问题 2 46 中看到 爱国者导弹软件近似为 0 1 因为 x 0 000110011001100110
  • Azure 相同的 FTP URL 适用于共享相同应用程序服务计划的所有 Azure 网站

    我为单一应用程序服务计划创建了几个 Web 应用程序 对于所有这些应用程序 我看到一个 FTP URL 问题是 当我转到 URL 时 我可以看到一个 Site wwwroot 文件夹 其中仅显示一个应用程序 不是可以访问其他Web应用程序的
  • 在 Python 或 MATLAB 中从等值线图的像素中提取数据

    我有一个这样的等高线图 Now 如果我没有生成等值线图的数据 而我拥有的只是图像 如何从图像中提取每个像素的值并将其存储在数组中 MATLAB Python 中的任何建议或示例都会有帮助 如果您知道像素值 请使用find 您可以找到您想要的
  • 文本修饰:外观和计算值之间的明显差异

    我在处理与以下内容相关的代码时注意到了这一点 奇怪 a div 周围的链接 div 内的样式 https stackoverflow com questions 13595357 alink around div styling insid
  • EC2 Ubuntu 14 默认密码

    我有一个EC2实例运行Ubuntu 14我经常使用它连接SSH 现在我尝试使用 Windows 中的远程桌面连接到此实例 如图所示here https askubuntu com questions 592537 can i access
  • ggplot2交错轴标签

    我正在制作一个ggplot x 轴是因子 标签很长 我无法缩短标签 它们已经尽可能短了 我有兴趣使标签垂直偏移 我的偏好是让每个奇数标签的高度为 0 每个偶数标签的高度距离 x 轴更远 2 个单位 我看过这里 ggplot 希望帮助 htt
  • Rails 4.0 安装错误 -require: 无法加载此类文件 -- active_support (LoadError)

    我安装了新的 Ruby 2 0 和 Rails 4 0 当我执行 Rails new test app 时 我得到以下信息 有人遇到这个吗 devuser devbox rails 新 test app usr local lib ruby
  • 将二进制字符串转换为字节

    我有一个由 0 255 字节值组成的字符串 我需要将其转换为字节数组 我不想将范围 128 255 转换为 utf 8 事实上 该字符串已经以 utf 8 编码 我到底该如何解决令人沮丧的 不在 0 128 范围内 错误 gt gt gt
  • 如何在 Swift 中生成随机 unicode 字符?

    我当前尝试创建随机 unicode 字符生成失败 并出现错误 例如我的其他问题中提到的错误here https stackoverflow com questions 32158381 fatal error high and low su
  • 从 std::string 解析整数,但如果是浮点则失败

    在 C 和 C 中 有多种方法可以将字符串转换为整数 但我还没有找到解析浮点数时失败的转换方法 const float fnum std stof 1 5 std cout lt lt fnum lt lt std endl prints
  • 如何按顺序调用多个异步 javascript 函数?

    我试图按顺序调用以下函数 但它们不一定以正确的顺序返回 然后我了解了可以使用 回调 顺序调用的异步函数 如何使用回调使这些函数按顺序执行 getJSON http localhost search data php title title
  • WPF 进度栏未显示正确的进度

    我有一个应用程序 我正在其中分块上传文件 我的前端是WPF 我有一个进度条来显示文件上传进度 上传是由单独的线程完成的 进度条采用单独的形式 在上传开始时由子线程调用 我找到了文件中的块总数来设置进度条的最大属性 现在 对于上传的每个块 我
  • 在 HttpConfiguration 实例中的 ASP.NET Web API 应用程序中处理 json 漂亮的打印参数

    我需要在 ASP NET Web API 应用程序中添加和处理可选的 pretty 参数 当用户发送 pretty true 时 应用程序响应应该看起来像带有缩进的人类可读的 json 当用户发送 pretty false 或者根本不发送该
  • 使用环境变量调用python中的子进程

    我正在尝试编写一个 python 脚本来使用 Plex 媒体扫描仪自动扫描 plex 的一部分 为此 我必须以运行 plex 的用户身份运行扫描仪 在本例中为 plex 并为其提供环境变量 LD LIBRARY PATH 我尝试过使用 su
  • 参数化查询.....需要参数“@units”,但未提供该参数

    我收到这个异常 参数化查询 Name nvarchar 8 type nvarchar 8 units nvarchar 4000 rang 需要参数 units 但未提供该参数 我的插入代码是 public int insertType
  • Spring上下文动态变化

    我已经阅读了动态 bean 定义的更改 我在一个简单的代码示例中尝试了它 参见下面的代码 我发现它在我不想停止服务器但添加 更改 bean 定义的情况下非常有吸引力 问题 这样做安全吗 参见下面的代码 你必须定义safe The Abstr
  • 如何使用bind_param php mysqli选择行?

    通常我使用此代码来回显页面行 做工很好啊 query SELECT FROM table WHERE id id result mysqli query db mysqli query row mysqli fetch assoc resu