Is there a (better) way to access $wpdb results? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Moderator Election Q&A - Questionnaire 2019 Community Moderator Election ResultsRetrieving multisite blog IDs, somehow failing to foreach them properlyChecking if meta_value exists for any userwpdb inside foreach loop only returns first result - 2 other similar cases foundCustom $wpdb returns unexpected time based resultswpdb query problem to access previous 3 days postsaccess JSON results from wordpress database with wpdbIs $wpdb->prepare escaping to much? How to use it properly?How to access PostgreSQL using WPDB?wpdb query not workingWPDB delivers wrong results from complex queries
Generate an RGB colour grid
Is it true that "carbohydrates are of no use for the basal metabolic need"?
Denied boarding although I have proper visa and documentation. To whom should I make a complaint?
Identifying polygons that intersect with another layer using QGIS?
How to align text above triangle figure
Identify plant with long narrow paired leaves and reddish stems
Is the Standard Deduction better than Itemized when both are the same amount?
What does this icon in iOS Stardew Valley mean?
Align equal signs while including text over equalities
How do I stop a creek from eroding my steep embankment?
What's the meaning of 間時肆拾貳 at a car parking sign
3 doors, three guards, one stone
How does the particle を relate to the verb 行く in the structure「A を + B に行く」?
List of Python versions
Dating a Former Employee
Single word antonym of "flightless"
Apollo command module space walk?
If a contract sometimes uses the wrong name, is it still valid?
What's inside the kernel part of virtual memory of 64 bit linux processes?
Use BFD on a Virtual-Template Interface
What to do with chalk when deepwater soloing?
What is the role of the transistor and diode in a soft start circuit?
What is a non-alternating simple group with big order, but relatively few conjugacy classes?
Is it ethical to give a final exam after the professor has quit before teaching the remaining chapters of the course?
Is there a (better) way to access $wpdb results?
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
2019 Moderator Election Q&A - Questionnaire
2019 Community Moderator Election ResultsRetrieving multisite blog IDs, somehow failing to foreach them properlyChecking if meta_value exists for any userwpdb inside foreach loop only returns first result - 2 other similar cases foundCustom $wpdb returns unexpected time based resultswpdb query problem to access previous 3 days postsaccess JSON results from wordpress database with wpdbIs $wpdb->prepare escaping to much? How to use it properly?How to access PostgreSQL using WPDB?wpdb query not workingWPDB delivers wrong results from complex queries
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I have this:
global $wpdb;
$wpdbp = $wpdb->prepare('SELECT EXISTS ([some query] WHERE user_id =%d);',$target_user_id);
$result = $wpdb->get_results($wpdbp);
I want to know if the query result is 1 or 0.
But a var_dump() of $result give something like:
array (size=1)
0 =>
object(stdClass)[4592]
public 'EXISTS ([some query] WHERE user_id =2)' => string '0' (length=1)
Which means I should first get element 0 of array, but then, I need to access a property which name is literally the whole query.
I yet need to test if that is even doable in php (I guess yes but I don't remember in this language precisely), and what happens if I have multiline query ...
Anyway I find that so ugly ... is there a cleaned way to get query result?
Maybe there's a way to give a name string to the query or so?
Here is what I'm trying and this isn't even working ...
$qeryAsPropertyName = substr($wpdbp,7, -strlen($wpdbp-1));
$result0 = $result[0]->$qeryAsPropertyName;
wpdb sql
add a comment |
I have this:
global $wpdb;
$wpdbp = $wpdb->prepare('SELECT EXISTS ([some query] WHERE user_id =%d);',$target_user_id);
$result = $wpdb->get_results($wpdbp);
I want to know if the query result is 1 or 0.
But a var_dump() of $result give something like:
array (size=1)
0 =>
object(stdClass)[4592]
public 'EXISTS ([some query] WHERE user_id =2)' => string '0' (length=1)
Which means I should first get element 0 of array, but then, I need to access a property which name is literally the whole query.
I yet need to test if that is even doable in php (I guess yes but I don't remember in this language precisely), and what happens if I have multiline query ...
Anyway I find that so ugly ... is there a cleaned way to get query result?
Maybe there's a way to give a name string to the query or so?
Here is what I'm trying and this isn't even working ...
$qeryAsPropertyName = substr($wpdbp,7, -strlen($wpdbp-1));
$result0 = $result[0]->$qeryAsPropertyName;
wpdb sql
1
That might be a MySQL-generated column name. You could trySELECT EXISTS (...) AS nameto give it a different name (where you can quote name in backticks).
– Rup
9 hours ago
This worked thank you. If you write it as answer I can check it as solution.
– TTT
9 hours ago
add a comment |
I have this:
global $wpdb;
$wpdbp = $wpdb->prepare('SELECT EXISTS ([some query] WHERE user_id =%d);',$target_user_id);
$result = $wpdb->get_results($wpdbp);
I want to know if the query result is 1 or 0.
But a var_dump() of $result give something like:
array (size=1)
0 =>
object(stdClass)[4592]
public 'EXISTS ([some query] WHERE user_id =2)' => string '0' (length=1)
Which means I should first get element 0 of array, but then, I need to access a property which name is literally the whole query.
I yet need to test if that is even doable in php (I guess yes but I don't remember in this language precisely), and what happens if I have multiline query ...
Anyway I find that so ugly ... is there a cleaned way to get query result?
Maybe there's a way to give a name string to the query or so?
Here is what I'm trying and this isn't even working ...
$qeryAsPropertyName = substr($wpdbp,7, -strlen($wpdbp-1));
$result0 = $result[0]->$qeryAsPropertyName;
wpdb sql
I have this:
global $wpdb;
$wpdbp = $wpdb->prepare('SELECT EXISTS ([some query] WHERE user_id =%d);',$target_user_id);
$result = $wpdb->get_results($wpdbp);
I want to know if the query result is 1 or 0.
But a var_dump() of $result give something like:
array (size=1)
0 =>
object(stdClass)[4592]
public 'EXISTS ([some query] WHERE user_id =2)' => string '0' (length=1)
Which means I should first get element 0 of array, but then, I need to access a property which name is literally the whole query.
I yet need to test if that is even doable in php (I guess yes but I don't remember in this language precisely), and what happens if I have multiline query ...
Anyway I find that so ugly ... is there a cleaned way to get query result?
Maybe there's a way to give a name string to the query or so?
Here is what I'm trying and this isn't even working ...
$qeryAsPropertyName = substr($wpdbp,7, -strlen($wpdbp-1));
$result0 = $result[0]->$qeryAsPropertyName;
wpdb sql
wpdb sql
edited 9 hours ago
TTT
asked 9 hours ago
TTTTTT
1728
1728
1
That might be a MySQL-generated column name. You could trySELECT EXISTS (...) AS nameto give it a different name (where you can quote name in backticks).
– Rup
9 hours ago
This worked thank you. If you write it as answer I can check it as solution.
– TTT
9 hours ago
add a comment |
1
That might be a MySQL-generated column name. You could trySELECT EXISTS (...) AS nameto give it a different name (where you can quote name in backticks).
– Rup
9 hours ago
This worked thank you. If you write it as answer I can check it as solution.
– TTT
9 hours ago
1
1
That might be a MySQL-generated column name. You could try
SELECT EXISTS (...) AS name to give it a different name (where you can quote name in backticks).– Rup
9 hours ago
That might be a MySQL-generated column name. You could try
SELECT EXISTS (...) AS name to give it a different name (where you can quote name in backticks).– Rup
9 hours ago
This worked thank you. If you write it as answer I can check it as solution.
– TTT
9 hours ago
This worked thank you. If you write it as answer I can check it as solution.
– TTT
9 hours ago
add a comment |
2 Answers
2
active
oldest
votes
The string you're seeing is the column name that MySQL is using for the result, because it doesn't have any better ideas. One way is to give it an explicit name to use instead with AS, e.g.
global $wpdb;
$wpdbp = $wpdb->prepare('SELECT EXISTS ([some query] WHERE user_id =%d) AS `exists`;',
$target_user_id);
$result = $wpdb->get_results($wpdbp);
then the column name will be exists, i.e.
$result = $result[0]['exists'];
However I'm surprised there isn't a 'execute query and return scalar' method in $wpdb that you can use instead to just fetch a single result like this.
add a comment |
The WPDB Class has quite a few methods which vary what will be returned.
Using WPDB::get_results() returns an array of objects whose properties end up being what it expects to be returned. In this case may be best to alias your subquery. For example, if I wanted to check if user ID 1 exists I could say:
$results = $wpdb->get_results( "SELECT EXISTS( SELECT ID FROM $wpdb->users WHERE ID = 1 ) AS 'exists'" );
if( ! empty( $results ) && $results[0]->exists )
/* ... */
A better solution would be, if you just want one thing returned, you could use WPDB::get_var()
$exists = $wpdb->get_var( $wpdb->prepare( "
SELECT EXISTS ( [some query] WHERE user_id = %d )
", $user_id ) );
if( $exists )
/* ... */
Or if you wanted the username by ID:
$username = $wpdb->get_var( $wpdb->prepare( "
SELECT user_login FROM $wpdb->users WHERE ID = %d
", $user_id ) );
if( ! empty( $username ) )
printf( 'User %d user name is: %s', $user_id, $username );
That being said your best bet is to read through the documentation and look at the available methods to figure out which is best in your user case:
https://codex.wordpress.org/Class_Reference/wpdb
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "110"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fwordpress.stackexchange.com%2fquestions%2f334503%2fis-there-a-better-way-to-access-wpdb-results%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
The string you're seeing is the column name that MySQL is using for the result, because it doesn't have any better ideas. One way is to give it an explicit name to use instead with AS, e.g.
global $wpdb;
$wpdbp = $wpdb->prepare('SELECT EXISTS ([some query] WHERE user_id =%d) AS `exists`;',
$target_user_id);
$result = $wpdb->get_results($wpdbp);
then the column name will be exists, i.e.
$result = $result[0]['exists'];
However I'm surprised there isn't a 'execute query and return scalar' method in $wpdb that you can use instead to just fetch a single result like this.
add a comment |
The string you're seeing is the column name that MySQL is using for the result, because it doesn't have any better ideas. One way is to give it an explicit name to use instead with AS, e.g.
global $wpdb;
$wpdbp = $wpdb->prepare('SELECT EXISTS ([some query] WHERE user_id =%d) AS `exists`;',
$target_user_id);
$result = $wpdb->get_results($wpdbp);
then the column name will be exists, i.e.
$result = $result[0]['exists'];
However I'm surprised there isn't a 'execute query and return scalar' method in $wpdb that you can use instead to just fetch a single result like this.
add a comment |
The string you're seeing is the column name that MySQL is using for the result, because it doesn't have any better ideas. One way is to give it an explicit name to use instead with AS, e.g.
global $wpdb;
$wpdbp = $wpdb->prepare('SELECT EXISTS ([some query] WHERE user_id =%d) AS `exists`;',
$target_user_id);
$result = $wpdb->get_results($wpdbp);
then the column name will be exists, i.e.
$result = $result[0]['exists'];
However I'm surprised there isn't a 'execute query and return scalar' method in $wpdb that you can use instead to just fetch a single result like this.
The string you're seeing is the column name that MySQL is using for the result, because it doesn't have any better ideas. One way is to give it an explicit name to use instead with AS, e.g.
global $wpdb;
$wpdbp = $wpdb->prepare('SELECT EXISTS ([some query] WHERE user_id =%d) AS `exists`;',
$target_user_id);
$result = $wpdb->get_results($wpdbp);
then the column name will be exists, i.e.
$result = $result[0]['exists'];
However I'm surprised there isn't a 'execute query and return scalar' method in $wpdb that you can use instead to just fetch a single result like this.
answered 9 hours ago
RupRup
776715
776715
add a comment |
add a comment |
The WPDB Class has quite a few methods which vary what will be returned.
Using WPDB::get_results() returns an array of objects whose properties end up being what it expects to be returned. In this case may be best to alias your subquery. For example, if I wanted to check if user ID 1 exists I could say:
$results = $wpdb->get_results( "SELECT EXISTS( SELECT ID FROM $wpdb->users WHERE ID = 1 ) AS 'exists'" );
if( ! empty( $results ) && $results[0]->exists )
/* ... */
A better solution would be, if you just want one thing returned, you could use WPDB::get_var()
$exists = $wpdb->get_var( $wpdb->prepare( "
SELECT EXISTS ( [some query] WHERE user_id = %d )
", $user_id ) );
if( $exists )
/* ... */
Or if you wanted the username by ID:
$username = $wpdb->get_var( $wpdb->prepare( "
SELECT user_login FROM $wpdb->users WHERE ID = %d
", $user_id ) );
if( ! empty( $username ) )
printf( 'User %d user name is: %s', $user_id, $username );
That being said your best bet is to read through the documentation and look at the available methods to figure out which is best in your user case:
https://codex.wordpress.org/Class_Reference/wpdb
add a comment |
The WPDB Class has quite a few methods which vary what will be returned.
Using WPDB::get_results() returns an array of objects whose properties end up being what it expects to be returned. In this case may be best to alias your subquery. For example, if I wanted to check if user ID 1 exists I could say:
$results = $wpdb->get_results( "SELECT EXISTS( SELECT ID FROM $wpdb->users WHERE ID = 1 ) AS 'exists'" );
if( ! empty( $results ) && $results[0]->exists )
/* ... */
A better solution would be, if you just want one thing returned, you could use WPDB::get_var()
$exists = $wpdb->get_var( $wpdb->prepare( "
SELECT EXISTS ( [some query] WHERE user_id = %d )
", $user_id ) );
if( $exists )
/* ... */
Or if you wanted the username by ID:
$username = $wpdb->get_var( $wpdb->prepare( "
SELECT user_login FROM $wpdb->users WHERE ID = %d
", $user_id ) );
if( ! empty( $username ) )
printf( 'User %d user name is: %s', $user_id, $username );
That being said your best bet is to read through the documentation and look at the available methods to figure out which is best in your user case:
https://codex.wordpress.org/Class_Reference/wpdb
add a comment |
The WPDB Class has quite a few methods which vary what will be returned.
Using WPDB::get_results() returns an array of objects whose properties end up being what it expects to be returned. In this case may be best to alias your subquery. For example, if I wanted to check if user ID 1 exists I could say:
$results = $wpdb->get_results( "SELECT EXISTS( SELECT ID FROM $wpdb->users WHERE ID = 1 ) AS 'exists'" );
if( ! empty( $results ) && $results[0]->exists )
/* ... */
A better solution would be, if you just want one thing returned, you could use WPDB::get_var()
$exists = $wpdb->get_var( $wpdb->prepare( "
SELECT EXISTS ( [some query] WHERE user_id = %d )
", $user_id ) );
if( $exists )
/* ... */
Or if you wanted the username by ID:
$username = $wpdb->get_var( $wpdb->prepare( "
SELECT user_login FROM $wpdb->users WHERE ID = %d
", $user_id ) );
if( ! empty( $username ) )
printf( 'User %d user name is: %s', $user_id, $username );
That being said your best bet is to read through the documentation and look at the available methods to figure out which is best in your user case:
https://codex.wordpress.org/Class_Reference/wpdb
The WPDB Class has quite a few methods which vary what will be returned.
Using WPDB::get_results() returns an array of objects whose properties end up being what it expects to be returned. In this case may be best to alias your subquery. For example, if I wanted to check if user ID 1 exists I could say:
$results = $wpdb->get_results( "SELECT EXISTS( SELECT ID FROM $wpdb->users WHERE ID = 1 ) AS 'exists'" );
if( ! empty( $results ) && $results[0]->exists )
/* ... */
A better solution would be, if you just want one thing returned, you could use WPDB::get_var()
$exists = $wpdb->get_var( $wpdb->prepare( "
SELECT EXISTS ( [some query] WHERE user_id = %d )
", $user_id ) );
if( $exists )
/* ... */
Or if you wanted the username by ID:
$username = $wpdb->get_var( $wpdb->prepare( "
SELECT user_login FROM $wpdb->users WHERE ID = %d
", $user_id ) );
if( ! empty( $username ) )
printf( 'User %d user name is: %s', $user_id, $username );
That being said your best bet is to read through the documentation and look at the available methods to figure out which is best in your user case:
https://codex.wordpress.org/Class_Reference/wpdb
answered 9 hours ago
Howdy_McGee♦Howdy_McGee
13.7k1459127
13.7k1459127
add a comment |
add a comment |
Thanks for contributing an answer to WordPress Development Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fwordpress.stackexchange.com%2fquestions%2f334503%2fis-there-a-better-way-to-access-wpdb-results%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
-sql, wpdb
1
That might be a MySQL-generated column name. You could try
SELECT EXISTS (...) AS nameto give it a different name (where you can quote name in backticks).– Rup
9 hours ago
This worked thank you. If you write it as answer I can check it as solution.
– TTT
9 hours ago