Data is not constantly loading from custom wordpress table - mysql

global $wpdb;
$tablename_temp = $wpdb->prefix . 'faculty_temp';
$toke = $_GET['token'];
$user = $wpdb->get_results("SELECT * FROM $tablename_temp where token='$toke'");
This is to fetch data from custom wordpress table, the loads fine sometimes. On some times data isn't fetched. Like I refresh 10 times, data doesn't appear in 1 out of 10 times. Seems to be server issue, while updating files in Advanced File Manager & while getting data in WP data access plugin also has same issue

First of all your code is unsafe. Need to add the sanitize functions and the escaping query to the database
global $wpdb;
$tablename_temp = $wpdb->prefix . 'faculty_temp';
$toke = isset( $_GET['token'] ) ? sanitize_text_field( wp_unslash( $_GET['token'] ) ) : '';
$user = $wpdb->get_results("SELECT * FROM $tablename_temp where token='".$wpdb->esc_like($toke)."'");
The code is valid. Perhaps the problem is that you are simultaneously writing and deleting to the temporary table "faculty_temp" and the fetch request is sent when data is deleted or modified.
Need to change your method for working with temp data

Related

Create variable from MySQL datatable that can be used in HTML code

So I have a MySQL database and would like to create variables from that database that I can use in HTML code.
For example if I use <video blablabla some stuff src="phpVariable" /video>
I don't want to have a static URL in the HTML code. It should be assigned to a variable based on an SQL query. What is the best way to do this?
First, you need to retrieve the data from the database that you wish to use, using a database query. From there, you can loop through all the results and output them.
Replace 'tablename' with the name of the database table and 'columnName' with the column name.
$con should be used to connect to your database. See https://www.php.net/manual/en/pdo.connections.php
$stmt = $con->prepare("SELECT * FROM tablename");
$stmt->execute();
while($row = $stmt->fetch()) {
echo $row['columnName'];
}
If you only needed to retrieve one record, change the code to:
$stmt = $con->prepare("SELECT * FROM tablename");
$stmt->execute();
$row = $stmt->fetch();
echo $row['columnName'];
You can also store the retrieved data as a variable, like this:
$variableName = $row['columnName'];
// Then to use the variable in your code:
echo'<video src='.$variableName.'</video>';
This is very basic PHP though. Have you looked at some online guides?

SQL Syntax Error after updating to WordPress 4.8.2

I have been using a hook in the Advanced Custom Fields plugin (load_field) which loads objects from a table in my database to an ACF select field. The table ('wp_new_royalsliders') is created by the RoyalSlider image slider plugin so i use the hook to populate a select field with the slider names.
This function has worked fine for a long time but recently stopped working - I think after updating core to 4.8.2:
add_filter('acf/load_field/name=media_gallery_slider', 'my_acf_royalslider_choices');
function my_acf_royalslider_choices($field){
$field['choices'] = array();
global $wpdb;
$query = $wpdb->prepare('SELECT * FROM %1$s ORDER BY ID ASC', 'wp_new_royalsliders');
$results = $wpdb->get_results($query);
if(!empty($results)) :
foreach($results as $result) :
$value = $result->id;
$label = $result->name;
$field['choices'][ $value ] = $label;
endforeach;
endif;
return $field;
}
When I turn debugging on I get an error:
WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%1$s ORDER BY ID ASC' at line 1]
SELECT * FROM %1$s ORDER BY ID ASC
When you pass in a hardcoded string value, you don't need placeholders, you can just use
$query = $wpdb->prepare('SELECT * FROM wp_new_royalsliders ORDER BY ID ASC');
If you want to get fancy and portable, you might opt for
$query = $wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'new_royalsliders ORDER BY ID ASC');
So it would work on other prefixes, too, but that might not be necessary if this is a very custom thing that's not going to make it into any other site.
It appears that others have noted the removal of that possibility too, see this request.
Update: as $wpdb->prepare() expects a second parameter (since its job is to escape variable inputs for use in SQL), it might complain. Solution: get rid of it and give your SQL directly to get_results:
$results = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'new_royalsliders ORDER BY ID ASC');

Yii2 - Connect to database inside Controller Action

Greetings,
Facts:
Database named -> acastro
Table called -> contacto
Fields in table are -> id, nome, email
I making an Yii2 application, and need to connect a highcharts chart to a table field in my database.
How can i inside an action called actionAdmin connect to my database and then count the number of id's in my Contacto table stored inside acastro database.
In the old Yii1.xx i used to establish connection this way:
public function actionAdmin() {
$sql = Yii::app()->db->createCommand('
SELECT count(*) as total
FROM contacto
')->queryAll();
$total = array();
for ($i = 0; $i < sizeof($sql); $i++){
$total[] = (int) $sql[$i]["total"];
}
$this->render('admin', array('total' => $total));
}
}
The problem is that this syntax no longer works in Yii2, and i've tried the sintaxe explained in Yii2 api guide but it always give's me error of undefined variable. Here is the code that i'm using to connect acording to Yii2 api guide:
use yii\db\Command;
$total = $connection->createCommand('SELECT count (*) FROM contacto')->queryAll();
What am i doing wrong ? Any solutions ?
Many thanks in advance.
I am not very sure that it will solve ur problem.
But in yii2 this the syntax
use app\models\Contacto; //look your Contacto Model namespace
$query = (new Query())->from('contacto');
$count = $query->count('column_name');
I hope this will help
The easiest syntax in Yii2 is:
$count=(new \yii\db\Query)->from('TBL_NAME')->count('*');
It just returns the count. For example: 500

Wordpress Plugin Custom Databse Query (SQL UPDATE SET WHERE)

Quick background:
CRUD plugin
WP 3.5
Creating this plugin for my personal knowledge - I'm sure one already exists.
Variables echo out ok.
The create portion of plugin needed 3 hours of research to get the query to work. Tried everything in codex, a handful of answers from Stack Overflow until something worked.
Problem:
Updating a row in a custom table.
This query will work in SQL ->
UPDATE wp_current_issue SET issue_year=9999, issue_month=29 WHERE issue_id=17;
Tried:
global $wpdb;
$wpdb->update(CURRENT_ISSUE_TABLE,
array(
'issue_year' => $issue_year,
'issue_month' => $issue_month
),
array('issue_id' => $issue_edit_id),
array('%d','%d'),
array('%d'));
As well as: (with and without backticks around column names)
global $wpdb;
$sql = $wpdb->prepare("UPDATE wp_current_issue SET issue_year=".$issue_year.", issue_month=".$issue_month." WHERE issue_id=".$issue_edit_id);
$wpdb->query($sql);
Now the funny thing is, I went through the same thing with the INSERT INTO statement. Tried everything. Only thing that would work is this:
global $wpdb;
$sql = $wpdb->prepare(
"INSERT INTO `".CURRENT_ISSUE_TABLE."` (`issue_path`,`issue_img_path`,`issue_year`,`issue_month`) VALUES (%s,%s,%d,%d)", $fileName_issue, $fileName_img, $issue_year, $issue_month);
$wpdb->query($sql);
Anyone know how I could rewrite this query for an update statement?
Assuming I understood your problem correctly if you want to rewrite that insert into an update then just use
$sql = $wpdb->prepare(
"UPDATE `".CURRENT_ISSUE_TABLE."` SET `issue_path` = %s, `issue_img_path` = %s, `issue_year` = %s, `issue_month` = %s
WHERE issue_id = %i", $fileName_issue, $fileName_img, $issue_year, $issue_month, $issue_edit_id);
The rest is the same.

Joomla Database - How to use LIMIT in getQuery?

I want to build the below query using joomla inbuilt database class.
SELECT *
FROM table_name
ORDER BY id DESC
LIMIT 1
This is the query I have built up to now.
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query->select($db->nameQuote('*'));
$query->from($db->nameQuote(TABLE_PREFIX.'table_name'));
$db->setQuery($query);
$rows = $db->loadObjectList();
I don't know how to add the limit(LIMIT 1) to the query. Can someone please tell me how to do it? Thanks
Older than Joomla 3.0
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('*')
->from($db->nameQuote('#__table_name'))
->order($db->nameQuote('id').' desc');
$db->setQuery($query,0,1);
$rows = $db->loadObjectList();
$db->setQuery function takes 3 parameters. The first one being the query, then the start, then the limit. We can limit records as shown above.
Newer than Joomla 3.0
setLimit(integer $limit, integer $offset)
If you want just one row
$query->setLimit(1);
Read more
This should work as well:
$query->setLimit(1);
Documentation: http://api.joomla.org/cms-3/classes/JDatabaseQueryLimitable.html
SetLimit doesn't work for me in Joomla 3.4.x, so try:
Within the model:
protected function getListQuery()
{
// Create a new query object.
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Select some fields
$query->select('*');
$query->from('#__your_table');
$this->setState('list.limit', 0); // 0 = unlimited
return $query;
}
Davids answer: https://joomla.stackexchange.com/questions/4249/model-getlistquery-fetch-all-rows-with-using-jpagination
Run that before the model calls getItems and it will load all the
items for you.
A few caveats with this.
You can also do this outside the model, so if for instance you were in
your view. You could do the following:
$model = $this->getModel(); $model->setState('list.limit', 0);
Sometimes you can do this too early, before the model's state has been
populated, which will cause the model to get rebuilt from the user
state after you have set the limit, basically overriding the limit.
To fix this, you can force the model to populate its state first:
$model = $this->getModel(); $model->getState();
$model->setState('list.limit', 0); The actual populateState method is
protected, so outside the model you can't call it directly, but any
call to getState will make sure that the populateState is called
before returning the current settings in the state.
Update: Just had to revisit this answer, and I can confirm, both the methods
setLimit & order are working if used as below.
$query->order($db->qn($data->sort_column_name) . ' ' . $data->sort_column_order);
$query->setLimit($length,$start);
OLD ANSWER
As of 08/Sept/14 The solutions from #Dasun or #escopecz arent working for me on J3.x
but this old trick is working for me which is nice,
$query->order($db->qn('id') . ' DESC LIMIT 25');
And About your specific requirement of wishing to fetch only 1 row you could use :
$rows = $db->loadObject();