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');
Related
I have the following code, but it doesn't work. I think it might be because the method was removed? Not sure what the new way to do it is though. I'm on wordpress.
<php?
mysql_query ("UPDATE $wpdb->users
SET access_key = $newAccessKey
WHERE ID = $currentUserID");
?>
That don't work.
users is the table nome.
Advice??
This script is to be run on a page on php.
First you start with wrong syntax to start PHP script '
Now you should check the type of access_key if it is integer than you wrote right and if it is varchar or text then you should write with ''. For this your query is below.
mysql_query ("UPDATE $wpdb->users
SET access_key = '$newAccessKey'
WHERE ID = $currentUserID");
I hope you will get solution.
use single quote for string vars and be sure for sanitize $wpdb->users use concat
mysql_query ("UPDATE " . $wpdb->users .
" SET access_key = '$newAccessKey'
WHERE ID = $currentUserID");
The reason why it doesn't work for you can be a number of things. You can find it out by enabling error reporting (ini_set('display_errors', true); error_level(E_ALL);) and checking for mysql errors (echo mysql_error();).
Second, if it wasn't a typo when you were writing the question:
<php? doesn't start PHP code. It should be <?php, the way you wrote it it is ignored both by the server and the browser because it is an illegal tag and the code inbetween isn't executed at all.
Apart from that, $wpdb brings its own update() function that you can use:
$wpdb->update(
$wpdb->users,
array( 'access_key' => $newAccessKey ),
array( 'ID' => $currentUserID ),
array(
'%s' // if $newAccessKey is a string
// '%d' // if $newAccessKey is an integer
),
array( '%d' )
);
That way you don't have to worry about the database connection or deprecated functions.
I can't seem to print the data form mysql using the following code.
Am I missing something?
<?php
mysql_connect("localhost","user","pass");
mysql_select_db("myDB");
$res=mysql_query("select * from myTABLE");
while($row=mysql_fetch_array($res))
{
echo "$row[id]";
?>
Check the PHP Manual on echo,
This part shows you how to print arrays:
// You can also use arrays
$baz = array("value" => "foo");
echo "this is {$baz['value']} !"; // this is foo !
You are missing closing curly bracket. And put id into quotation marks:
<?php
mysql_connect("localhost","user","pass");
mysql_select_db("myDB");
$res=mysql_query("select * from myTABLE");
while($row=mysql_fetch_array($res))
{
echo $row['id'];
}
?>
I recommend using mysqli. mysql extension is deprecated.
Appreciate your responses. I am able to make it work now.
I am trying to make the code more specific and secure.
I tried joining two tables, using this and it won't print the id from main (m.id) and category_name on c.category_name table.
$res = mysqli_query("SELECT m.id, c.category_name FROM `main` AS m INNER JOIN `categories` AS c ON m.category_id=c.id");
The code below works
$res = mysql_query("SELECT * from main");
Regarding connecting to the db via a separate file. This doesn't work. And no errors are being display on the php even after adding error_reporting.
require_once('../../../hide/dbconn.php');
instead of using below
mysql_connect("localhost","user","pass");
mysql_select_db("myDB");
Can i use where and order by in mysql together like this
$results=mysql_query("SELECT `status_content`
FROM `status`
WHERE `user_id`=".$_SESSION['user_id']."
ORDER BY `status_time` DESC" );
her is my code, but it is giving me error
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\lr\profile.php on line 65
<?php
$results=mysql_query("SELECT status_content FROM status
WHERE user_id=".$_SESSION['user_id']."
ORDER BY status_time DESC" );
while($row=mysql_fetch_array($results)) {
echo $row['status_content'];
}
?>
yes, this is valid as google will tell you http://dev.mysql.com/doc/refman/5.0/en/select.html
For your actual error, from the php docs:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
// do something
}
Also: you should not use the mysql_* functions anymmore since they are deprecated and unsafe.
Use mysqli_* or PDO instead.
i keep having this error "mysql_fetch_array() expects parameter 1 to be resource, null given in" when i try to display the returned value of count in sql. heres my code.
$query="SELECT med_rec_ID, COUNT(med_rec_ID)
FROM med_issue
WHERE MONTH(issue_date) = MONTH('2013-02-05')
GROUP BY med_rec_ID";
$result= mysql_query($query);
while($count = mysql_fetch_array($display3)){
echo $count[0];
}
i have tried to run the query in sql alone it displays 2 columns (the med_rec_ID, and the COUNT). guys how do i display the count and fix the error too?
First of all, don't use mysql_* functions since they're deprecated. Use mysqli or PDO.
Secondly, look at what you're passing into the fetch_array function.
You probably want to do something like:
$link = mysqli_connect("localhost", "admin", "pass", "db_name");
$result = mysqli_query($link, $sql);
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$medIds[] = $row['med_rec_ID'];
...
}
Then fix the count by giving it an alias.
Please note that you should actually store how you access the DB in a more secure manner, but I use this only to illustrate the example. Here's a pretty good post: How to create global configuration file?
Is your query even executing? that error will happen if mysql_query doesnt return the resource, in case query fails
$query="SELECT med_rec_ID, COUNT(med_rec_ID) as C FROM med_issue where MONTH(issue_date) = MONTH('2013-02-05') GROUP BY med_rec_ID";
$result= mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
echo $row["C"];
}
Note: Please do not use mysql_* functions anymore
Give it an alias:
SELECT
med_rec_ID,
COUNT(med_rec_ID) TheCount
FROM med_issue
where MONTH(issue_date) = MONTH('2013-02-05') GROUP BY med_rec_ID
then you can select that column TheCount inside the while loop with $row['TheCount'], also use lope through the $result:
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo $row['TheCount'];
}
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();