php - return variable from function - php

I am trying to return a variable from a function. I have the function below, which inserts a postid to the database. I need the postid's value returned to another page.
forum.php - Where the function is.
function newTopic(){
// Get the POST data
global $ir;
$postid = mysql_insert_id();
mysql_query("UPDATE forum_topics SET post_id='$postid' WHERE topic_id='$topicid'");
// No error found and the update was succesful - Return success!
return 100;
return $postid;
}
newtopic.php - Where I need the $postid variable.
if($_POST)
{
$newTopic = $forum->newTopic();
/*
* Return codes:
* 100: Success
*/
switch($newTopic)
{
//If no error = success.
case 100:
$success = 'You have successfully created the topic.';
$issuccess = 1;
$stop = true;
break;
}
$checkerror = $error;
$checksuccess = $success;
}
if($checksuccess){
$contents.="
".alert("success","$success")."";
refresh("3","/forum/t$id-$postid");
}
As you can see, I am trying to use $postid variable from the function newTopic(). Although, the $postid variable is empty.
How can I get the value from the function newTopic.php located in forum.php, to newtopic.php?

When you have used
return 100;
your code will never see
return $postid;
You can use this code to return
return array("code"=>"100","postid"=>$postid);
Now in new_topic.php use the code as shown
if($_POST)
{
$newTopic = $forum->newTopic();
/*
* Return codes:
* 100: Success
*/
switch($newTopic['code'])
{
//If no error = success.
case 100:
$success = 'You have successfully created the topic.';
$issuccess = 1;
$stop = true;
break;
}
$checkerror = $error;
$checksuccess = $success;
}
if($checksuccess){
$contents.="
".alert("success","$success")."";
refresh("3","/forum/t$id-$newTopic['postid']");
}

Your code looks that is returning value 100 before returning $postid variable.
That's wrong.Your code will exit the function at first return.
comment the line "//return 100;"
OR return an array. You cannot return two values like u do.
Instead of doing
return 100;
return $postid;
Do
//return 100;
return array("successs"=>100,"id"=>$postid);
Then use your $newTopic variable as folows:
In switch:
switch($newTopic['success'])
Use the postId anywhere else
$newTopic['id']

try with reference like in the below code
function newTopic(&$postid){
// Get the POST data
global $ir;
$postid = mysql_insert_id();
mysql_query("UPDATE forum_topics SET post_id='$postid' WHERE topic_id='$topicid'");
// No error found and the update was succesful - Return success!
return 100;
}
....... //some codes
$postid = null;
newTopic($postid);
$my_postId = $postid; //Now you have your post ID
OR in you exists code like
if($_POST)
{
$last_postid = null;
$newTopic = $forum->newTopic($last_postid );
/*
* Return codes:
* 100: Success
*/
switch($newTopic)
{
//If no error = success.
case 100:
$success = 'You have successfully created the topic.';
$issuccess = 1;
$stop = true;
$postid = $last_postid;
break;
}
$checkerror = $error;
$checksuccess = $success;
}
if($checksuccess){
$contents.="
".alert("success","$success")."";
refresh("3","/forum/t$id-$postid");
}
EDIT: Call-time pass-by-reference fixed.

If you want to return two values you can not just write two returns.
There are several options to return more values. One is using an array:
return array(100, $postId);
and
list($status, $postId) = $forum->newTopic();
You can also use an associatve array as s.d suggested.
However, as your one variable only contains the status you can also use exceptions in the case the operation fails.

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.

get results returned in a function

i have this inside a php function:
$result = new stdClass();
$result->domainname = $domainName;
$result->element = $element;
$result->availability = $availability;
return ($result);
so its returning all of the values in the $result variable
when i do a print_r on the function, the results display like this:
stdClass Object
(
[domainname] => domain.com
[element] =>
[availability] => false
)
i am calling the function with this code:
$domain = domainNameCheck($_GET["domain"].'.'.$_GET["tld"]);
so i tried to get the returned by doing $domain->availability but its not returning the value, example:
if($domain->availability) {
echo 'yes';
} else {
echo 'no';
}
am i trying to get the data the incorrect way?
UPDATE
the full function is:
if(!function_exists("domainNameCheck")) {
function domainNameCheck($domainName, $element) {
$result = '';
$client = new IcukApiClient();
$client->username = "username";
$client->key = "pass";
$client->encryption = "SHA-512";
$req = new IcukApiRequest();
$req->url = "/domain/availability/" . $domainName;
$req->method = "GET";
$res = $client->send($req);
$availability = 'unknown';
if ($res->success) {
$obj = json_decode($res->response);
$availability =($obj->available) ? 'true' : 'false';
}
else {
$availability = 'unknown';
}
$result = new stdClass();
$result->domainname = $domainName;
$result->element = $element;
$result->availability = $availability;
return ($result);
}
}
Your main problem seems to be that you are calling a function with 2 parameters but passing only one parameter
function domainNameCheck($domainName, $element) {}
// called like this (one parameter)
$domain = domainNameCheck($_GET["domain"].'.'.$_GET["tld"]);
This should be generating a compile error!
Also here
if ($res->success) {
$obj = json_decode($res->response);
// check what $obj->available is set to
// it may also be a string and not a boolean
print_r($obj);
$availability =($obj->available) ? 'true' : 'false';
}
else {
$availability = 'unknown';
}
Please note that there are two error/warning messages PHP is giving:
E_WARNING : type 2 -- Missing argument 2 for domainNameCheck()
E_NOTICE : type 8 -- Undefined variable: element
You should fix those errors, and make sure you are informed of errors during development.
Secondly, you have defined your availability as a string by assigning "false", "true", or "unknown". So when you do this:
if($domain->availability) {
... that will be true for all three values, because strings are true for PHP when converted to boolean (except when empty). To illustrate, this will echo "hello":
if ("false") echo "hello";
So you need to change your test like this:
if($domain->availability === "true") {
Or, If you want to define $domain->availability as a true boolean, then you need to alter the assignments in your function, like this:
....
$availability = $obj->available; // assuming that is a boolean!
}
else {
$availability = null; // unknown
}
... and then you can do what you had:
if($domain->availability) {
Likely because $domain->availability is boolean
To output you can first check whether its true or false and output accordingly
here's a simple example:
if ($domain->availability){
echo 'Available';
}
else {
echo 'Not Available';
}

Function returns strings but not when stored in variable

I have a strange problem with a function i wrote. When returning an hardcoded string like "Hello" it returns this value, but when i store this value in a variable it doesn't return anything.
Also when i don't store it in a variable and try to return it nothing gets returned.
Below is my code. Can anybody see what i'm doing wrong?
Thanks in advance.
public function getPath($pageID = null) {
if($pageID == null) $pageID = $this->id;
$data = $this->_db->fetch_array("SELECT * FROM `pages` WHERE `id` = '".$pageID."'");
if(!empty($data)) {
$this->tempPath[] = $data['basename'];
if($data['parentID'] != 0) {
$this->getPath($data['parentID']);
} else {
$returnPath = $this->tempPath;
$this->tempPath = array();
$returnPath = implode('/', array_reverse($returnPath));
//This variable holds the value, when echo'ed its the correct value
echo $returnPath;
return $returnPath;
}
}
}
Rewrote the code to the following and now it's working
public function getPath($pageID = null) {
if($pageID == null) $pageID = $this->id;
$data = $this->_db->fetch_array("SELECT * FROM `pages` WHERE `id` = '".$pageID."'");
if(!empty($data)) {
$this->tempPath[] = $data['basename'];
}
return implode('/', $this->tempPath);
}
Problem was that the code was in a foreach loop which kept overwriting the correct values and looping till there is no path to return. Thanks for the suggestions.
More code isn't always better :-)

PHP - Return array from function

I am submitting a form, using the following function (prize.php):
loadmodule('validate'); //This just loads the validate.php function.
$validate = new Validate;
if($_POST)
{
$validateForm = $validate->validateForm();
switch($validateForm)
{
case 1:
$error = 'You\'re not logged in..';
$stop = true;
break;
//If no error = success.
if($validateForm['code'] == "100"){
$won = $val['prize'];
$type = $val['type'];
$success = 'You have won! The prize was '.$won.' '.$type.'';
die($success);
}
}
die($error);
}
This is the function to validate the form (validate.php):
function validate()
{
global $userdata;
if(!is_array($userdata))
return 1; // User not logged in - return error code one.
//If no error, lets show a success message.
$prize = "100";
$text = "dollars";
return array("code"=>"100","prize"=>"$prize","type"=>"$text");
}//If won
}
The above code returns:
Notice: Undefined variable: error in /home/.../public_html/pages/prize.php on line 27
Although, it shouldn't throw an error there, since the die($success) should be triggered by the code 100.
What am I doing wrong?
$error = '';
$stop = false;
switch($validateForm){
case 1:
$error = 'You\'re not logged in..';
$stop = true;
break;
}
//If no error = success.
if($validateForm['code'] == "100"){
$won = $val['prize'];
$type = $val['type'];
$success = 'You have won! The prize was '.$won.' '.$type.'';
die($success);
}
first guess is that the if($validateForm['code'] == "100"){ is ment to be outside the switch.
$validateForm = $validate->validateForm();
returns an array.. later on your're doing a if ($validateForm==1) in the switch.. when $validateForm is an array.
you might have better luck with a simple is_array() if statement than the whole switch

Custom 404 error message not working in codeigniter

When I access the wrong function in my controller, a 404 error page is working well. But, when i access url like 'http://example.com/model/detail/116', which 116 is wrong number [are not in the database], my 404 error page not working.
I have this code in my controller:
public function detail()
{
$id['id_galeri'] = $this->uri->segment(3);
$detail = $this->app_model->getSelectedData("tbl_galeri",$id);
foreach($detail->result() as $d)
{
$bc['jdl'] = "View";
$bc['id_galeri'] = $d->id_galeri;
$bc['nama'] = $d->nama;
$bc['foto'] = $d->foto;
$bc['deskripsi'] = $d->deskripsi;
$bc['stts_input'] = "deskripsi";
}
if($this->uri->segment(3) == '' && $id['id_galeri'] == FALSE)
{
$segment_url = 0;
}else{
if(!is_numeric($this->uri->segment(3)) || !is_string($this->uri->segment(3))){
redirect('404');
}else{
$segment_url = $this->uri->segment(3);
}
}
$this->load->view('frontend/global/bg_top');
$this->load->view('frontend/page/bg_view_model',$bc);
$this->load->view('frontend/global/bg_footer');
}
Sorry for my bad english, please help :-)
Thank you..
Instead of:
redirect('404');
try using CodeIgniter's native:
show_404('page');
EDIT
Try this code, a bit cleaned up and the checks are done before they're saved for views use.
public function detail()
{
$id['id_galeri'] = $this->uri->segment(3);
// Check if the supplied ID is numeric in the first place
if ( ! is_numeric($id['id_galeri']))
{
show_404($this->uri->uri_string());
}
// Get the data
$detail = $this->app_model->getSelectedData("tbl_galeri",$id);
// Check if any records returned
if (count($detail->result()) === 0)
{
show_404($this->uri->uri_string());
}
foreach($detail->result() as $d)
{
$bc['jdl'] = "View";
$bc['id_galeri'] = $d->id_galeri;
$bc['nama'] = $d->nama;
$bc['foto'] = $d->foto;
$bc['deskripsi'] = $d->deskripsi;
$bc['stts_input'] = "deskripsi";
}
/**
* Here do whatever you want with the $segment_url which doesn't seem to be
* used in your code
*/
$this->load->view('frontend/global/bg_top');
$this->load->view('frontend/page/bg_view_model',$bc);
$this->load->view('frontend/global/bg_footer');
}

Categories