duannao1920 2016-10-10 18:06
浏览 57

无法将mySQL函数转换为PDO,同时保留变量名称 - 几乎拥有它

I had the following PHP mySQL code:

$q = @mysql_query("SELECT * FROM tablename WHERE admin_id = '" . $admin_id . "'");
while ($arr = mysql_fetch_array($q)) {
    $user_settings[$arr['setting']] = html_entity_decode($arr['value']);
}

In my database I have a table with settings. Each row has an admin ID, a setting name, and a setting value.

For example, a row could be:

id|adminid|setting|value <-column names
1|1|settingName1|5

The code above resulted in variables in this format:

$user_settings['settingName1']

which had the value of "5" from the database.

I'm trying to convert this to the PDO methods that are used by WHMCS. This is my first time working with PDO. I'm trying to get the variable names and values to match the old way so that less code changes are required

So far I came up with this:

    foreach (Capsule::table('tablename')->where('admin_id', '=', $admin_id)->get() as $user_settings) {
echo "<pre>".print_r($user_settings, true)."</pre>";
    }

That outputs:

stdClass Object
(
    [id] => 16
    [admin_id] => 1
    [setting] => settingName1
    [value] => 5
)

stdClass Object
(
    [id] => 15
    [admin_id] => 1
    [setting] => anotherSetting
    [value] => ON
)

stdClass Object
(
    [id] => 14
    [admin_id] => 1
    [setting] => yetAnotherSetting
    [value] => ON
)

I have no idea how to get these settings to match the old format.

For example, the three examples shown above should end up like this:

$user_settings['settingName1'] (value should be: 5)
$user_settings['anotherSetting'] (value should be: ON)
$user_settings['yetAnotherSetting'] (value should be: ON)

I would really appreciate some help as I learn how PDO works.

  • 写回答

3条回答 默认 最新

  • doujian4752 2016-10-10 18:20
    关注

    Speaking of PDO, this brilliant library indeed has a fetch mode designed exactly for your case:

    $stmt = $pdo->prepare("SELECT setting, value FROM tablename WHERE admin_id = ?");
    $stmt->execute([$admin_id]);
    $user_settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    

    While that home-brewed query builder you are using most likely makes this mode unavailable.

    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路