How to use return value in PHP - php

Im sending a mail from one function to another like this
sendMail($email)
if($result == 1) {
return redirect('/')->with("msg", $response);
} else {
return redirect('/')->with("msg", $badResponse);
}
function sendMail($email) {
//...
if($mail->send){
$result = 1;
} else {
$result = 2;
}
echo $result;
}
How do i get the value of $result and use it after the function call?

You need to return the result and save it to a variable, rather than just echoing it:
$result = sendMail($email);
if($result == 1) {
return redirect('/')->with("msg", $response);
} else {
return redirect('/')->with("msg", $badResponse);
}
function sendMail($email) {
//...
if($mail->send){
$result = 1;
} else {
$result = 2;
}
return $result;
}

Related

How to pass more arguments to that function?

I have this function:
function mobio_checkcode($servID, $code, $debug=0) {
$res_lines = file("http://www.mobio.bg/code/checkcode.php?servID=$servID&code=$code");
$ret = 0;
if($res_lines) {
if(strstr("PAYBG=OK", $res_lines[0])) {
$ret = 1;
}else{
if($debug)
echo $line."\n";
}
}else{
if($debug)
echo "Unable to connect to mobio.bg server.\n";
$ret = 0;
}
return $ret;
}
And here how i use it:
if(mobio_checkcode($servID, $code, 0) == 1) {
echo "Code is valid!!";
}
$code = $_REQUEST['code'];
$servID = 29;
$post = $_REQUEST['post'];
Here i have form! In this form u enter code and display is valid or no so i want to pass more $code like
$code1 = $_REQUEST['code1'];
$code2 = $_REQUEST['code2'];
$code3 = $_REQUEST['code3'];
I want to pass more variables to function how it will be done.. Please help me thank u <3
Just pass all of variables as array like
$array = ['servID'=>29,'code'=>XXXX];
function checkcode($array) {
//Do stuff
$array['servID']
$array['code']
}
function mobio_checkcode($servID, $code, $debug=0, $element1, $element2) {
$res_lines = file("http://www.mobio.bg/code/checkcode.php?servID=$servID&code=$code");
$ret = 0;
if($res_lines) {
if(strstr("PAYBG=OK", $res_lines[0])) {
$ret = 1;
}else{
if($debug)
echo $line."\n";
}
}else{
if($debug)
echo "Unable to connect to mobio.bg server.\n";
$ret = 0;
}
return $ret;
//you can pass extra elements so on.. otherwise create an array of elements and pass only array to function

Memcache results and while loop

I wrote this function for caching queries:
function get_cached($query, $type = 1) {
$key = md5(strtolower($query));
$cached = $memcache->get($key);
if($cached) {
$res = unserialize($cached);
} else {
$r = mysql_query($query);
if($mode == 1) {
$res = mysql_fetch_object($r);
} else {
$res = mysql_fetch_array($r);
}
$memcache->store($key, serialize($res));
}
return $res;
}
And it kinda works, i can cache simple queries. But i have problem with queries that operate within loops.
I really can't understand how to get around this, and "port" this to use my get_cached() function first.
$ref = mysql_query("query");
while($res = mysql_fetch_object($ref)) {
//do something with results
}
How i can do it through cache?
You cannot store the mysql result object but you can fetch all rows into an array and cache the array. like
function get_cached($query, $type = 1) {
$key = md5(strtolower($query) . $type);
$cached = $memcache->get($key);
if($cached) {
return unserialize($cached);
} else {
$r = mysql_query($query);
$data = array();
if($mode == 1) {
foreach($row = mysql_fetch_object($r)) {
$data[] = $row;
}
} else {
foreach($row = mysql_fetch_array($r)) {
$data[] = $row;
}
}
$memcache->store($key, serialize($data));
}
return $data;
}
don't forget to store the type of your functions as cache key too, otherwise you fetch a results set with type==1 and in return you get the elements as array

which is more efficient, simple or nested condition using IF()

I'm newbie, and just want to asking about programming stuff. I hope you guys help me getting understand :)
which is more efficient in coding and performance between this two function?
first function using nested condition, and second function using simple condition,
which is better to be implemented?
function optionOne()
{
$a = getData();
$return = array();
if ($a === false) {
$return['error'] = true;
} else {
$b = getValue();
if ($b === false) {
$return['error'] = true;
} else {
$c = getVar();
if ($c === false) {
$return['error'] = true;
} else {
$return['error'] = false;
$return['message'] = 'congrat!';
}
}
}
return $return;
}
function optionTwo()
{
$return = array();
$a = getData();
if ($a === false) {
$return['error'] = true;
return $return;
}
$b = getValue();
if ($b === false) {
$return['error'] = true;
return $return;
}
$c = getVar();
if ($c === false) {
$return['error'] = true;
return $return;
} else {
$return['error'] = false;
$return['message'] = 'congrat!';
}
return $return;
}
thank you before guys,
function option()
{
$return=array();
$return['error'] = true;
switch(getData()){
case false:
return $return;
break;
case true:
if(getValue()==false){return $return;}
else{
if(getVar()==false){return $return;}
else{
$return['error'] = false;
$return['message'] = 'congrat!';}
}
break;
default:
return 'getData() return null value';
break;
}
}
i was tried to applied the switch method to your function, as one of your option too
A neater option would be to make the 3 functions throw an exception when there's an error instead of returning boolean false. That's what exceptions are for anyway. Then in your function you can just wrap the calls in a try-catch block.
function option {
$return = array();
try {
$a = getData();
$b = getValue();
$c = getVar();
$return['error'] = false;
$return['message'] = 'congrat!';
} catch(Exception e) {
$return['error'] = true;
}
return $return;
}

How to display MySQL select statements in PHP / HTML

The MySQL selects are not displaying properly in the PHP / HTML
This is my code:
<?php
session_start();
require_once("database.php");
require_once("MySQL_connection.php");
/* Database connection */
$db = new MySQLConnection($config['sql_host'], $config['sql_username'], $config['sql_password'], $config['sql_database']);
$db->Connect();
unset($config['sql_password']);
/* Cron */
require_once("cron.php");
/* Display Advert */
$ad_link = $db->Query("SELECT `site_url` FROM `adverts` WHERE `zone`=1 AND `days`>0 ORDER BY RAND() LIMIT 0,1;");
$img_link = $db->Query("SELECT `image_url` FROM `adverts` WHERE `zone`=1 AND `days`>0 ORDER BY RAND() LIMIT 0,1;");
?>
<!DOCTYPE html>
<html>
<body>
<img src="<? echo $img_link ?>">
</body>
</html>
For some reason that is displaying as:
<html><head></head><body>
<img src="Resource id #7">
</body></html>
Is anybody know what is wrong?
Forgot to add the code for MYSQL_connection.php, the following code is everything within that file that is used to connect to the DB.
<?php
class MySQLConnection {
private $sqlHost;
private $sqlUser;
private $sqlPassword;
private $sqlDatabase;
private $mySqlLinkIdentifier = FALSE;
public $QueryFetchArrayTemp = array();
private $numQueries = 0;
public $UsedTime = 0;
public function __construct($sqlHost, $sqlUser, $sqlPassword, $sqlDatabase = FALSE) {
$this->sqlHost = $sqlHost;
$this->sqlUser = $sqlUser;
$this->sqlPassword = $sqlPassword;
$this->sqlDatabase = $sqlDatabase;
}
public function __destruct() {
$this->Close();
}
public function Connect() {
if($this->mySqlLinkIdentifier !== FALSE) {
return $this->mySqlLinkIdentifier;
}
$this->mySqlLinkIdentifier = mysql_connect($this->sqlHost, $this->sqlUser, $this->sqlPassword, TRUE); // Open new link on every call
if($this->mySqlLinkIdentifier === FALSE) {
return FALSE;
}
if($this->sqlDatabase !== FALSE) {
mysql_select_db($this->sqlDatabase, $this->mySqlLinkIdentifier);
}
return $this->mySqlLinkIdentifier;
}
public function Close() {
if($this->mySqlLinkIdentifier !== FALSE) {
mysql_close($this->mySqlLinkIdentifier);
$this->mySqlLinkIdentifier = FALSE;
}
}
public function GetLinkIdentifier() {
return $this->mySqlLinkIdentifier;
}
public function Query($query) {
$start = microtime(true);
$result = mysql_query($query, $this->GetLinkIdentifier());
$this->UsedTime += microtime(true) - $start;
$this->numQueries++;
if( $result === false ){
die($this->GetErrorMessage());
}
return $result;
}
public function FreeResult($result) {
mysql_free_result($result);
}
public function FetchArray($result) {
return mysql_fetch_array($result, MYSQL_ASSOC);
}
public function FetchArrayAll($result){
$retval = array();
if($this->GetNumRows($result)) {
while($row = $this->FetchArray($result)) {
$retval[] = $row;
}
}
return $retval;
}
public function GetNumRows($result) {
return mysql_num_rows($result);
}
public function GetNumAffectedRows() {
return mysql_affected_rows($this->mySqlLinkIdentifier);
}
// Helper methods
public function QueryFetchArrayAll($query) {
$result = $this->Query($query);
if($result === FALSE) {
return FALSE;
}
$retval = $this->FetchArrayAll($result);
$this->FreeResult($result);
return $retval;
}
public function QueryFirstRow($query) {
$result = $this->Query($query);
if($result === FALSE) {
return FALSE;
}
$retval = FALSE;
$row = $this->FetchArray($result);
if($row !== FALSE) {
$retval = $row;
}
$this->FreeResult($result);
return $retval;
}
public function QueryFirstValue($query) {
$row = $this->QueryFirstRow($query);
if($row === FALSE) {
return FALSE;
}
return $row[0];
}
public function GetErrorMessage() {
return "SQL Error: ".mysql_error().": ";
}
public function EscapeString($string) {
if (is_array($string))
{
$str = array();
foreach ($string as $key => $value)
{
$str[$key] = $this->EscapeString($value);
}
return $str;
}
return get_magic_quotes_gpc() ? $string : mysql_real_escape_string($string, $this->mySqlLinkIdentifier);
}
function GetNumberOfQueries() {
return $this->numQueries;
}
public function BeginTransaction() {
$this->Query("SET AUTOCOMMIT=0");
$this->Query("BEGIN");
}
public function CommitTransaction() {
$this->Query("COMMIT");
$this->Query("SET AUTOCOMMIT=1");
}
public function RollbackTransaction() {
$this->Query("ROLLBACK");
$this->Query("SET AUTOCOMMIT=1");
}
public function GetFoundRows() {
return $this->QueryFirstValue("SELECT FOUND_ROWS()");
}
public function GetLastInsertId() {
return $this->QueryFirstValue("SELECT LAST_INSERT_ID()");
}
public function QueryFetchArray($query, $all = false, $useCache = true)
{
$tempKey = sha1($query . ($all === true ? 'all' : 'notAll'));
$temp = $this->QueryFetchArrayTemp[$tempKey];
if ($temp && $useCache === true)
{
return unserialize($temp);
}
else
{
$queryResult = $this->Query($query);
$result = $all === true ? $this->FetchArrayAll($queryResult) : $this->FetchArray($queryResult);
$this->QueryFetchArrayTemp[$tempKey] = serialize($result);
return $result;
}
}
}
?>
Using your custom MySQL class, this will probably work:
$result = $db->Query("SELECT `site_url`,`image_url` FROM `adverts` WHERE `zone`=1 AND `days`>0 ORDER BY RAND() LIMIT 0,1;");
while($row = $db->FetchArray($result)) {
echo '<img src="' . $row['image_url'] . '">';
}
$db->FreeResult($result);
However, as others have pointed out, the code used in your custom MySQL class is deprecated and should be updated to use newer php methods/libraries.
You are using some custom MySQL wrapper, but you probably should fetch the result from the query using mysql_result(), mysql_fetch_array() or similar.
You would do well to read up on mysqli, which is a safer way to carry out MySQL queries. You can find the excellent documentation here: http://php.net/manual/en/book.mysqli.php and there is also a very useful tutorial here which covers simple queries like yours: http://www.phphaven.com/article.php?id=65
For your specific question, I would use the following:
$query = "SELECT `site_url`,`image_url` FROM `adverts` WHERE `zone`=1 AND `days`>0 ORDER BY RAND() LIMIT 0,1;";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// I've split these lines up to make them a little more readable.
echo '<a href="';
echo $row['site_url'];
echo '">';
echo '<img src="';
echo $row['image_url'];
echo '"</img></a>';
}
}
else {
echo 'NO RESULTS';
}
I hope this helps.

Why does this PHP function cycle endlessly?

function nonrecgen($min, $max, $amount) {
for($i=0;$i<$amount;$i++) {
$NrArray[$i] = rand($min,$max);
echo $NrArray[$i];
do {
for($j=0;$j<=$i;$j++) {
if ($NrArray[$j] == $NrArray[$i]) {
$NrArray[$i] = rand($min,$max); }
}
$Reccuring = false;
if ($i > 0) {
for($k=0;$k<=$i;$k++) {
if ($NrArray[$k] == $NrArray[$i]) {
$Reccuring = true; }
}
}
}
while ($Reccuring = true);
}
Return $NrArray;
}
$Test = nonrecgen(0,1,2);
print_r($Test);
I wanted to look into how to generate an array of nonreccuring numbers and while this is certainly not the most efficient way I believe, I can't seem to figure out why it loops endlessly on the first iteration. I tried logical analysis over and over, but there has to be something I'm missing.
do {
...
} while ($Reccuring = true);
Because your while statement sets $Reccuring to true, instead of evaluating it.
Try:
do {
...
} while ($Reccuring === true);
Other than the = to == you were also resetting the $Recurring in the wrong place:
<?
function nonrecgen($min, $max, $amount)
{
for($i=0;$i<$amount;$i++)
{
$NrArray[$i] = rand($min,$max);
do
{
for($j=0;$j<=$i;$j++)
{
if ($NrArray[$j] == $NrArray[$i])
{
$NrArray[$i] = rand($min,$max);
}
}
if ($i > 0)
{
for($k=0;$k<=$i;$k++)
{
if ($NrArray[$k] == $NrArray[$i])
{
$Reccuring = true;
}
}
}
$Reccuring = false;
}
while ($Reccuring == true);
}
return $NrArray;
}
$Test = nonrecgen(0,2,5);
echo "<pre>";
print_r($Test);
?>
You're currently assigning a value rather than checking (which will always be true).
Change it to: while ($Reccuring == true);

Categories