mySQL min() and max() query array echoing zero - php

I have a table set up with 5 columns:
user_id, 5k, 10k, halfmarathon, and marathon.
I want to display the user's best times on a user page for each distance of run. The user will be able to update any of the times which creates a new row and the rest of the columns are set to null. So for example,
Row 1 is:
user_id: 5, 5k: null, 10k: 45:00, half: null, marathon: null.
Then the user runs another 10k and gets a better time, plus wants to update their 5k time :
Row 2 is then:
user_id: 5, 5k: 15:53, 10k: 40:40, half: null, marathon: null.
When I run the following SQL query
$query = "SELECT MIN(5k), MIN(10k), MIN(halfmartahon), MIN(marathon)
FROM Times
WHERE user_id = ".$userID."
GROUP BY user_id";
$db->query($query);
//Assign Result Set
$user_benchmarks = $db->single();`
I get an array that is correct when I vardump() (I am storing the times in seconds) :
object(stdClass)#18 (4) { ["MIN(5k)"]=> string(3) "953" ["MIN(10k)"]=> string(4) "2440" ["MIN(halfmarathon)"]=> string(1) "0" ["MIN(marathon)"]=> string(1) "0" }
However, when I try to echo this, so $user_benchmarks->5k it doesn't show anything and when I run print_r($user_benchmarks->5k) it comes back as NULL.
Has anyone encountered this / know what's happening? I've also tried turning the string to an integer before printing it to no avail - still get NULL.

var_dump already showed you exactly what keys to use:
object(stdClass)#18 (4) { ["MIN(5k)"]=> string(3) "953"
^^^^^^^
so why are you using
$user_benchmarks->5k
^^^
?

It's because the "5k" property of the $user_benchmarks object doesn't exist. You need to access the "MIN(5k)" property instead. So for example:
echo $user_benchmarks->{"MIN(5k)"};
On the other hand you can change the query to something like this:
SELECT MIN(5k) AS `5k`, MIN(10k) AS `10k` ...
Then you will be able to access properties "5k" and "10k" just like you wanted.

Use
SELECT MIN(5k) as 5k,
MIN(10k) as 10k,
MIN(halfmartahon) as halfmartahon,
MIN(marathon) as marathon

Related

select query of sphinxql returns everything in string irrespective of data type in table

I wrote my config file as attribute as -:
sql_attr_float = rad_latitude
sql_attr_float = rad_longitude
but on a select query i get the data as
array(2) {
["rad_latitude"]=>
string(9) "-0.371600" //this needs to be float
["rad_longitude"]=>
string(9) "-0.878434" //this needs to be float
}
it comes out as a string and i cant calculate geodist as it's in string.
sphinxql's execute function returns the data in string but you can use it in geodist query as it is. just remember not to use quotes on the columns name in your query, if you put quotes over it sphinx treats it as a string and i wont produce any result.

R loop - how to use it correctly?

I am coming from PHP background and still trying to get my head around R.
For instance, I can easily loop an array in PHP and manipulate the data,
$array = [
"site1" => 9
"site2" => 10
"site3" => 18
"site4" => 28
]
foreach($array as $index => $id) {
echo $id . '<br/>';
}
result,
9
10
18
28
But in R, I have this data frame for instance,
siteKey siteCode
1 site1 9
2 site2 10
3 site3 18
4 site4 28
loop,
for(i in 1:length(sites.df$siteKey)) {
print(sites.df$siteCode)
}
result,
[1] "9" "10" "18" "28"
[1] "9" "10" "18" "28"
[1] "9" "10" "18" "28"
[1] "9" "10" "18" "28"
I thought it should be this result below?
"9"
"10"
"18"
"28"
Any idea how I can use the R loop to get the result above that I need?
EDIT:
The query,
# Prepare SQL query1.
dataQuery <- "SELECT
*
FROM speckdata AS s
LEFT JOIN weatherunderground AS w
ON s.wid_timestamp = w.wid_timestamp
LEFT JOIN nodes AS n
ON n.nid = s.nid
AND n.datatype = 'speck'
WHERE n.nid = 'SITE'
"
Maybe better to loop this below?
#
# Data: site 1
#
# Match the pattern and replace it.
data1Query <- sub("SITE", as.character(site1), data1Query)
# Store the result in data1.
data1 = dbGetQuery(DB, data1Query)
#
# Data: site 2
#
data2Query <- sub("SITE", as.character(site2), data2Query)
# Store the result in data.
data2 = dbGetQuery(DB, data2Query)
#
# Data: site 3
#
data3Query <- sub("SITE", as.character(site3), data3Query)
# Store the result in data.
data3 = dbGetQuery(DB, data3Query)
#
# Data: site 4
#
data4Query <- sub("SITE", as.character(site4), data4Query)
# Store the result in data.
data4 = dbGetQuery(DB, data4Query)
Then merge all the data,
# Merge data sets.
set.seed(1)
dataList = list(data1, data2, data3, data4)
allData = Reduce(function(...) merge(..., all=T), dataList)
Then plot the data,
timePlot(
allData,
pollutant = c(species, condition),
avg.time = mean,
lwd = 2,
lty = 1,
type = "site",
group = TRUE,
auto.text = FALSE
)
Add a call to [i] in your loop like so...
for(i in 1:length(sites.df$siteKey)) {
print(sites.df$siteCode[i])
}
This way, each iteration will print the single instance at location [ i ].
Hopefully that makes sense.
The solution of #dsifford is ok in base R. However, I recommend to have a look at the dplyr package early in the switchover from php, because it makes things much more transparent than the hopeless mess of xapply functions (apologies to all radical base-R-ers).
library(dplyr)
site.df = data.frame(siteKey = paste0("site",1:4), siteCode = runif(4,9,28))
site.df %>%
rowwise %>%
do(print(.$siteCode))
In itself this is not really easier, but if you have additional manipulations, it makes for a smoother ride.
Your question as written is "R loop: How to use it correctly?"
You propose this code
for(i in 1:length(sites.df$siteKey)) {
print(sites.df$siteCode)
}
This code would be an example of using an R loop correctly (if you insisted on it, even though it is discouraged).
What this code is saying is for each pass print out the "column" or complete list of values for $siteCode. The loop is repeating that print request for each site, so you are getting the same complete list for each pass.
As suggested above by #dsifford changing it to
for(i in 1:length(sites.df$siteKey)) {
print(sites.df$siteCode[i])
}
will mean that instead of printing the entire list it will print just the ith value from that list for each pass.
The new code you added has different issues, specifically you are repeating the same code over and over for each site. You might want to consider writing functions to replace the duplicate code and then feeding the functions the list of sites you are using. That is a case where a loop may possibly make sense (although it may not). But that is all a side issue from your original question.

PHP - Extract value from query array

Do you have to use a loop to extract the value from a query array.
Query:
$fetchRegion = Singlequery("SELECT region FROM regions WHERE id = :id LIMIT 1",
array('id' => $_GET['region']),
$conn);
This is my array:
array(1) {
[0]=>
array(1) {
["region"]=>
string(10) "South West"
}
}
I want to take the value and use it in another query, I didn't know if I had to use a foreach for example to get the value to use in my next query. The other stackoverflow questions that I saw used a loop
If i understand your question correctly and you want to acces to value then access it like so:
$fetchRegion[0]['region'];
You don't need to use foreach or any other loop since it will return at most one element because LIMIT 1 you used in query.
Using loop :-
foreach($fetchRegion as $v) {
$var = $v["region"];
}
or you get directly like:-
echo $fetchRegion[0]["region"];
No, there is no need to use a loop with that query because it will not return more than a single row. Instead, just check that you got a row back (it could return no results), and then use it.
If you're certain that your result is going to look like that, reset(reset($fetchRegion)) will give you the value 'south west'. It will behave badly if you don't get that exact format back though - for example, if the query does not return a row.

get value from stored procedure in php

This is my SP:
DELIMITER $$
CREATE DEFINER=FUNCTION `test`(p_begin varchar(10),p_end varchar(10),p_code varchar(2)) RETURNS varchar(10) CHARSET latin1
BEGIN
DECLARE V_ADA VARCHAR(8);
DECLARE V_LAST VARCHAR(8);
DECLARE V_NIK VARCHAR(8);
select NIK INTO V_NIK from absen where join_date >= p_begin and join_date<= p_end AND company_id=p_code ORDER BY NIK DESC LIMIT 1 ;
SET V_NIK=V_NIK+1;
return V_NIK;
END
I am trying to get the return value with php:
$query=$this->db->query("select test(\"$begin\",\"$end\", \"$code\")")->result();
var_dump($query);
die;
The result is:
array(1) { [0]=> object(stdClass)#20 (1) { ["test("2007-01-01","2007-12-31", "1")"]=> string(7) "118" } }
My problem is that I want to get the value from stored procedure ("118") and I don't know how to change the object into a string.
Try this:
$query=$this->db->query("select test(\"$begin\",\"$end\", \"$code\")")->result();
// Cast object to array (also you can try get_object_vars() to do that)
$query = (array)$query[0];
// Get the last value from array (it the only on so it is OK)
echo end($query);
Perhaps will help..
If you need to send the object as text to somewhere else (database, Javascript code), you have a choice of serialize, json_encode, XML conversion, and many more, depending on your exact situation.

trying to send array through GET variable, when printed, var equals string of 'Array'

Whenever i build a URL i.e.
cart.php?action=add&p[]=29&qty[]=3&p[]=5&qty[]=13
and try to grab the p variable and the qty variable, the = 'Array'
var_dump =
array(3) { ["action"]=> string(3) "add" ["p"]=> string(5) "Array" ["qty"]=> string(5) "Array" }
I create half the URL with PHP, and the other half is concatenated with Javascript.
P and QTY are Arrays because you created them using the variable[] syntax. And when you try to turn an array into a string, PHP just use's 'Array'. Echoing something turns it into a string, and then prints it to the string.
The [] tells PHP to make a new key in the array numerically, and assign the value to it.
If you want to get acess of the values of p, go like this
foreach($_GET['p'] as $value)
{
// $value is one of the values of the array, and it goes through all of them
}
The foreach iterates through all of the values of the array, where $value is the value of the current element you are working on.
If you want to access the first value assigned to p, use
echo $_GET['p'][0];

Categories