PHP - Extract value from query array - php

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.

Related

PHP echo single value from array returned by mysql database query

When I execute var_dump($row) in PHP script it returns this:
array(1) { ["rmb4"]=> string(2) "10" }
How can I get the 10 out of that? The return is from a SQL query. I just want some expression that will get 10 by itself so I can say $my_var=result of expression to get 10 by itselt.
<?php
$row = array('rmb4'=>10);
var_dump($row);
echo $row['rmb4'];
?>
Output
This should work:
echo $row['rmb4'];
Explanation:
If you need a key from an array, which is recognizable by the arrow =>, you will have to do: $array['key']
If you need a object from a array you will need to this:
$array->object
A combination is also possible. That would be:
$array['key']->object

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

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

return data from mysql and unserialize it

My SQL
$query = "SELECT value FROM oc_setting WHERE setting_id =7258";
$result = $this->db->query($query);
return $result->rows;
when I var_dump it show
array(1) {
[0]=>
array(1) {
["value"]=>
string(158) "a:1:{i:0;a:5:{s:8:"rss_link";s:11:"ddddddddddd";s:9:"layout_id";s:1:"2";s:8:"position";s:14:"content_bottom";s:6:"status";s:1:"1";s:10:"sort_order";s:1:"5";}}"
}
}
how can I unserialize array like this? cast to string first? I tried unserializ(var) but it say error coz it's an array.
PHP function unserialize (http://php.net/manual/en/function.unserialize.php) will help you.
unserialize($result[0]['value']);
will return you the array.
It seems you're using some PHP Framework (very similar to CodeIgniter one, but not sure).
There should be a function to retrieve exactly one (first) row from the result set.
Right now you're asking about a workaround which is not good. Usually DB drivers have a good interface to get how many rows/columns it took from query/view.
I usually use the following statement if I need go through the result array:
if ($result -> num_rows())
{
foreach ($result -> result_array() as $entry)
{
// do something
}
}

Adding key-value in PHP array?

Inside a loop where I'm dealing with variables related to a product and a number of units, I'm trying to add these two to an array:
$pedido = array();
So,
foreach($_POST as $post_key => $post_value){
if ($post_value=="on") {
$nombreProducto = mysql_fetch_assoc($mySQL->query("SELECT nombre from productos WHERE id_producto='$post_key'"));
$cantidad = $_POST[$post_key."Number"];
echo "<h1>".$nombreProducto['nombre']."</h1>"." Cantidad: ".$cantidad." <br><br>";
$pedido["$nombreProducto"] = $cantidad;
}
}
It's right in:
$pedido["$nombreProducto"] = $cantidad;
Where I try to perform the adding, however the output of var_dump is like:
array(1) { ["Array"]=> string(1) "3" }
Not exactly what I wanted neither the format.
Use $pedido[$nombreProducto['nombre']] = $cantidad; instead of $pedido["$nombreProducto"] = $cantidad;
Remove quotes and
$pedido[$nombreProducto['nombre']] = $cantidad;
EDITED
It seems $nombreProducto is an array so you need to indicate the key field, so i changed to use the field "nombre"
If you see your var_dump it's an Array with the key "Array" this is why you are trying to convert the array to string and it return the word "Array"
You shouldn't be putting a variable by itself in quotes. Remove the quotes.
Also, since you were just accessing $nombreProducto['nombre'] on the previous line, it's fairly obvious that that variable is an array. You cannot use an array as a key, only integers and strings are allowed. So use something that identifies it, such as its ID number.
The following makes no sense to do:
$pedido["$nombreProducto"] = $cantidad;
What are you trying to do here? I think what you want to do is this:
$pedido[$nombreProducto['nombre']] = $cantidad;
Also you may want to try to output the array like this:
print_r($pedido);
I recommend you re-write the mysql query so you don't need to loop it. That is for safety and efficiency reasons. I also recommend you use mysqli instead of mysql, because mysql is deprecated and unsafe to use. You don't check if $_POST[$post_key."Number"] is set, at least not in this code. I hope you sanitize/validate the input from $_POST before using it against the database?

PHP $_GET should return array instead of string

I have a strange error with a $_GET Value. I'm using this code for a query:
array($_GET['cats'])
If I insert the get parameter manually, like: array(3,328) everything works fine. But if I use:
array($_GET['cats']) and submit the cats by URL like ?cats=3,328 it does not work. What could be the issue?
You can't plug a value like that. array($_GET['cats']) is equivalent to array('3,328'), if the value of $_GET['cats'] is 3,328. So basically, the value is a string, not a list of integers. What you want is:
explode(',', $_GET['cats'])
array($_GET['cats']) will create an array containing the single element that’s value is the value of $_GET['cats'], no matter what value it is. In case of the string value 3,328 is would be identical to array('3,328').
If you want to turn the string value 3,328 into an array identical to array(3,328), use explode to split the string at , into strings and array_map with intval to turn each string into an integer:
$arr = array_map('intval', explode(',', $_GET['cats']));
Now this resulting array is really identical to array(3,328):
var_dump($arr === array(3,328)); // bool(true)
As others have said, $_GET['cats'] is a string as you're doing things at the moment.
However, if you change your URI querystring to ?cats[]=3,328 then $_GET['cats'] will be the array(3,328) ready for you to use.
Solution 1: Send HTTP GET parameters as an array in your URL
URL: parameters ?cats[]=3&cats[]=328
var_dump($_GET["cats"]) will result in:
array(2) {
[0]=>
string(1) "3"
[1]=>
string(3) "328"
}
Solution 2: Send numbers as one string in URL and process it with PHP
URL parameters: ?cats=3,328
... and then process it with some PHP code:
$cats = array_map("intval", explode(",", $_GET["cats"]));
var_dump($_GET["cats"]) will result in:
array(2) {
[0]=>
string(1) "3"
[1]=>
string(3) "328"
}
$_GET['cats'] is a simple string. If you want to get 3 and 328 as seperate values you need to use explode. You can than use foreach to print your exploded values.
You need to split up the GET-Parameters
$values = explode(',', $_GET['cats'])

Categories