I'm pretty new to using WordPress and am having an issue with getting my expected result. I am trying to pull from the WordPress database so I am using $wpdb. The following is what I have:
global $wpdb;
echo $wpdb->query("SELECT * FROM wp_users");
Rather than it echoing all of the users, it returns with the number of users in the table. If I add "WHERE id = some number" it echoes that ID number.
What is going wrong and how do I get it to select all from that table?
Thanks.
The function returns an integer corresponding to the number of rows
affected/selected. If there is a MySQL error, the function will return
FALSE. (Note: since both 0 and FALSE can be returned, make sure you
use the correct comparison operator: equality == vs. identicality ===)
You can use get_results to fetch all records
global $wpdb;
$users=$wpdb->get_results( "SELECT * FROM wp_users" );
print_r( $users);
Manual Class_Reference wpdb
Related
how to display count() sql function using php
$results = "SELECT count(votesnumber) FROM `votes` WHERE `candidate_id` = '$candidate_id'";
$queryresults = mysqli_query($connect, $results);
if($queryresults) {
$rowresults = mysqli_fetch_assoc($queryresults);
echo $rowresults['votesnumber'];
} else {
echo "error";
}
i want to display the results of sql count() function using php. am counting specific columns WHERE ID = "some value" in phpmyadmin its working but with php its giving me headache . any ideas on how to solve this?
Try this:
$results = "SELECT count(votesnumber) AS VoteNum FROM `votes` WHERE `candidate_id` = '$candidate_id'";
$queryresults = mysqli_query($connect, $results);
if($queryresults) {
$rowresults = mysqli_fetch_assoc($queryresults);
echo $rowresults['VoteNum'];
} else {
echo "error";
}
First, if you want to refer to the column name by a reference, then you need to give it a better name using an alias:
SELECT COUNT(votesnumber) as votesnumber
ROM `votes`
WHERE `candidate_id` = '$candidate_id';
Second, you should not be munging query strings with parameter values. Instead of '$candidate_id', learn to use parameters. This prevents unexpected syntax errors and SQL injection accounts.
Third, if votesnumber is actually a number of votes, then you probably want SUM() rather than COUNT().
You need to add "AS" instruction to your SQL if you want to get this data as a specific index from array (like $rowresults['votes']):
$results = "SELECT count(votesnumber) AS votes FROM `votes` WHERE `candidate_id` = '$candidate_id'";
Remember that you can always print_r() (for arrays) or var_dump() your variable to check if it contains data you want to have.
I have a MYSQL table called 'devices'. I've successfully done the bin/cake bake all. In fact I have the auto-built DevicesController.php fully working. But I can't figure out how to count the rows in a table. I've tried:
$conn = ConnectionManager::get('default');
$numRows = $conn->execute('select count(*) from devices');
and
$this->DeviceSetups = TableRegistry::get('Devices');
$numRows = $this->Devices->query('select count(*) from devices'); // both like this
$numRows = $this->Devices->query('select count(*) from devices')->execute(); // and like this
and
$this->DeviceSetups = TableRegistry::get('Devices');
$numRows = $this->Devices->find('count');
Going thru mysql_query() isn't really a good idea because I have all the access info already setup in app.php for CakePHP to use. I tried something else using AnyModel that didn't work.
The former 2 attempts return a Cake\Database\Statement\MysqlStatement not an integer with the number of rows in the table. I've consulted this answer and this answer and read the CakePHP docs. Nothing seems to tell me how to count up a table nor how to execute a raw My SQL command string and then access the result.
TableRegistry::get('DeviceSetups')->find()->count();
See http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#getting-a-count-of-results.
If you want to count in table then it should be like below.
$count = $this->find()->count();
echo $count;
I've been out of the mysql and perl game for quite a few years and can't seem to get this right. I have a table with just 3 columns. 'cnt' is one of them. All I want to do is query the table on 'name' and see if name exists. If it does, I want to capture the value of 'cnt'. The table has a record of testName with a value of 2 I added manually. When this script is run it returns empty.
my $count;
my $pop = qq(SELECT cnt FROM popular WHERE name="testName");
my $sth = $dbh->prepare($pop);
$sth->execute() or die $dbh->errstr;
my #return;
while (#return = $sth->fetchrow_array()) {
$count = $return[1];
}
print "our return count is $count";
Is it obvious to anyone what I did wrong?
You probably mean
$count = $return[0];
According to perl doc on mysql
An alternative to fetchrow_arrayref. Fetches the next row of data and returns it as a list containing the field values.
Since you select cnt as the return value ,so , the size of #return is 1,but you misunderstand it as the number of results which meets your query condition.No, it is not so!Please have a more careful reading of perl doc.
I'm trying to create a function to count different table rows in my MySQL database. I have the following script, but when executing it, it will generate an error saying that the variable $con is not set, but it is. So my question is how can I use "global" in this statement?
function countrows($rows){
$sql = mysqli_query($con,"SELECT * FROM $rows");
$num_rows = mysqli_num_rows($sql);
echo $num_rows;
}
If $con is defined in the global scope (that is, it is not created inside any other functions), then make this call:
global $con;
as the first line in that function.
You might also pass it as a function parameter:
function countrows($rows, $con){
...
}
Here's how you do it:
function countrows($rows){
global $con;
$sql = mysqli_query($con,"SELECT * FROM $rows");
$num_rows = mysqli_num_rows($sql);
echo $num_rows;
}
BTW, if the table is large, I recommend using SELECT COUNT(*) instead of SELECT *. The latter requires downloading the entire contents of the table in order to count the rows, the former can usually be done efficiently in SQL.
$urlid = mysql_query("SELECT URL_Id FROM url ORDER BY URL_Id DESC LIMIT 1");
foreach($textnode as $key => $value) {
$value = stripslashes($value);
$value = mysql_real_escape_string($value, $con);
mysql_query("INSERT INTO paragraphs (paragraphs, URL_Id)
VALUES ('$value', '$urlid')");
}
has been returning 0 for the URL_Id column. Any suggestions ? It should be returning 1.
mysql_query function retrieving only resource object. then you need to go with looping and retrieve actual data by mysql_fetch_array() function.
i.e:
while($rowFeach = mysql_fetch_array($urlid));
print_r($rowFeach);
try this.
Thanks.
mysql_query returns a resource to the query results, not the actual selected values.
Please recheck the docs and examples in there.
(Side-note: That select could get expensive depending on the database type, and if your code has any threading, directly or indirectly (e.g. run from a web server with multiple processes), you'll get unexpected duplicate url ids).
mysql_query always returns a resource. Use either sql_fecth_assoc or mysql_fecth_array to get the values in the resource.