使用WPDB在WP短代码

时间:2017-09-18 07:45:55

标签: database wordpress

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

可悲的是,插件可以完成我需要的所有内容,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完成它吗?

亲切的问候:)

1 个答案:

答案 0 :(得分:0)

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

//连接数据库

<?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 colum1colum2,... FROM”您应该获取所有列,可能是fetchColumn需要替换为不同的东西。