Wordpress How to retrieve results from database using $wpdb - sql

I have a table of values and I would like a user to choose a row from the list with a drop-down menu in a WordPress page and have values from various columns populated in the same WordPress page.
I am trying to learn how to use the $wpdb class in WordPress to do this, I am trying to understand first how to write something that will be displayed in the user's browser, but I think I might be missing some critical parts:
What I have done is to create a table called 'wp_axleaa' in my WordPress database. I am trying to query this table and the only result I get printed is “Array”
I wrote a plugin as follows:
<?php
/**
* #package Trying to Connect
* #version 1.6
*/
/*
Plugin Name: Trying to Connect
Plugin URI:
Description: Connecting to DB with $wpdb
Author: Paul J
Version: 1.0
Author URI:
*/
function tc_info() {
global $display;
global $wpdb;
$display = $wpdb->get_results(
'
SELECT *
FROM $wpdb->wp_axleaa
');
print $display;
}
add_shortcode('showinfo','tc_info');
?>
Then I put the shortcode [showinfo] into my WordPress site, and when I view the page then it just shows “Array”. If I add a WHERE clause to the SQL statement, then I get an error message on the page.
I am very new to WordPress and writing PHP and would really appreciate any help, I'm sorry if this is a long-winded question...
Thanks very much,

That's because get_results() returns an array. You may want to modify your code like this:
function tc_info()
{
global $wpdb;
$output = '';
$sql = 'SELECT * FROM $wpdb->wp_axleaa';
$rows = $wpdb->get_results( $sql );
if ( $rows ) {
foreach ( $rows as $row ){
$output .= $row[0];
}
}
print $output;
}

Your problem is not exactly retrieving the database info. First, Shortcode values should be returned. Not printed or echoed. Second, you need to do something with the array you're receiving from the DB query.
To have a nicely formatted display of the array contents, instead of print $display;, use:
return '<pre>' . print_r( $display, true ) . '<pre>';
If you want fast progress in learning, you'll need to consult the documentation frequently:
http://codex.wordpress.org/Class_Reference/wpdb
http://php.net/manual/en/function.print-r.php

Related

passing msqli to a function - can't suss out why it's not working

I've searched high and low for an answer on this, but I'm either missing something, or I just can't find anything in this context.
Background - trying to avoid spaghetti frenzy with a little casual project I'm starting; part of this will involve mainly just calls to a mysql database, displaying table content and so on. Simply put, like a CRM I guess.
I may be way off base here, but I want to be able to create my sql calls as functions, which will help if/when I tweak and tune, as well as creating a cleaner code for what I'm looking to do.
So, without further ado, I have this as a demomstration:
echo "<table>";
selectall('actions','content',$mysqli);
echo "</table><br><br>";
What this does is show all rows from my table of 'actions. "content" is just an example field name I'm passing through that I want to display, as it is the main human-relevant field name in that table. I'm also passing $mysqli through here for my function db call.
My function looks like this:
function selectall($s_table,$s_content,$mysqli){
$query = "SELECT * FROM " . $s_table;
$resource = $mysqli->query($query);
if ( !$resource ) throw new Exception($db->error);
while ( $row = $resource->fetch_assoc() ) {
$id = $row['id'];
echo "<tr><td>{$row[$s_content]}</td></tr>";
}
$resource->free();
$mysqli->close();
}
However.... it doesn't work, and it seems to throw a wobbly saying:
Warning: mysqli::query(): Couldn't fetch mysqli
This points to the action within the line $resource = $mysqli->query($query);
I know the function and everything is ok, as if I restate and declare $mysqli within the first line of the function, like so...
$mysqli = new mysqli(username password and so on in here);
... it works spot on.
$mysqli exists and works within the same code that is passing the variable within the function too.
This is early stages, so by shuffling the code around trying to poke the $mysqli pass into life I have perhaps made the code a little messier that intended, so try not to worry too much about that.
Anyone any ideas why it doesn't like this?
D'oh...
I had a
$mysqli->close();
in the lines above. Solved myself.
For reference, this is my function:
function selectall($s_table,$s_field,$mysqli){
if ($mysqli->connect_error) {die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);}
$s_table = preg_replace('/[^0-9a-zA-Z_]/', '', $s_table); // Cleans up the table name variable
$s_field = preg_replace('/[^0-9a-zA-Z_]/', '', $s_field); // Cleans up the field name variable
$query = "SELECT * FROM " . $s_table; // Adds passed table name to the select all
$resource = $mysqli->query($query);
if ( !$resource ) throw new Exception($db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "<tr><td>{$row[$s_field]}</td></tr>"; // Content for each row of the select all
}
$resource->free();
$mysqli->close();
}
As you can see, I've also tried to protect the variables that enter the function.
This can be called via:
selectall('actions','content',$mysqli);
In this context, I want to view all the entries in the 'actions' table by the field name 'content'. This function, with some code above and below for a table, will create a new row for each entry.
I'll probably evolve a few, already created on that includes a delete button at the end of the line which is 'selectalldel'.
Open to comments on whether this actually is worthwhile, but thought I'd post up my corrected stupidity in case anyone finds this useful.

Perl6 API with Slang::SQL

Hi im trying to do an API in Perl6 using Bailador, DBIish and Slang::SQL but when I try to use
sql select * from user where nom='"$name"'; do -> $row {
"$row".say;
}
instead of
sql select * from user where nom="try"; do -> $row {
"$row".say;
}
it dont tell me anything :c (obviously $name == "try")
I search for hour on the internet but with no answer. I already try to use only DBIish synthaxe but it end with the same result. Can someone help me :) ?
You should be using place holders is the main reason why. The slang doesn't do quoting of that kind, and even if it did you'd be introducing a point of entry for a SQL injection exploit in your code - unless you escaped quotes in the variable.
Instead try:
sql select * from user where nom = ?; with ($name) do -> $row {
$row.say;
}
Good luck with your app. BTW there's a subreddit that'd be interested in your progress https://www.reddit.com/r/perl6
So I tried Matt Oates's answer but it didn't give me anything back (like if it didn't find anything in the DB). But I finally found the syntax that did the job:
my $email = request.params<email>;
my $db = 'SELECT * FROM user WHERE email=?';
my $do = $*DB.prepare($db);
$do.execute($email);
my %row = $do.fetchrow_hashref;
return (%row);

Joomla: how to load JTable-element with LIKE-condition

I am using the following code to load a categorys record:
$res = JTable::getInstance('category');
$res->load(array('id' => $catid));
Now I would like to load the record based on its title which whould be matched against a SQL LIKE-pattern - is it possible to do this in a simple way with JTable, or do I need $dbo?
Far as I know JTable is made to be simple and carry only one element at a time, and through the primary key. If you really want something more advanced, I recomend that you use JDatabaseQuery way.
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select all articles for users who have a username which starts with 'a'.
// Order it by the created date.
$query
->select(array('a.*', 'b.username', 'b.name'))
->from('#__content AS a')
->join('INNER', '#__users AS b ON (a.created_by = b.id)')
->where('b.username LIKE \'a%\'')
->order('a.created DESC');
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects.
$results = $db->loadObjectList();
In your case, instead of "$db->loadObjectList();" you can use "$db->loadObject();" for load just one item.
Source:
http://docs.joomla.org/Accessing_the_database_using_JDatabase/3.1

Sorting posts on a WordPress site with custom SQL

I have a php function that generates a comma separated list of Post IDs that specify the order those posts should display on my WordPress site.
I'm looking for a place I can insert an SQL query like:
SELECT * FROM wp_posts WHERE ID IN ('1', '2', '3')
Which .php file should I modify? How should I phrase the SQL?
Paste your php function in file (root wordpress folder)/wp-content/themes/(name of your theme)/functions.php
SQL query should be like.
$sql=$wpdb->prepare("SELECT * FROM wp_posts WHERE ID IN ('1', '2', '3');");
$results=$wpdb->get_results($sql);
echo ">>>>".$result[0]->something."<br />";//blah blah...
WoW,i did not mention $wpdp as global,still code was working fine on my system!,anyways
i would suggest you write "global $wpdb" in your function.
Now the main question is from where should you call this function;
you have to call it from theme/(your theme)/index.php
Try figuring out how the posts are generated in your current theme,and you might get what you need to do!
First off you should use wp_query for this. It is designed to query posts.
<?php
$args = array(
'post__in' => array ( 1,2,3) //the Ids
);
$query = new WP_Query($args);
if ($query->have_posts()){
while ($query->have_posts()) {
$query->the_post();
echo get_the_ID().'<br/>';
}
} else {
echo 'no posts found';
}
About the placement
I advise to do it in a custom template, make a simple template with the code above, create a page assign it that template and make the page private.
global $wpdb; $results = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE ID IN (1, 2, 3) ORDER BY ID");
You can use that in your theme's functions.php file.

How can I see CakePHP's SQL dump in the controller?

Is there a way that one can cause CakePHP to dump its SQL log on demand? I'd like to execute code up until a point in my controller and see what SQL has been run.
Try this:
$log = $this->Model->getDataSource()->getLog(false, false);
debug($log);
http://api.cakephp.org/2.3/class-Model.html#_getDataSource
You will have to do this for each datasource if you have more than one though.
There are four ways to show queries:
This will show the last query executed of user model:
debug($this->User->lastQuery());
This will show all executed query of user model:
$log = $this->User->getDataSource()->getLog(false, false);
debug($log);
This will show a log of all queries:
$db =& ConnectionManager::getDataSource('default');
$db->showLog();
If you want to show all queries log all over the application you can use in view/element/filename.ctp.
<?php echo $this->element('sql_dump'); ?>
If you're using CakePHP 1.3, you can put this in your views to output the SQL:
<?php echo $this->element('sql_dump'); ?>
So you could create a view called 'sql', containing only the line above, and then call this in your controller whenever you want to see it:
$this->render('sql');
(Also remember to set your debug level to at least 2 in app/config/core.php)
Source
for cakephp 2.0
Write this function in AppModel.php
function getLastQuery()
{
$dbo = $this->getDatasource();
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
To use this in Controller
Write : echo $this->YourModelName->getLastQuery();
It is greatly frustrating that CakePHP does not have a $this->Model->lastQuery();. Here are two solutions including a modified version of Handsofaten's:
1. Create a Last Query Function
To print the last query run, in your /app_model.php file add:
function lastQuery(){
$dbo = $this->getDatasource();
$logs = $dbo->_queriesLog;
// return the first element of the last array (i.e. the last query)
return current(end($logs));
}
Then to print output you can run:
debug($this->lastQuery()); // in model
OR
debug($this->Model->lastQuery()); // in controller
2. Render the SQL View (Not avail within model)
To print out all queries run in a given page request, in your controller (or component, etc) run:
$this->render('sql');
It will likely throw a missing view error, but this is better than no access to recent queries!
(As Handsofaten said, there is the /elements/sql_dump.ctp in cake/libs/view/elements/, but I was able to do the above without creating the sql.ctp view. Can anyone explain that?)
In CakePHP 1.2 ..
$db =& ConnectionManager::getDataSource('default');
$db->showLog();
What worked finally for me and also compatible with 2.0 is to add in my layout (or in model)
<?php echo $this->element('sql_dump');?>
It is also depending on debug variable setted into Config/core.php
Plugin DebugKit for cake will do the job as well. https://github.com/cakephp/debug_kit
If you are interested in some specific part of code, you can clear first the log, and then display only queries that happen after that point.
Also note that 'Model' below, is the actual class name, like User, Page etc.
//clear log (boolean $clear = true)
$this->Model->getDataSource()->getLog(false, true);
...
...
...
...
//Show log so far
$log = $this->Model->getDataSource()->getLog(false, false);
debug($log);
exit;