All,
I have the following code:
$qry = "Select * from vendor_options order by vendor_option_name ASC";
$result = mysql_query($qry);
while($resultset = mysql_fetch_array($result)){
if(isset($_SESSION['pav_choosen_vendor_categories'])){
for($z=0;$z<$_SESSION['pav_choosen_vendor_categories'];$z++){
$sVendorId = $_SESSION['pav_vendor_categories_' . $z];
if($sVendorId==$resultset['vendor_option_id']){
$vendor_cats_choosen[] = $sVendorId;
}
}
if(in_array($resultset['vendor_option_id'],$vendor_cats_choosen)){
?>
<input type="checkbox" value="<?php echo $resultset['vendor_option_id']; ?>" class="select_vendor" name="vendor_categories[]" checked><?php echo $resultset['vendor_option_name']; ?><br>
<?php
}else{
?>
<input type="checkbox" value="<?php echo $resultset['vendor_option_id']; ?>" class="select_vendor" name="vendor_categories[]"><?php echo $resultset['vendor_option_name']; ?><br>
<?php
}
}
}
I'm trying to check to see if the value returned in the mysql_fetch_array is already in my array. Say the first value it finds in the array is in the fourth iteration of the while loop. I'll get the following error:
Warning: in_array() expects parameter 2 to be array, null
Once it gets to a value that is in the array the rest of them work fine. Why does itgive an error for the first couple? Thanks.
It looks like you have not initialized $vendor_cats_chosen to be an array, and so if the condition if($sVendorId==$resultset['vendor_option_id']) is not true, no elements will be appended to it, turning it implicitly into an array.
Initialize it before the while loop. You should just about always initialize arrays before use.
// Initialize the array
$vendor_cats_chosen = array();
while($resultset = mysql_fetch_array($result)){
....
Now, when your in_array() statement executes, the array may be empty, but will be a valid array.
// $vendor_cats_chosen might be an empty array, or may have elements.
if(in_array($resultset['vendor_option_id'],$vendor_cats_choosen)){
The problem is that your array not always creates. To fix this issue just add
$vendor_cats_choosen = array();
somewhere before while in your code.
You only ever populate the array $vendor_cats_choosen inside an if statement, which means it can potentially contain no values. You also do not declare it before you start the loop which populates it - which you should do anyway, because adding a value to an undeclared array will emit an E_NOTICE.
Add the line
$vendor_cats_choosen = array();
...at the top of the script and the error will disappear. If you think this array should contain values, you may need to examine the logic in your if statement.
In order to eliminate the warning message, two approaches can be followed:
1) use of # before the statement which is generating the warning message ( However, this is not an advisable engineering approach )
2) prior to using the array object, it can be filtered out in an if-else.
For example, in your case, you can add this line
if( $vendor_cats_choosen ){
if(in_array($resultset['vendor_option_id'],$vendor_cats_choosen)){
?>
<input type="checkbox" value="<?php echo $resultset['vendor_option_id']; ?>" class="select_vendor" name="vendor_categories[]" checked><?php echo $resultset['vendor_option_name']; ?><br>
<?php
}else{
?>
<input type="checkbox" value="<?php echo $resultset['vendor_option_id']; ?>" class="select_vendor" name="vendor_categories[]"><?php echo $resultset['vendor_option_name']; ?><br>
<?php
}
} ?>
Related
This question already has answers here:
Passing an array using an HTML form hidden element
(8 answers)
Closed 3 years ago.
Hi so for the website I am designing I have been asked to use mal's eCommerce for the payment gateway. I have been trying to set up the remote call function they have so that once a purchase has been made it will make a call back to my website to run a script and sen email confirmation of their order.
This however has proved extremely frustrating as the session variables I have stored do not get passed through with the remote call, only certain values that they allow.
I tried storing them all in an array and putting them in one of the values I can change called sd:
$cart =array($_SESSION["date"], $_SESSION["name"], $_SESSION["email"], $_SESSION["number"], $_SESSION["address"], $_SESSION["town"], $_SESSION["postcode"],
$_SESSION["county"], $_SESSION["cake_type"], $_SESSION["collection"], $_SESSION["icingColour"], $_SESSION["trimColour"], $_SESSION["filling"], $_SESSION["wording"],
$_SESSION["cakePhoto"], $_SESSION["price"], $_SESSION["photo"] );
<input type="hidden" name="sd" value="<?php echo $cart?>">
Then in my script I tried:
$result = $_POST['sd'];
echo $result[0];
to test it
but the remote call just passed the value as "Array" so echo $result[0] just returned "A", the values was just passed as Array and none of the values in the array got passed with it.
So now I'm trying to store all my session variables in the sd value like this:
<input type="hidden" name="sd" value="<?php foreach ($_SESSION as $key=>$val) { echo $val;}?>">
and then I tested it by doing on my script:
$result = $_POST['sd'];
echo $result;
Now this does pass all the values but obviously just as one big value, is there a way I can split them up? Is there a better way with the array I haven't thought of? Any advice would be greatly appreciated because I'm at a complete loss
Edit:
Forgot to add this part:
So after the array has been split I would need to stored the values separately so something like:
$name = first value
$email = second value etc
try changing <input type="hidden" name="sd" value="<?php echo $cart?> to
<input type="hidden" name="sd[]" value="<?php echo $cart?>
or use serialize() then unserialize() the result.
Refer to Passing an array using an HTML form hidden element
You can use php implode and explode function.
The first part is implode.
We use ; as implode delimeter which joins array elements as single string using that delimeter.
<input type="hidden" name="sd" value="<?php foreach ($_SESSION as $key=>$val) { echo $val.';';}?>">
Explode converts that string to array again using the delimeter we passed.
foreach (explode(';', $_REQUEST["sd"]) as $key) {
echo $key;
echo "<br>";
}
Update : Try This
<input type="hidden" name="sd" value="<?php foreach ($_SESSION as $key=>$val) { echo $key.';'.$val.';;';}?>">
Explode converts that string to array again using the delimeter we passed.
foreach (explode(';;', $_REQUEST["sd"]) as $key) {
echo explode(';', $key)[0];
echo " = " ;
echo explode(';', $key)[1];
echo "<br>";
}
this is my input filed which I'm using
This is how I am print my variable
getting this error
Array ( [0] =>
Notice: Array to string conversion in C:\xampp\htdocs\attendance-system\view-all-latecomers.php on line 162
Array )
Any Solution please helped me. Thanks
When you add [] to the end of an input name, that causes all the values of those inputs to be put into an array in PHP. So $_POST['checked_id'] is an array, not a string. Then when you do:
value="<?= $_POST['checked_id'] ?>"
you're trying to echo the entire array into that one input. You can't echo an array, so you get that warning.
If this is part of a loop, you need to index the array
for ($i = 0; $i < count($_POST['checked_id']); $i++) { ?>
...
<input type="hidden" name="checked_id[]" value="<?=$_POST['checked_id'][$i]?>">
...
<?php
}
I'm not quite sure where I'm going wrong :(
if(isset($_POST['finish'])){
$objectives=addslashes(strip_tags($_POST['item']));
foreach ($objectives AS $objective) {
echo "$objective <br />";
}
}
It's not showing anything.. what have I missed out? I'm trying to get data from multiple input entries..
<input class="item" id="objectives" name="item[]" />
Any ideas?
Well if you have multiple <input class="item" id="objectives" name="item[]" /> then $_POST['item'] will be an array and not a string. So you have to iterate over it or apply an array_map function.
$items = array_map('strip_tags',$items);
$items = array_map('addslashes',$items);
Your code would then be
if(isset($_POST['finish'])){
$_POST['item'] = array_map('strip_tags',$_POST['item']);
$_POST['item'] = array_map('addslashes',$_POST['item']);
foreach ($_POST['item'] AS $objective) {
echo "$objective <br />";
}
}
The direct answer is that any tag that has brackets([]) is put in the superglobal array as an array. You will need to loop over your this or use array_map to perform functions on this array.
My extended answer is that if you are using php 5.2 or later you can use the filter_var_array to perform this operation without iterating over your array in php. As well as do type checking. filter_var and filter_var_array have to many filter options for me to cover. Please see the docs http://php.net/manual/en/function.filter-var-array.php
if(isset($_POST['finish'])) {
$objectives = filter_var_array($_POST['item'], FILTER_SANITIZE_STRING);
foreach ($objectives AS $objective) {
echo "$objective <br />";
}
}
I have multiple input tag submitted from previous page, say step1.php like this :
<input type="hidden" name="block01" value="001"/>
<input type="hidden" name="block02" value="012"/>
<input type="hidden" name="block03" value="002"/>
<input type="hidden" name="block04" value="005"/>
<input type="hidden" name="block05" value="008"/>
<input type="hidden" name="block06" value="015"/>
now I want to process those inputs in the step2.php and I have 2 options to do it, either using Array or Loop.
If I'm using array, those inputs will be appended like this :
<?php
$stack = array(""); //empty array declared
// I assume I have some codes here to 'catch' those inputs and put it as array_push
array_push($stack, "001", "012", "002", "005", "008", "015");
print_r($stack);
?>
compare to array, I have this LOOP option too :
<?php
$i = 1;
$x = 'block0'.$i;
$webBlock = $_POST[$x];
while (!empty($webBlock)){
$x = 'block0'.$i;
$webBlock = $_POST[$x];
echo $webBlock . "<br />";
$i++;
}
?>
both are solutions of my problem on step2.php. I just need your opinion which is more less memory / cpu consuming? that's all...
thanks!
In first case, you are using array_push() and print_r(). The first function uses a loop to push arguments passed onto a stack. The second function that is print_r() also uses a loop to print all the values of the array. So, basically you are running loop twice to do the task.
Where as in second case, you have written a code to handle both things at once. So, this method just needs to loop once. Moreover, looking into the working of print_r() and echo, if you run echo X times and use print_r() to print X values, the echo is bit faster than print_r. Read php documentation for more info about all these function.
So, the second way is better.
I have PHP code that is used to add variables to a session:
<?php
session_start();
if(isset($_GET['name']))
{
$name = isset($_SESSION['name']) ? $_SESSION['name'] : array();
$name[] = $_GET['name'];
$_SESSION['name'] = $name;
}
if (isset($_POST['remove']))
{
unset($_SESSION['name']);
}
?>
<pre> <?php print_r($_SESSION); ?> </pre>
<form name="input" action="index.php?name=<?php echo $list ?>" method="post">
<input type="submit" name ="add"value="Add" />
</form>
<form name="input" action="index.php?name=<?php echo $list2 ?>" method="post">
<input type="submit" name="remove" value="Remove" />
</form>
I want to remove the variable that is shown in $list2 from the session array when the user chooses 'Remove'.
But when I unset, ALL the variables in the array are deleted.
How I can delete just one variable?
if (isset($_POST['remove'])) {
$key=array_search($_GET['name'],$_SESSION['name']);
if($key!==false)
unset($_SESSION['name'][$key]);
$_SESSION["name"] = array_values($_SESSION["name"]);
}
Since $_SESSION['name'] is an array, you need to find the array key that points at the name value you're interested in. The last line rearranges the index of the array for the next use.
To remove a specific variable from the session use:
session_unregister('variableName');
(see documentation) or
unset($_SESSION['variableName']);
NOTE:
session_unregister() has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
Is the $_SESSION['name'] variable an array? If you want to delete a specific key from within an array, you have to refer to that exact key in the unset() call, otherwise you delete the entire array, e.g.
$name = array(0 => 'a', 1 => 'b', 2 => 'c');
unset($name); // deletes the entire array
unset($name[1]); // deletes only the 'b' entry
Another minor problem with your snippet: You're mixing GET query parameters in with a POST form. Is there any reason why you can't do the forms with 'name' being passed in a hidden field? It's best to not mix get and post variables, especially if you use $_REQUEST elsewhere. You can run into all kinds of fun trying to figure out why $_GET['name'] isn't showing up the same as $_POST['name'], because the server's got a differnt EGPCS order set in the 'variables_order' .ini setting.
<form blah blah blah method="post">
<input type="hidden" name="name" value="<?= htmlspecialchars($list1) ?>" />
<input type="submit" name="add" value="Add />
</form>
And note the htmlspecialchars() call. If either $list1 or $list2 contain a double quote ("), it'll break your HTML
If you want to remove or unset all $_SESSION 's then try this
session_destroy();
If you want to remove specific $_SESSION['name'] then try this
session_unset('name');
Currently you are clearing the name array, you need to call the array then the index you want to unset within the array:
$ar[0]==2
$ar[1]==7
$ar[2]==9
unset ($ar[2])
Two ways of unsetting values within an array:
<?php
# remove by key:
function array_remove_key ()
{
$args = func_get_args();
return array_diff_key($args[0],array_flip(array_slice($args,1)));
}
# remove by value:
function array_remove_value ()
{
$args = func_get_args();
return array_diff($args[0],array_slice($args,1));
}
$fruit_inventory = array(
'apples' => 52,
'bananas' => 78,
'peaches' => 'out of season',
'pears' => 'out of season',
'oranges' => 'no longer sold',
'carrots' => 15,
'beets' => 15,
);
echo "<pre>Original Array:\n",
print_r($fruit_inventory,TRUE),
'</pre>';
# For example, beets and carrots are not fruits...
$fruit_inventory = array_remove_key($fruit_inventory,
"beets",
"carrots");
echo "<pre>Array after key removal:\n",
print_r($fruit_inventory,TRUE),
'</pre>';
# Let's also remove 'out of season' and 'no longer sold' fruit...
$fruit_inventory = array_remove_value($fruit_inventory,
"out of season",
"no longer sold");
echo "<pre>Array after value removal:\n",
print_r($fruit_inventory,TRUE),
'</pre>';
?>
So, unset has no effect to internal array counter!!!
http://us.php.net/unset
Try this one:
if(FALSE !== ($key = array_search($_GET['name'],$_SESSION['name'])))
{
unset($_SESSION['name'][$key]);
}
Simply use this method.
<?php
$_SESSION['foo'] = 'bar'; // set session
print $_SESSION['foo']; //print it
unset($_SESSION['foo']); //unset session
?>