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

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.

Related

Php / Laravel check for duplicate in loop

I am trying to check whether a generated string is in my database table or not.
If there is no duplicate I want to return and save it.
If there is a duplicate I want to generate a new string and save it
currently this function does not return me the generated token:
public function checkForHashDuplicate($string)
{
$newToken = '';
$inquiries = DB::table('inquiries')->get();
foreach($inquiries as $inquiryKey => $inquiryValue)
{
while($inquiryValue->android_device_token == $string)
{
$newToken = generateAlphanumericString();
if($newToken != $inquiryValue->android_device_token)
{
return $newToken;
}
}
}
}
$inquiry->android_device_token = $this->checkForHashDuplicate($hash);
A simplified version of your code is:
public function checkForHashDuplicate($string)
{
do {
// generate token
$newToken = generateAlphanumericString();
// find token in a DB
$duplicate = DB::table('inquiries')
->where('android_device_token', '=', $newToken)->first();
// if token is FOUND `$duplicate` has truthy value
// and `do-while` keeps running
// else `$duplicate` is falsy and `do-while` breaks
} while ($duplicate);
return $newToken;
}
Instead of using:
$inquiries = DB::table('inquiries')->get();
and loop, use where like:
$inquiries = DB::table('inquiries')->where('android_device_token', '=', $string)->get();
if( count($inquiries ) == 1 )
{
// found
}
else
{
// Not found, generate new one
}
You can check like this:
public function checkDuplicate($string){
$count = DB::table('inquiries')->where('android_device_token',$string)->count();
if($count==0){
// $string exists
return generateAlphanumericString();
}else{
// $string doesn't exists
return $string;
}
}
Now, use this function to assign value of $string or new token as
$inquiry->android_device_token = $this->checkForHashDuplicate($hash);
Hope you understand.

PHP Function multiple parameters

I', trying to update a row on parse using PHP. I'm using this function:
if (isset($_GET['updateHistory']))
{
updateHistory($_GET['updateHistory']);
}
if (isset($_GET['yesNo']))
{
yesNo($_GET['yesNo']);
}
function updateHistory($obId,$yesNo) {
$bool = "";
if ($yesNo == "YES") {
$bool = true;
} else {
$bool = false;
}
$query = new ParseQuery("TestObject");
try {
$history = $query->get($obId);
$history->set("isHistory", $bool);
$history->save();
} catch (ParseException $ex) {
echo "Error Updating History";
}
reload();
}
The problem now is I can't pass the 2nd variable which is $yesNo using
<a href='?updateHistory=$obId&yesNo=YES'>YES</a>
How can I pass the 2nd variable? thanks!
try
if (isset($_GET['updateHistory'], $_GET['yesNo'])) {
// you should sanitize your $_GET values before using them
updateHistory($_GET['updateHistory'], $_GET['yesNo']);
}
Since your function depends on both variables being set, combine the if-statement to check both fields and do a single call to your function:
if (isset($_GET['updateHistory']) && isset($_GET['yesNo'])) {
updateHistory($_GET['updateHistory'], $_GET['yesNo']);
}
You can then drop this part altogether:
if (isset($_GET['yesNo']))
{
yesNo($_GET['yesNo']);
}

Is there any possibility to break a loop while calling a function?

Let's say I have a simple code:
while(1) {
myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) break;
}
This will not work with error code 'Fatal error: Cannot break/continue 1 level on line'.
So is there any possibility to terminate the loop during a subfunctin execution?
Make the loop condition depend upon the return value of the function:
$continue = true;
while( $continue) {
$continue = myend();
}
Then, change your function to be something like:
function myend() {
echo rand(0,10);
echo "<br>";
return (rand(0,10) < 3) ? false : true;
}
There isn't. Not should there be; if your function is called somewhere where you're not in a loop, your code will stop dead. In the example above, your calling code should check the return of the function and then decide whether to stop looping itself. For example:
while(1) {
if (myend())
break;
}
function myend() {
echo rand(0,10);
echo "<br>";
return rand(0,10) < 3;
}
Use:
$cond = true;
while($cond) {
$cond = myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) return false;
}

return and echo my array from a function

I have a function that returns either a value into a variable if it is successful or it returns an errors array. see part of it below.
function uploadEmploymentDoc($var, $var2){
$ERROR = array();
if(empty($_FILES['file']['tmp_name'])){
$ERROR[] = "You must upload a file!";
}
//find the extensions
$doctypeq = mysql_query("SELECT * FROM `DocType` WHERE `DocMimeType` = '$fileType'");
$doctype = mysql_fetch_array($doctypeq);
$docnum = mysql_num_rows($doctypeq);
if($docnum == 0){
$ERROR[] = "Unsupported file type";
}
if(empty($ERROR)){
// run my code
return $var;
} else{
return $ERROR;
}
then when I run my code
$result = uploadEmploymentDoc(1, 2);
if($result !=array()){
// run code
} else {
foreach($result as $er){
echo $er."<br>";
}
}
Now my question is this. Why is my function running my code and not showing me an error when I upload an unsupported document type. Am I defining my foreach loop correctly? For some reason I cant get my errors back.
you should write like this-
if(is_array($result)){
foreach($result as $er){
echo $er."<br>";
}
} else {
//your code for handling error
}
You can get more info :http://us2.php.net/is_array
Try use
$result = uploadEmploymentDoc(1, 2);
if(!is_array($result)){
// run code
} else {
foreach($result as $er){
echo $er."<br>";
}
}
Probably will be better add parameter by reference to function for the errors array. From function return "false" if error and value if no error occurred.

Instead of calling the same function twice

I'm first checking if a function returns a valid result, and then, if the result is valid, I need to use that in my script. But instead of checking once, and then coming back again to the function for its result, is there a way to do it all in one go? Here, $strVal is the variable I need to use in an querystring later.
$conn = connect();
encrypt('HIs#$%.-','x');
decrypt('6507A27EB0521AFA0776F1A4F8033041','x');
//If the function returns a valid result,
if (encrypt('Tom','x'))
{
echo 'Success'.$strVal;//I'll use this in a querystring later.
}
else
{
echo 'An error occurred';
}
//Encrypt string
function encrypt($strToEncrypt,$salt)
{
global $conn;
$elements = $conn->prepare("select hex(aes_encrypt(:what,:salt)) as encValue");
$elements->bindParam(':what', $strToEncrypt);
$elements->bindParam(':salt', $salt);
$elements->execute();
$row = $elements->fetch();
$strVal = $row['encValue'];
if(is_null($strVal)){return false;}else{return $strVal;}
}
//Decrypt string
function decrypt($strToDecrypt,$salt)
{
global $conn;
$elements = $conn->prepare("select aes_decrypt(unhex(:what),:salt) as decValue");
$elements->bindParam(':what', $strToDecrypt);
$elements->bindParam(':salt', $salt);
$elements->execute();
$row = $elements->fetch();
if(is_null($row['decValue']))
{echo "Null";}else{echo $row['decValue'];}
}
Yes, you could do the variable assignment inside the condition:
/* single 'equal' operator intended */
if( $strVal = encrypt( 'Tom', 'x' ) )
{
echo 'Success' . $strVal;
}

Categories