How to declare and use global variables - php

On this test page https://wintoweb.com/sandbox/question_2.php , the visitor can make searches in the DB and tick as many checkboxes as wished. When button [Accept...] is clicked, I want the result of all searches to be shown under 'Your selections so far'. Right now, only the last search is displayed. I tried using a global array to store the result of previous searches and increment it upon each new one. That's where I have a problem.
On top of file I have :
<?php
global $all_authors;
array ($all_authors, '');
?>
At bottom of file I have :
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
if(isset($_GET['search'])){
//echo 'Search</br>';
} elseif(isset($_GET['display_this'])) {
echo getNames();
}
function getNames() {
$rets = '';
if(isset($_GET['choices']) and !empty($_GET['choices'])){
foreach($_GET['choices'] as $selected){
$rets .= $selected.' -- ';
}
//array_push($all_authors, $rets); // This is the problem
//print_r($allAuthors); // this too
echo '</br><b>Your selections so far :</b></br>';
}
return $rets;
}
?>
EXPECTED: Results of all previous searches to be listed
ACTUAL: No go due to problem with array_push(). See function gatNames()

You should make the array global inside the function, so on top:
$all_authors = array();
In the bottom:
function getNames() {
global $all_authors;
// Do the rest of the stuff
}

You are returning $rets from your getNames function but not using it. You just need to use this variables $rets instead of Global Variable.
if(isset($_GET['search'])){
//echo 'Search</br>';
} elseif(isset($_GET['display_this'])) {
$rets = getNames(); //The $rets will hold the value returned by your function getName().
if( !empty ( $rets ) ) {
echo '</br><b>Your selections so far :</b></br>';
echo $rets;
}
}
You could remove the echo statement from inside your getNames Method.
function getNames() {
$rets = '';
if(isset($_GET['choices']) and !empty($_GET['choices'])){
foreach($_GET['choices'] as $selected){
$rets .= $selected.' -- ';
}
}
return $rets;
}

Related

How do you make sure an array is empty in PHP?

Im writing a page in HTML/PHP that connects to a Marina Database(boats,owners etc...) that takes a boat name chosen from a drop down list and then displays all the service that boat has had done on it.
here is my relevant code...
if(isset($_POST['form1'])){//if there was input data submitted
$form1 = $_POST['form1'];
$sql1 = 'select Status from ServiceRequest,MarinaSlip where MarinaSlip.SlipID = ServiceRequest.SlipID and BoatName = "'.$form1.'"';
$form1 = null;
$result1 = $conn->query($sql1);
$test = 0;
while ($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$values1[] = array(
'Status' => $row['Status']
);
$test = 1;
}
echo '<p>Service Done:</p><ol>';
if($test = 1){
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
echo '</ol>';
}else{
echo 'No service Done';
}
the issue im having is that some of the descriptions of sevice are simply Open which i do not want displayed as service done, or there is no service completed at all, which throws undefined variable: values1
how would I stop my script from adding Open to the values1 array and display a message that no work has been completed if values1 is empty?
Try this
$arr = array();
if (empty($arr))
{
echo'empty array';
}
We often use empty($array_name) to check whether it is empty or not
<?php
if(!empty($array_name))
{
//not empty
}
else
{
//empty
}
there is also another way we can double sure about is using count() function
if(count($array_name) > 0)
{
//not empty
}
else
{
//empty
}
?>
To make sure an array is empty you can use count() and empty() both. but count() is slightly slower than empty().count() returns the number of element present in an array.
$arr=array();
if(count($arr)==0){
//your code here
}
try this
if(isset($array_name) && !empty($array_name))
{
//not empty
}
You can try this-
if (empty($somelist)) {
// list is empty.
}
I often use empty($arr) to do it.
Try this instead:
if (!$values1) {
echo "No work has been completed";
} else {
//Do staffs here
}
I think what you need is to check if $values1 exists so try using isset() to do that and there is no need to use the $test var:
if(isset($values1))
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
Or try to define $values1 before the while:
$values1 = array();
then check if it's not empty:
if($values1 != '')
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
All you have to do is get the boolean value of
empty($array). It will return false if the array is empty.
You could use empty($varName) for multiple uses.
For more reference : http://php.net/manual/en/function.empty.php

Won't read variable in function in another script

Whenever I leave my input field empty, $error['commment'] should be set and echoed, but it won't echo, but if I just say echo "some text";, it echo's it.
The comments function is in my functions.php file and $error[] = array() is given in my text.php file above my comments() function, so I don't understand why it's not working, please help guys.
The last bit of PHP code is in a while loop that has to display all the results of my SQL query.
Code above my HTML in text.php:
<?php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error[] = array();
comments();
?>
Code in my functions.php:
function comments(){
if (isset($_POST['submit'])) {
$text = $_POST['text'];
$filledIn = true;
if (empty($text)) {
$error['comment'] = "No text filled in";
$filledIn = false;
}
}
}
This is the code in my text.php:
<?php
if(isset($error['comment'])) echo "<p class='error'>".$error['comment']."</p>";
?>
Because $error is not in the scope of the comments() function. So $error['comment'] never gets set.
Ideally you would want to do something like this:
text.php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error['comment'] = comments();
functions.php
function comments(){
if (isset($_POST['submit'])) {
$text = $_POST['text'];
if (empty($text)) {
return "No text filled in";
}
}
return null;
}
text.php
<?php
if(!empty($error['comment'])) echo "<p class='error'>".$error['comment']."</p>";
?>
Rather than setting the array key "comments" directly I would use a return value from the comments() function to set it. This allows you to avoid having to use global variables.
Edit: I removed the $filledIn variable from comments() because it wasn't being used in the provided code.
#pu4cu
imo, since you dont come across as very advanced, so that you dont have to make many code changes to what you have now which might get you the minimal edits, and easiest for you to understand;
if in your comment function, you just return a response from this function, like a good little function does, then your response will be available when you call the function, when you set that function to a variable.
//functions.php (note this sets error to true to be failsafe, but this depends on how your using it. set the $response to an empty array in the first line instgad, i.e. array(); if you don't want it failsafe.
<?php
function comments()
{
$response = array(
'error' => TRUE,
'filledIn' => FALSE
);
if (isset($_POST['submit']))
{
$text = $_POST['text'];
$response['filledIn'] = TRUE;
if (empty($text))
{
$response['error']['comment'] = "No text filled in";
}
else{
$response['error'] = NULL;
}
}
return $response;
}
//index.php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$response = comments();
//text.php
<?php
if($response['error']['comment'])) echo "<p class='error'>".$response['error']['comment']."</p>";
I find your code overly complicated, 3 files, 2 includes, and 1 function, when all you really needed is this:
$error = array();
$error['comment'] = empty($_POST['text']) ? "No text filled in" : $_POST['text'];
echo "<p class='error'>".$error['comment']."</p>";
Your scopes are all mixed up. Your comments() function checks for $_POST, which should be checked before the function is called, and then tries to set a variable within its scope, but you try to access the same variable from outside.
The correct way would be:
text.php:
<?php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error[] = array();
if (isset($_POST['submit']) {
comments($_POST);
}
?>
functions.php
function comments($data){
if (isset($data['text'])) {
$text = $data['text'];
if (empty($text)) {
return array('comment' => 'No text filled in');
}
return true;
}
return null;
}
Then you can use the values returned by your function on to act on the result.

PHP function not being called, am i missing something obvious?

i think i need a second pair of eyes.
I have some ajax calling a php file, and it's returning json. This all works fine. I'm then alerting the data elements i return for testing purposes. In doing this i narrowed down my function is not being called.
<?php
// database functions
$response = array();
$count = 1;
// connect to db
function connect() {
$response['alert'] = 'connect ran'; // does not get alerted
}
// loop through query string
foreach ($_POST as $key => $value) {
switch ($key) {
case 'connect':
$response['alert'] = 'case ran';
if ($value == 'true') {
$response['alert'] = 'if ran'; // this is what gets alerted, should be overwriten by 'connect ran'
connect(); // function call does not work?
} else {
$response['alert'] = 'false';
$mysqli->close();
}
break;
case 'otherstuff':
break;
}
++$count;
}
$response['count'] = $count;
echo json_encode($response);
?>
Any ideas? Thanks.
your $response variable is out of scope.. use global keyword inside your function to registering your outer variable(s)
function connect() {
global $response;
$response['alert'] = 'connect ran';
}
or SDC's edit:
function connect($response) {
$response['alert'] = 'connect ran';
}
connect($response);
actually you defined the result variable but in another type and you also have another result variable at the top so you put data in $result[] but you try to use $result so your code may not give you the expected result.

PHP Get Multi Select List Values

I'm trying to write a simple function to construct field names for a form. It works fine if at least one value is selected in a multi-select list but if nothing is selected I get an Undefined index error. Here is what I have:
function mcFieldName($mcFieldName){
$mcField = $_POST[$mcFieldName];
if( !is_array($mcField) ){
if( !empty($mcField) ){
return $mcField;
}else{
return 'n/a';
}
}
if( is_array($mcField) ){
$mcFieldArray = implode(',', $mcField);
return $mcFieldArray;
}
}
$MultiSelect = mcFieldName('mcMultiSelect');
// test
echo $MultiSelect . '<br/>';
Thank you!
You just need to protect yourself from reading a key that does not exist in $_POST:
$mcField = isset($_POST[$mcFieldName]) ? $_POST[$mcFieldName] : null;
Before you try to access an array item make sure it exists with using isset():
if (isset($_POST[$mcFieldName])) {
$mcField = $_POST[$mcFieldName];
...
}

Yii: Customize the results of CAutoComplete

I need to make a dropdown list using CAutoComplete. Everything is set and works fine, here is my code of the action:
<?php
public function actionSuggestCharacter() {
if(Yii::app()->request->isAjaxRequest && isset($_GET['q'])) {
$name = $_GET['q'];
$criteria = new CDbCriteria;
$criteria->condition='`Character` LIKE :keyword';
$criteria->params=array(':keyword'=>"$name%");
$criteria->limit = 5;
$suggestions = zCharacter::model()->findAll($criteria);
$returnVal = '';
foreach($suggestions as $suggestion) {
$returnVal .= $suggestion->Character."\n";
}
if (isset($suggestion)) {
echo $returnVal;
}
$criteria->condition='`Character` LIKE :keyword';
$criteria->params=array(':keyword'=>"%$name%");
$criteria->limit = 5;
$suggestions = zCharacter::model()->findAll($criteria);
$returnVal = '';
foreach($suggestions as $suggestion) {
$returnVal .= $suggestion->Character."\n";
}
if (isset($suggestion)) {
echo $returnVal;
}
}
}
?>
What this code does is that it shows the first 5 matches with the keyword at the beginning and the next 5 matches are with the keyword in any place.
Example. Let's say a user types in the input field "pdd" (doesn't really matter, could be any text), so the results returned by autocomplete will look like:
1. pddtext...
2. pddtext...
3. pdd_some_other_text
4. pdd_text
5. pdd_text
1. text_text_pdd
2. text_pdd_text
3. etc...
The problem is I need to separate these two blocks by some kind of line (<hr> or <div> with the border). How can I do this?
Thank you.
Can't you do something like this?
<?php
public function actionSuggestCharacter() {
if(Yii::app()->request->isAjaxRequest && isset($_GET['q'])) {
...
if (isset($suggestion)) {
echo $returnVal;
}
echo "Hey this is the delimiter\n";
$criteria->condition='`Character` LIKE :keyword';
....
}
}
?>
And then on the client side check for this string and when you encounter ""Hey this is the delimiter" replace it with your separator.

Categories