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?
Related
I have a number of items of data. Sometimes the var is not created/set, sometimes it is. This is because the var data comes from a form with optional fields.
I have created the variables only if the information is present as such:
if(!empty($_POST["user-jobtitle"])){
$idealJobTitle = $_POST["user-jobtitle"]; }
So if the field user-jobtitle is not filled in, then $idealJobTitle is not created.
I now wish to create an array with a key for each value. But I only want to add to the array if that variable exists. Otherwise, I just want to omit it.
I have written code below which I know is wrong but follows the sort of logic I am after. What is the correct way to do this? Do I really have to run through nested if statements checking if the var exists and only then pushing to the array?
$other_info = array (
"other_info" => array(
if(isset($message)){
"message" => $message
},
if(isset($salaryRange)){
"salary_range" => $salaryRange
},
if(isset($idealJobTitle)){
"ideal_job_title" => $idealJobTitle
}
if(isset($applyFor)){
"ideal_applying_for" => $applyFor
}
)
);
An expected result, if the user has not provided an ideal job title on the form, would be as such:
array(1) {
["other_info"]=>
array(3) {
["message"]=>
string(18) "my message here"
["salary_range"]=>
string(19) "£25k - £30k"
["ideal_applying_for"]=>
string(18) "Cat cuddler"
}
}
As you can see in the above, the ideal_job_title key and value are simply not present.
You should not conditionally declare variables. That's just asking for problems later on.
Unpacking values from one array into a variable and then conditionally packing them back into an array is needlessly complex. Keep your data in an array and move it around in one "package".
You can't have nested if statements within an array declaration.
The most useful way to handle this would be to use names in your form that you're also going to use later on in your $other_info array. Translating between various variable and key names throughout your code is just terribly confusing, pointless and needlessly requires a ton of additional code. In other words, why does the same piece of information need to be called user-jobtitle and $idealJobTitle and ideal_job_title in different contexts? If you'd keep it consistent, you could simply filter empty values and be done with it:
$other_info = array('other_info' => array_filter($_POST));
Yup, array_filter gets rid of empty elements without individual if statements. You can further use array_intersect_key and similar functions to further filter out keys.
If you name variables as key in the array, you can use compact function. Undefined variable will not be in array
$ar = compact("message", "salaryRange", "idealJobTitle", "applyFor");
You can use the below code :
$other_info = array();
if(isset($message)){
$other_info['other_info']["message"] = $message;
}
if(isset($salaryRange)){
$other_info['other_info']["salary_range"] = $salaryRange;
}
if(isset($idealJobTitle)){
$other_info['other_info']["ideal_job_title"] = $idealJobTitle;
}
if(isset($applyFor)){
$other_info['other_info']["ideal_applying_for"] = $applyFor;
}
You already have a code that works and puts the values in variables. Create an empty array and put the data directly in the array under various keys instead of individual variables:
$info = array();
// Analyze the input, put the values in $info at the correct keys
if (! empty($_POST["message"])) {
$info["message"] = $_POST["message"];
};
if (! empty($_POST["salaryRange"])) {
$info["salary_range"] = $_POST["salaryRange"];
};
if (! empty($_POST["idealJobTitle"])) {
$info["ideal_job_title"] = $_POST["idealJobTitle"];
}
if (! empty($_POST["applyFor"])) {
$info["ideal_applying_for"] = $_POST["applyFor"];
}
// Voila! Your data is now in $info instead of several variables
// If you want to get the structure you described in the non-working code you can do:
$other_info = array(
"other_info" => $info,
);
My session variables are
$_SESSION["listofIds"]=163,164;
$_SESSION["listofVals"]=4,3;
I want to select session values like
$_SESSION["listofIds"][0]=163;
$_SESSION["listofIds"][1]=164;
$_SESSION["listofVals"][0]=4;
$_SESSION["listofVals"][1]=3;
I tried
echo $_SESSION["listofIds"][0];
then it prints '1' i.e. first character. How can I handle this?
Also how can I get 1st element of $_SESSION["listofIds"] and 1st element of $_SESSION["listofVals"] after placing in while loop for mysql query.
Your session variables seem to be strings. Use
$IdsArr = explode(",", $_SESSION["listofIds"]);
echo $IdsArr[0];
With explode splitting the string by "," to an array.
$listofIds = array();
$listofIds = explode(",",$_SESSION["listofIds"]);
now you can access the variables using listofIds[0] or listofIds[1].
First of all you should start by defining from scratch an array while placing values in the $_SESSION array. This is a better way to write code.
Anyway as all the other answers said:
$listofIds = array();
$listofIds = explode(",",$_SESSION["listofIds"]);
will convert your string into an array and you will be able to access each value in different ways. Most commons:
using a foreach loop
getting the index of the item you want to use.
If you want to use the first item in a query you should get its value using the index (array starts from 0) so your value will be $listofids[0]. The same logic will apply to the other $_SESSION value.
Another good practice for programming: when you put an array value in a query string assign it to a variable before:
$id_to_search = $listofids[0];
and then use it into the query:
$sql = "SELECT * FROM your_table WHERE id='$id'";
This will save you a lot of headache with singe and double quotes.
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.
I am running into a problem where the below is not working as I think it should.
// this will not work and $usernames appears empty
$usernames = "\"user1\", \"user2\"";
$query->notContainedIn("username", [$usernames]);
// this does work
$user1 = "user1";
$user2 = "user2";
$query->notContainedIn("username", ["$user1", "$user2"]);
Thanks
According to https://parse.com/docs/php_guide#queries you need to provide an array and $usernames is a string. By using the short-array notation, i.e. the square brackets, you've created an array with precisely one element, namely the string. What you need is an array with two elements corresponding to the two values of interest.
If for some reason your data is only available in this type of formatted string, then you would need to convert it to an array. There are at least two ways you could do this:
<?php
$usernames = explode(",",str_replace("\"","","\"user1\",\"user2\""));
?>
This is less complicated than it might appear. The code replaces the quotes encompassing each value with empty strings. Then it explodes the string in two by indicating that the comma is a delimitor. Although I've never worked with Parse, I would expect that you could replace the second parameter in the query with $usernames now, as follows:
<?php
$query->notContainedIn("username", $usernames);
Don't use the square brackets or you'll be creating a multidimensional array whose first element contains the array $usernames.
Alternative way of converting said string to array:
<?php
$string = "\"user1\",\"user2\"";
$tok = strtok($string, "\",");
$usernames = null;
while ($tok !== false) {
$usernames[] = "$tok";
$tok = strtok("\",");
}
$usernames now contains two values just like in the previous solution I proposed. While this second solution is more involved, note that it uses only one function instead of two, so it might produce faster results. You could try both solutions, benchmark them, and then pick the one you find to have superior performance.
Hope this helps.
I currently have var: $_REQUEST['fb_friend_uid'] which gives me the following output:
Array{"returned_val":["47483647","47483647","47483647","665414807","263901486","665414807","665414807","665414807"]}
Im looking to save the data here into a new array, containing only the numbers in a format of; 47483647, 47483647, etc
The objective is to use it in a sql query like so:
SELECT * FROM vote WHERE
vote_fb_uid IN ($myNumbers)
Saving it into a new array I figured could be done like so:
foreach ($_REQUEST['fb_friend_uid'] as $uid) {
$uids[] = $uid['id'];
}
$ids = join(',', $uids);
However my issue remains, how to "clean" the first var to contain numbers only.
Suggestions?
I can't give you an exact solution, because I'm not sure if the value returned by $_REQUEST['fb_friend_uid'] is a PHP array printed using json_encode(), or the value is actually a json string.
In either case, where is an example which makes use of both circumstances, so use whichever one makes sense in your scenario:
If PHP Array:
Assumes PHP Array has a format similar to:
array('returned_val' => array('47483647', '47483647', '47483647', '665414807', '263901486', '665414807', '665414807', '665414807'));
<?php
$original_arr = $_REQUEST['fb_friend_uid']['returned_val'];
If JSON String:
Assumes the JSON String has a format similar to:
{"returned_val":["47483647","47483647","47483647","665414807","263901486","665414807","665414807","665414807"]}
<?php
$json_arr = json_decode($_REQUEST['fb_friend_uid'], True);
$original_arr = $json_arr['returned_val'];
Then, use this code:
<?php
// Extract only whole number values, omit anything which is not a 0-9 character.
$filtered_arr = array_filter($original_arr, 'ctype_digit');
// Escape values to remove possibility of SQL injection.
$filtered_arr = array_map('mysql_real_escape_string', $filtered_arr);
// Convert the array to a string
$string_arr = "'" . implode("','", $filtered_arr) . "'";
// Perform SQL Query
mysql_query("SELECT * FROM vote WHERE vote_fb_uid IN ($string_arr)");
Just filter the array using is_numeric:
$uids = array_filter($_REQUEST['fb_friend_uid'], 'is_numeric');
To filter for numbers you can use is_numeric( mixed $var ).
But if you need more control (only integers of certain type, length) you can either use REGEX or is_numeric and some ifs.
This looks like a json string, so use http://php.net/json_decode
Maybe you need to remove Array at the beginning (but I don't know if Array is actual in the variable), use http://php.net/substr
$jsonString = substr($_REQUEST['fb_friend_uid'], 5);
$fb_friend_uid = json_decode($jsonString);
$ids = join(',', $fb_friend_uid['returned_val']);