【问题标题】:using WPDB to display external database-data inside a WP-shortcode使用 WPDB 在 WP-shortcode 中显示外部数据库数据
【发布时间】:2017-09-18 07:45:55
【问题描述】:

我正在尝试找出一种方法来使用 WPDB 从另一个表(不是 Wordpress-DB)加载整行或单个单元格/字段并以简码显示它们。我有一堆天气数据值,我需要数据库的最新行(每列是数据库的另一种数据类型(温度、风、湿度等)。

遗憾的是,可以满足我所有需求的插件 SQL Shortcode 不再起作用了。我现在发现了这个:

https://de.wordpress.org/plugins/shortcode-variables/

虽然我仍然需要使用一些 PHP/PDO-foo 从数据库中获取数据。

通过大量复制和粘贴,我想出了这个:

<?php

$hostname='localhost';
$username='root';
$password='';
$dbname='sensordata';

$result = $db->prepare(SELECT * FROM `daten` WHERE id=(SELECT MAX(id) FROM `daten`););
$result->execute();

while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$data = $row['*'];
}

echo $data;

?>

但显然它不起作用。使用 WPDB 完成它需要什么?

亲切的问候:)

【问题讨论】:

    标签: database wordpress


    【解决方案1】:

    以防万一其他人将来需要这个。我现在用这个:

    //连接数据库

    <?php
    $dbh = new PDO('mysql:host=localhost;dbname=databasename', 'dbuser',  
     'dbpasswort'); 
    
    //query the database "databasename", selecting "columnname" from table "tablename", checking that said column has no NULL entry, sort it by column "id" (autoincrementing numeric ID), newest first and just fetch the last one
    
    $sth = $dbh->query("SELECT `columnname` FROM `tablename` WHERE `columnname` IS NOT NULL order by id desc limit 1")->fetchColumn(0);
    
    //print the value/number
    
    print_r($sth);   
    
    ?>
    

    通过使用 "SELECT colum1, colum2,... FROM" 你应该得到所有的列,可能是 fetchColumn 需要用不同的东西替换。

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 2013-09-20
      • 2015-08-11
      • 2020-05-28
      • 2018-12-18
      • 2022-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多