using WPDB to display external database-data inside a WP-shortcode - database

I'm trying to figure out a way to use WPDB to load a whole row or single cells/fields from another table (not the Wordpress-DB) and displaying them in a shortcode. I have a bunch of weatherdata-values, I need the latest row (each column is another data-type (temp, wind, humidity, etc) of the database for a start.
Sadly, the plugin that would do everything that I need, SQL Shortcode, doesn't work anymore. I found this now:
https://de.wordpress.org/plugins/shortcode-variables/
Though I still need to use some PHP/PDO-foo to get the data from the database.
By heavy copy&pasting I came up with this:
<?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;
?>
But obviously it's not working. What I need to get it done with WPDB?
kind regards :)

Just in case anyone else needs this in the future. I used this now:
//connect to the database
<?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);
?>
By using "SELECT colum1, colum2,... FROM" You should get all the columns, could be that fetchColumn needs to be replaced with something different though.

Related

How can I make bulkCopy map the same columns?

Suppose I have a SQL Table that has these columns:
[server_name],[SESSION_ID],[SESSION_SPID]
I am trying to copy values stored in a data table ($dmvResult) to the SQL Table above ($Table)
$dmvResult = DMV_Query 'SELECT [SESSION_ID]
,[SESSION_SPID]
FROM $SYSTEM.DISCOVER_SESSIONS';
$ConnectionString ='Data Source=$server; Database=$database; Trusted_Connection=True;'
$bulkCopy = new-object Data.SqlClient.SqlBulkCopy($ConnectionString)
$bulkCopy.DestinationTableName=$Table
$bulkCopy.WriteToServer($dmvResult)
While the copying is being done successfully, there is an issue: it's copying by position, not by column name match. In other words, the copied columns are not being mapped and copied to the same columns.
[SESSION_ID] is being copied to [server_name] and
[SESSION_SPID] is being copied to [SESSION_ID]
How can I tell bulkCopy to match columns and copy?
The result copy should be [server_name] being empty because it wasn't selected from DMV query.
I found a neat solution in this thread:
https://stackoverflow.com/a/20045505/8397835
but I dont know how to translate it to my powershell code:
var meta = definition.Context.Mapping.GetMetaType(typeof(T));
foreach (var col in meta.DataMembers)
{
copy.ColumnMappings.Add(col.Member.Name, col.MappedName);
}
EDIT: foreach column.ColumnName output
EDIT2:
i tried this:
$dmvResult.Columns |%{$_.Name}
and it doesnt output anything.
before you say $dmvResult data table must be empty then, explain how is it possible that this actually works and copies in data?
$bulkCopy.ColumnMappings.Add('SESSION_ID', 'SESSION_ID')
$bulkCopy.ColumnMappings.Add('SESSION_SPID', 'SESSION_SPID')
$bulkCopy.WriteToServer($dmvResult)
and for some reason, its outputting this to the console as well:
so the data table $dmvResult is clearly populated.
i was hoping instead of defining mapping for every single column like this:
$bulkCopy.ColumnMappings.Add('SESSION_SPID', 'SESSION_SPID')
instead there would be anutomatic option like this:
foreach ($column in $dmvResult.Columns) { $bulkCopy.ColumnMappings.Add($column.ColumnName, $column.ColumnName)}
but that throws exception:
Exception calling "WriteToServer" with "1" argument(s): "The given
ColumnMapping does not match up with any column in the source or
destination."
A very weird solution but I just had to add a comma here before $dataset:
,$dataSet.Tables[0]
in the DMV_Query function
and then i used this foreach loop
foreach ($column in $dmvResult.Columns) { $bulkCopy.ColumnMappings.Add($column.ColumnName, $column.ColumnName) > $null }
and it worked!
it now maps the columns automatically!!

Mage::getModel but from another database don't work

I've managed to create a module that can connect to a second database next that one from the shop. It started an setup script to create the new table and I inserted one test data.
So far so good.
Now I want to get that data inside an observer.
I can get the model and the collection. Bbut when I count that collection it returns null. When I try getSelectSql(true) on that model that query looks like:
SELECT `main_table`.* FROM `custom_table` AS `main_table`
Running that query in the database returns my added test data.
app/etc/local.xml
<config>
<global>
<resources>
<external_db>
<connection>
<host><![CDATA[127.0.0.1]]></host>
<username><![CDATA[db_user]]></username>
<password><![CDATA[db_pass]]></password>
<dbname><![CDATA[external_db]]></dbname>
<active>1</active>
</connection>
Observer
public function validateRequest(Varien_Event_Observer $observer) {
try {
$collection = Mage::getModel('custom_module/custom_table')->getCollection();
$items = $collection->getItems();
That returns me the following exception:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'shop.custom_table' doesn't exist, query was: SELECT main_table.* FROM custom_table AS main_table
It looks like magento isn't able to choose the correct connection.
But I can't find the way to change that in a magento way.
The only way it works is:
$resource = Mage::getSingleton('core/resource');
$conn = $resource->getConnection('externaldb_read');
$results = $conn->query('SELECT * FROM custom_table');
I would like to do it without creating raw queries.
use setConnection() method before you load your collection. The Argument should be a valid core/resource object with your database selected.

Tuncate CakePHP 3.X table and reset Auto Incremented id

In the old cakePHP 2.X I used this statement:
$this->Products->query('TRUNCATE TABLE products;');
which was the only way I could get my ids reset to 1. Now in cakephp 3.X this does not seem to truncate the table at all.
I have tried:
deleteAll();
Which works but seems to always need a condition but most importantly does not reset the ID;
query()->delete()->execute();
Deletes everything but does not reset the ids.
Does anyone know how to accomplish this in Cakephp 3.2
Include "ConnectionManager" namespace in the controller
use Cake\Datasource\ConnectionManager;
Create connection string and execute query in your action
$connection = ConnectionManager::get('default');
$results = $connection->execute('TRUNCATE TABLE tableName');
The way you can execute arbitrary queries in CakePHP3 is:
$connection = \Cake\Datasource\ConnectionManager::get('default');
$connection->execute('TRUNCATE TABLE products');
http://book.cakephp.org/3.0/en/orm/database-basics.html#database-basics

Want to add to database, but not showing/Working

this code keeps saying that the "Record has been Added", yet it's no where to be seen on phpmyadmin...Any thoughts?
phpmyadmin: localhost>summative>Data
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
if(!$con)(die("could not connect " . mysql_error()));
mysql_select_db("summative") or die(mysql_error());
mysql_query("INSERT INTO Data(First Assister) VALUES('$_GET[assist1]')");
if("INSERT INTO Data(First Assister) VALUES('$_GET[assist1]'");
{
echo "Record Added";
}
?>
1.) mysql is now deprecated use mysqli... from http://us2.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended
for writing new code as it will be removed in the future. Instead,
either the mysqli or PDO_MySQL extension should be used. See also the
MySQL API Overview for further help while choosing a MySQL API.
2.) Are you seriously setting $_GET data into your database?
3.) Are you seriously setting $_GET data into your database without escaping it? ALWAYS escape user provided data when putting it into your databse unless you enjoy getting hacked by Chinese government sponsored hackers (or Russian, or Netherlands, or Brazil... or lesser common countries, but those are the most common as far as I've been hack attempted)
See the docs for mysqli_real_escape_string: http://us2.php.net/manual/en/mysqli.real-escape-string.php
2.) Where are you getting that INSERT format from? In MySQL the format is:
INSERT INTO table_name VALUES (value1, value2, value3,...)
From: http://www.w3schools.com/php/php_mysql_insert.asp
Personally, I prefer the other INSERT format:
INSERT [LOW_PRIORITY |
DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name,...)]
SET col_name={expr | DEFAULT}, ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
4.) What is your table name? I see a DB name, and I THINK a column name, and then a value...
So I'd change your INSERT statement to this:
$value = mysqli_real_escape_string($_GET['param']);
$sql = 'INSERT INTO `table_name` SET `column`="'.$value.'";';
$result = mysqli_query($sql);

How to list all rows from table and display specific column data from wordpress database

I have table called wp_email_subscription and inside table I have rows of emails from subscribed users. Each row contains id, email, and name column.
I have also created admin page for plugin where I would like to list all emails from subscribed table.
Basically I don't know how to use wpdb functions, I have read wpdb instructions from wp website but I don't understand.
what I need is to select all from wp_email_subscription and foreach row to display email and name column in list.
you have to use global wpdp variable and get_result function in your code page like this...
global $wpdb;
$row = $wpdb->get_results( "SELECT * FROM wp_email_subscription");
foreach ( $row as $row )
{ echo "email:".$row->email.";} //$row->your_column_name in table
like this, you can access all columns by $variable->col_name

Resources