I have a return statement in my function:
function fun($result)
{
$counter = 0;
while($row=mysql_fetch_array($result))
{
/*if($counter==2)
{
return $name;
}*/
$user=$row['message'];
$sql2="select username from members where id='$user'";
$result2=mysql_query($sql2);
$row2=mysql_fetch_array($result2);
$name .= $row2['username']." and ";
$counter++;
if($counter==2)
{
return $name;
}
}
}
The return block (commented) doesn't work which immediately terminates the execution of the function irrespective of the condition. But the return block if placed in position as shown in the code just works fine. Why?
I want to return only 2 rows. It seems that it should work whether it is placed before or after,because it depends on the value of the counter. Check the condition before adding new row to $name variable.First row will be added to $name and $counter is incremented,then check the condition and so on.What is wrong?
Function doesn't return anything when there are less than 3 rows even if you want to return when you reach 2, you need 3 rows minimal.
The function checks $counter in the loop after you handled your 2nd row.
So there need to be at least 3 rows for the function to return the $ name. This is weird because you want it to return then there are 2 names found.
The function doesn't necessarily terminates, but simply doesn't return anything.
Your function may never reach the return statement. You have to check for both conditions to be false and then return $name if they are. A for loop should do what you need.
function fun($result)
{
for($cnt=0; ($row=mysql_fetch_array($result)) AND $cnt<2; $cnt++)
{
$name .= 'Your Data';
}
return $name;
}
Related
i dont understand how the if statement works and the function is called, why i am getting "He has more strength", i know because the strength is greater, but what i am getting there, is it a boolean? can i dump it, it shows me NULL if i put this inside the if statement
edit:i have added the return.
<?php
class Ship
{
public $name;
public $strength = 0;
public function doesGivenShipHaveMoreStrength($givenShip)
{
return $givenShip->strength > $this->strength;
}
}
$myShip = new Ship();
$myShip->name = 'TIE Fighter';
$myShip->strength = 150;
$otherShip = new Ship();
$otherShip->name = 'Imperial Shuttle';
$otherShip->strength = 50;
if ($myShip->doesGivenShipHaveMoreStrength($otherShip)) {
echo $otherShip->name.' He has more strength';
} else {
echo $myShip->name.' She has more strength';
}
?>
If statements evaluates whatever inside it's braces () . if true or 1 the block or statement will be executed. your function returned a value , and that returned value is later evaluated by the if statement. these are examples that might help you understand how if statements work. the same goes with almost every other programming language.
//example 1
if(true){
// will be executed
}else{
// will not executed
}
//example 2
if(false){
// will not executed
}else{
// will be executed
}
//example 3
if( 2 > 1){
// will be executed
}else{
// will not executed
}
//example 4
if(1){
// will be executed
}else{
// will not executed
}
//example 5
if(0){
// will not executed
}else{
// will be executed
}
//example 5
if(myFunction()){
// will be executed
}else{
// will not executed
}
function myFunction()
{
return true;
}
Your class is not written properly, it should be :
class Ship
{
public $name;
public $strength = 0;
public function doesGivenShipHaveMoreStrength($givenShip)
{
return ($givenShip->strength > $this->strength);
}
}
Then it will work as expected :) In your version, the function does return nothing, as a result when you use it, it evaluates to NULL, which is equivalent to false, and your test block fails !
I would add one more point to the recently answers.
You must add return.
Even you add the return, you shall hit your block containing "He has more strength".
Reason: you are comparing with this->strength which is 0 and your both objects have strength set to 150 & 50 accordingly. It's going to be always true.
I would suggest to compare object level values if you are really want to achieve the same functionality.
Revised Answer: You may need to adjust/fix your condition.
as per your code snippet at here
Your value of given ship shall be printed as 50 and current object value is 150 . your function is checking if 50 > 150? answer would be false and you shall hit your else.
Hope this helps
I have a method called getField and it calls fetch, and I was wondering if there is method similar to fetch, only that it doesn't move the internal cursor forward, and instead stays where it is.
So, I have the following methods:
public function getField($field_name){
if(!is_array($this->row) || empty($this->row)){
$this->row = $this->stmt->fetch(PDO::FETCH_ASSOC);
}
return $this->row[$field_name];
}
public function nextRow($type = PDO::FETCH_ASSOC){
if(!($this->stmt instanceof PDOStatement)){
return array();
}
$this->row = $this->stmt->fetch($type);
$this->setArray($this->row);
return $this->row;
}
When I call getFields then nextRow the cursor moves ahead before nextRow is called. When that happens I would like the cursor to stay where it is and only increment when nextRow is called. Is there something like this?
Example
$this->db->query($somequery, $arrary_replacements);
if($this->db->getField("myField") === null){
// Do some stuff
// Do some database queries too
}else{
$row = $this->db->nextRow();
// Process $row
}
Your example
$this->db->query($somequery, $arrary_replacements);
if($this->db->getField("myField") === null){
// Do some stuff
// Do some database queries too
}else{
$row = $this->db->nextRow();
// Process $row
}
In my mind, your example usage is flawed. You have already accessed the first row by using getField(), therefore logically, I would assume nextRow() should get the second row. Otherwise you are saying that nextRow should return the current row but continue to the next row, which through my eyes, is confusing.
If you actually want the $row for processing then why don't you do this?
$this->db->query($somequery, $arrary_replacements);
$row = $this->db->nextRow();
if($row['myField'] === null){
// Do some stuff
// Do some database queries too
}else{
// Process $row
}
Otherwise, I think you should consider adding a new function named getRow() or currentRow() to obtain the current row data (return $this->row) as to not confuse other developers.
I have inherited an application that is not doing what it's supposed to do. I have isolated the problem to the database not being properly attached. The programmer wrote this function that seemingly is suppose to evaluate whether the database is attached, calling the "attachPaymentDatabase()" function to attach it if it's not.
function attachPaymentDatabaseIfNotDoneAlready()
{
global $db;
global $hasPaymentDatabaseAttached;
// Determine if we have attached the payment tables, and if not, add them.
$hasPaymentDatabaseAttached = false;
try {
// this new way should work the best-- looking for PAY.
$alldb = queryall($db, "PRAGMA database_list;");
for ($i = 0; $i < count($alldb); $i++)
{
$alldb[$i] = array_change_key_case($alldb[$i], CASE_LOWER);
if (strtolower($alldb[$i]['name']) == 'pay')
{
debugEmail("condition 1 worked.");
$hasPaymentDatabaseAttached = true;
break;
}
}
// if its name changed this will also work
if (!$hasPaymentDatabaseAttached)
{
$r = #$db->querySingle("SELECT * FROM PAY_PARAMETER;");
$hasPaymentDatabaseAttached = true;
debugEmail("condition 2 worked.");
}
}
catch(Exception $e)
{
}
if (!$hasPaymentDatabaseAttached)
{
debugEmail("nothing worked.");
attachPaymentDatabase();
}
}
I have written a debugEmail() function that emails me a defined message with a timestamp as used above. When executing the code from the application, I can see that "condition 2 worked." is being called one second before "nothing worked.".
I don't understand how this can be. If debugEmail("condition 2 worked."); is executing, then so should too $hasPaymentDatabaseAttached = true; in which case this should not execute:
if (!$hasPaymentDatabaseAttached)
{
debugEmail("nothing worked.");
attachPaymentDatabase();
}
But it clearly is.
What is going on here?!?!?!?
No it shouldn't, because $hasPaymentDatabaseAttached is set to true in the first condition. In still nonsense at all, but it works as described.
I want to create a function in class, to create username, function will check if username exist then it will increment username like username_1. and check if this username exist or not if it exist again increment it to username_2 till new username created. I have created this function but it return me nothing.Please help me what is wrong in my code.
class a{
function check_username($username){
if($usernameexist){
return true;
}
else
{
return false;
}
}
function create_username($username) {
$__name = __FUNCTION__;
if ($this->check_username($username)) {
$n++;
$username = $username . "_" . $n;
//return $__name($username); this return fatal error.
return call_user_func('create_username', $username);
} else {
return $username;
}
}
}
No need to use recursion for this, a simple while(){} loop will do:
Plain-Jane Interator method
// your original function
function create_username($username){
// check if the username (as-is) already exists
if ($this->check_username($username)){
// use $n to keep a counter
$n = 1;
// while {username}_{n} exists, keep incrementing the counter
while ($this->check_username($username.'_'.$n)){
$n++;
/* If you don't want this to check to infinity, uncomment
* the below portion. the 100 is an arbitrary number, but use
* whatever you want as a limitation (could even make it a
* parameter in the method). Also, returning FALSE allows you to
* gracefully catch when max attempts are reached.
*
* e.g.
* if (($new_user = $obj->create_username('BradChristie')) !== FALSE){
* // user was successfully created within the max allowed attempts
* }
*/
//if ($n > 100) return FALSE
}
// return the result
return $username.'_'.$n;
}
// username was fine, return it back
return $username;
}
Recursive method
// recursive username check
public function create_username($username, $n = 0)
{
/* Same as above function, this is a check to prevent counting
* to infinity. uncomment to apply it
*/
//if ($n > 100) return FALSE;
// establish the username we're testing. if $n is 0,
// it's the original call to the function (don't add _0)
// if it's >0, it's part of the search so include it
$_username = $username . ($n > 0 ? '_'.$n : '');
// check if the username exists.
if ($this->check_username($_username))
{
// it exists, so make a call to this same function passing
// the original username and the value of n + 1 (move to next
// possibility)
return $this->create_username($username, $n+1);
}
// the name, as-is, was fine. return it
return $_username;
}
Example
Your code is wrong in several ways and, as pointed out elsewhere, your desired function is better written iteratively.
Some of the problems with your code are as follows:
You are doing your recursive check when check_username has succeeded. So, if you fail to find the original $username you are never modifying it, so never checking the modified value.
You are modifying the name passed to create_username by appending _n (for appropriate n). Since you are passing a modified name in your recursive call you will actually end up with multiple _n parts on the name.
Since you are not limiting your recursive calls, even if this was written correctly, you would eventually get nested too deep.
There is no need for recursivity in this case... A simple loop would do just perfectly:
function create_username($username) {
$original_username = $username;
$i=1;
while(! $this->check_username($username) ) {
$username = $original_username . '_' .$i++;
}
return $username;
}
I have a check function:
function checkCandidateEmail($email)
{
$email = $_POST;
if($email)
{
$candemail = (SQL);
if(isset($candemail['email']))
{
return TRUE;
} else {
return FALSE;
}
return $canEmailCheck;
}
}
I have started to create a function but I am getting NULL
function checkCandidateEmail($email)
{
$email = $_POST; // being immediately overwritten - redundant argument.
if($email) // Since $email isn't an optional argument, you'll get a PHP warning if it is missing, making this check confusing.
{
$candemail = (SQL); // Evaluating a constant? this will be bool
if(isset($candemail['email'])) // Since $candemail is a bool and not an array, this will never return true
{
return TRUE;
} else {
return FALSE;
} // this entire if/else block can be simplified to this: return (isset($candemail['email']));
return $canEmailCheck; // this is an undefined variable and will never get returned anyway because of the above return statements.
}
}
Please, elaborate more on your questions next time. I am not sure what you attempt to compare, if the $_POST with the SQL query or the argument passed with the SQL query. I assume the former.
If the email from that SQL table row equals the submitted email, returns TRUE. Else, returns FALSE. Really simplified version. Now it also checks if the user provided an email:
function checkCandidateEmail()
{
if (!$_POST['email']) echo "Error, please provide an email";
else
{
$candemail = (SQL); // Return a row from a query
return $candemail['email'] == $_POST['email'];
}
}
If an argument is passed, compares that against the database. If none is passed, compares the submitted $_POST['email'] against the database.
function checkCandidateEmail($email=null)
{
$candemail = (SQL); // Return a row from a query
if (!$email) $email = $_POST['email'];
return $candemail['email'] == $email;
}
NOTE: In both cases you have to substitute SQL for the right string and function depending on your database.
NOTE 2: Make sure that your query returns an email, as this simple code does not check if both strings are empty.