I want to get an array of variables from wordpress database - php

I have a form set up where I am retrieving all users who fit a certain criteria (shoe size between 9-15). But sometimes it could be 1 user, 5 users or 0 users depending on the criteria.
I have a get_var set up but that only returns 1 variable and it breaks my code when it returns multiple values.
$woShoeMemberId = $wpdb->get_var(
"SELECT user
FROM data
WHERE field=16
AND value BETWEEN ".$_POST['woShoes']." AND ".$_POST['woShoes2']."");
How can I turn this into an array? Like $woShoeMemberId would contain an array of 'user' depending on the search results?
Also I then must turn those Ids into usernames which I do by
$woShoeMember = $wpdb->get_var(
'SELECT login
FROM users
WHERE ID='.$woShoeMemberId.'');
Same issue, how do I turn that into an array of usernames depending on the amount of Ids I have?

Instead of get_var(), use get_results() or get_col().
The get_var() method will always return a single result.
The get_results() method will return an array with objects that contain the selected results
The get_col() method will return an array with the selected results.

Related

Matching array of string to numbers to get database values

In my database, I have a status column where I'm using numbers to represent a status of a product. Each of these numbers represents a string value, for example 1 is open, 2 is closed, etc. Now to display a count of these statuses in my webpage, I am converting the following numbers into a string to display them to the user:
array(1=>'Open',8=>'Hot',2=>'Closed',3=>'Transacted',4=>'Dead',9=>'Follow Up',11=>'Working')
Now I have this count as a clickable link, where the user can click the count and it takes them to a new page showing the details of that item. For which I'm using this:
<a target='_blank' href='".site_url('reports/viewall?status=' . $status)."'>".$num."</a>
This correctly passes the argument to the URL and shows http://localhost/reports/viewall?status=Closed
Now I'm storing this variable in my controller as $status, but I cannot use this string value in my model query which is this since it is giving the string value of status and not the number related to it:
SELECT * from TABLE1 where status = $status
Controller Class where I'm storing the $status:
$status = $this->input->get('status');
$content['individualleads'] = $this->leads_model->get_all_leads($status )->result();
I think the best approach would be to pass the integer in the URL and use the array text value only when it is text meant for the user. So just:
http://localhost/reports/viewall?status=2
Another alternative is to flip the array and access the text key:
$status_num = array_flip($array)[$status];
Or search the original array:
$status_num = array_search($status, $array);
Probably more standard might be to have a status_types table with the integer status_id and text status_text for each status and join this when retrieving the status.

Trying to get an average in mySQL in Wordpress with PHP, object returns as an array, need it as a string

I have a custom table in my wordpress install, and I want to get an average out of a column on the table. I'm using the following PHP:
$latavg = $wpdb->get_results("SELECT AVG(stop_lat) FROM stops_txt");
However, when I want to use the average later on as a string, it returns as 'ARRAY', yet attempting to use PRINT_R to view the array reveals nothing. The Column in the table is a DECIMAL data-type, what am I missing?
When you just want a single variable instead of a whole row or column in wpdb, use get_var() instead:
$latavg = $wpdb->get_var("SELECT AVG(stop_lat) FROM stops_txt");
Here is the complete wpdb reference.

Laraver FindOrNew with multiple parameters

I'm using laravel FindOrNew() to get an entry with two parameters, or create a new one:
$option = \App\Option::findOrNew(['user_id' => $this->id , 'option_name' => $optionName]);
I want to get an option for a user that has the name in $optionName. The problem is that it just checks for the user_id, and does not create a new one when option_name does not exist.. instead it "finds" one which does not match the $optionName value..
Can someone say what I'm doing wrong? How can I achieve this?
TL;DR:
You're using the wrong method. You're looking for the firstOrNew() method, not findOrNew().
Explanation:
The findOrNew() is an extension of the find() method, which works on ids only. It takes two parameters, the first being the id (or array of ids) to find, and the second being the columns to retrieve. It's treating the array you've passed in as an array of ids to find.
The firstOrNew() method takes one parameter: an array of attributes to search for. It will turn the array into a where clause, and then call first() on the query builder. If no results are returned, it returns a new instance with those attributes filled in.

How to access the result of a MySQL Count function in php?

I have this function in a linked file:
function getNumberOfHerps() {
$sql = "SELECT COUNT(ID)
FROM HERPES;";
return DBIface::connect()->query($sql);
}
I can call on this function from any other page in the website. What I want to do is to be able to use the result of the COUNT function in my php code on various pages, because I need to know how many herps there are in the database on several occasions in the code.
I tried this:
$result = getNumberOfHerps();
$numberOfHerps = $result['COUNT'];
But it caused a parse error on the second line, saying this:
Cannot use object of type PDOStatement as array.
Please tell me how I can use the result of a Count function in php code. Thanks :D
You are actually facing 2 separate items here that need your attention:
You can't access the COUNT(ID) returned from your query and
You are attempting to access data of a PDOStatement object as an array
So:
You can create an ALIAS for the value returned from the COUNT() function:
$sql = "SELECT COUNT(ID) as COUNT...";
This will provide to your result set a new column named COUNT that you can access your row count from.
Secondly, you need to perform a fetch operation on the PDOStatement in order to access it's data (this is what is causing your parse error). You have several options for accessing the result set in a PDOStatement:
list ($idCount) = $result->fetch();
// $idCount will now have the value of your COUNT column
or
$results = $result->fetch(PDO::FETCH_ASSOC);
// you can then access your COUNT as $results['COUNT'];
or even
$results = $result->fetch(PDO::FETCH_OBJ);
// you can then access your count as $results->COUNT
There are actually several additional FETCH_* styles available to use. The ones I've described though would likely be the most common. You can find more information about fetching PDO result sets at
http://us1.php.net/manual/en/pdostatement.fetch.php
I worked it out for myself, so I'll put my answer up for anyone else who finds this question:
I changed the function to this:
function getNumberOfHerps() {
$sql = "SELECT COUNT(1)
FROM HERPES";
return DBIface::connect()->query($sql)->fetchColumn(0);
}
So what the function now returns is the actual count value (the first column of the query). That means that in the webpage php file, you can access it in this way:
$numberOfHerps = getNumberOfHerps();
Much more simple.

mysql In clause to avoid loop

I have to retrieve the history of a user and I have 4 tables whose data depend on each other.I can retrieve the data using loops,but I instead used the "where IN ()" clause and I implode the output of the previous query.However,if the list I provide to "where IN()" is empty it return an error.Is it that IN() cannot be empty?
When imploding an array for the IN clause, i do one of two things
1: Check if you even need to run the query at all
if(!empty($some_array)) {
//run mysql query
}
else {
// if you need to do something if the array is empty, such as error or set some defaults, do it here
}
2: A value in the array initiliser which is not ever in the database (for example, if im selecting based on a auto incrememnt id, i use zero as a default array value to stop any issues with empty data sets, as zero will never be in my id column).
$some_array = array(0);
You can add an empty value to the start, such as IN (0,your values here)

Categories