A bad result of the comparison - PHP - php

I have a function that connects to the database and returns a number and a second function, which returns the size of a file.
If I use the echo function to view the results functions: variable1 = 1345064, and variable2 = 135
,but when I use a comparison, go me incorrect result:
if($variable1 < $variable2)
{
echo 'This code is displayed';
}
else
{
echo 'This code should display';
}
what's wrong?
My source code:
<?php
include 'funkcje.inc';
$login = $_GET['login'];
$fsize = WielkoscPliku2($file);
$tmp = $fsize / 1000000;
$zmienna1 = SprTransfer($login);
$zmienna2 = floor($tmp);
if($zmienna1 < $zmienna2)
{
echo "This code is displayed";
}
else
{
echo "This code should be displayed";
}
?>
SprTransfer function:
<?php
require "connection.php";
connection();
...
function SprTransfer($login)
{
$zapytanie = "SELECT `transfer` FROM `uzytkownicy` WHERE `nick`='$login'";
$idzapytania = mysql_query($zapytanie);
$sprwaznosc = mysql_fetch_row($idzapytania);
return $sprwaznosc[0];
}
?>
Main file:
include 'funkcje.inc';
$login = $_GET['login'];
$fsize = WielkoscPliku2($file);
$tmp = $fsize / 1000000;
$zmienna1 = SprTransfer($login);
$zmienna2 = floor($tmp);
if($zmienna1 < $zmienna2)
{
echo "This code is displayed";
}
else
{
echo "This code should be displayed";
}
function.inc file:
require "connection.php";
connection();
function SprTransfer($login)
{
$zapytanie = "SELECT `transfer` FROM `uzytkownicy` WHERE `nick`='$login'";
$idzapytania = mysql_query($zapytanie);
$sprwaznosc = mysql_fetch_row($idzapytania);
return $sprwaznosc[0];
}

You are using variable names wrong. A variable needs to be preceded by a $.
$variable1 = 4;
$variable2 = 5;
if ($variable1 < $variable2) {
echo 'Yep';
}else {
echo 'Nope';
}
You should look into the basic syntax of PHP namely the Variables Section.

maybe the $ before variables:
if($variable1 < $variable2)

I'm not sure how, but it looks like you are interpreting your numbers as strings.
For example this will display This code is displayed:
<?php
$variable1 = "1345064a";
$variable2 = "135a";
if ($variable1 < $variable2) {
echo "This code is displayed";
}
else {
echo "This code should be displayed";
}
// Output: This code is displayed
?>
exmple
Cast your variables to int
<?php
$variable1 = "1345064a";
$variable2 = "135a";
if ((int) $variable1 < (int) $variable2) {
echo "This code is displayed";
}
else {
echo "This code should be displayed";
}
// Output: This code should be displayed
?>
example
Debugging:
You can check the type of your variables using gettype(). You should never use the output of gettype() to test for one particular type, since the output string is liable to change from one version of PHP to another.

assuming that missing the $ is just a typo ...
when you run into this type of problem, the best thing is to post a full working code sample. for example, the code below works as it should. it displays "This code should be displayed".
what happens when you run it? what is the difference between this code and yours? answer those two questions and you'll be at least pointed to your answer:
<?php
$variable1 = 1345064;
$variable2 = 135;
if ($variable1 < $variable2) {
echo "This code is displayed";
}
else {
echo "This code should be displayed";
}
?>

Related

Use return in php function with if statement

Is there a way to use return in a function with an if statement?
I would like to see either the function was executed until the if statement or not.
This would help me to check if the sql query would be executed as well.
I know to 100% I only could check it on the sql response, but I am looking for the shortest way to figure out if the content of a function was executed or not.
Here is an example:
<?php
function hi($i)
{
return (1==$i){echo "Hello"; };
}
$i = '1';
echo hi($i);
?>
I try to avoid to use it like this, since I always require to add an return before the end of the if statement:
<?php
function hi($i)
{
if(1==$i){
echo "Hello";
};
return true;
}
$i = '1';
echo hi($i);
?>
<?php
function ifReturn($input){
$message="";
if ($input == 3){
$message ="input is 3";
} else {
$message = "input is everything BUT 3";
}
return $message;
}
echo '<p>'.ifReturn(3).'</p>';
echo '<p>'.ifReturn(2).'</p>';

Simplified anarchy "if statement"

Is there a way to code this function/executable..
if($img1 > "")
{
$show = $img1;
}
elseif($img2 > "")
{
$show = $img2;
}
elseif($img3 > "")
{
$show = $img3;
}
else
{
$show = 'default.jpg';
}
echo $show;
..in a more simple way? Thx.
Any time you end up using variables named 1,2,3,etc it means you should be using an array.
If you had it like this, for example:
$img = [
1=> '',
2=> '',
3=> 'image.jpg'
];
You could then process this like so:
// Remove empty values
$img = array_filter($img);
// Echo the first value found (image.jpg)
echo current($img);
Or to add your default:
echo (count($img)) ? current($img) : 'default.jpg';
This uses a ternary operator to echo 'default.jpg' if count($img) is 0.
If you know the id number of the image, you could do something like this:
<?php
$images = array(
'myimg.jpg',
'my_awesome_img.jpg',
'awesome_awesome.jpg'
);
$show = $images[$x];
?>
You can just do
if(!empty($img1)) {
echo $img1;
} elseif(!empty($img2)) {
echo $img2;
} elseif(!empty($img3)) {
echo $img3;
} else {
echo 'default.jpg';
}
given that you only ever want to display one of these.
Did not test, but something like this:
<?php
$img1 = 'hello';
$img2 = 'world';
$array = [1,2,3];
for($i=1; $i<count($array); $i++){
$v = ${"img{$i}"};
if( !empty($v) ){
$show = $v;
break;
}
}
echo $show;
No idea what you're trying to accomplish or why the code looks like that, seems poorly constructed from the get-go.

dynamically name session isset how to use?

I am trying to get dynamic $_SESSION[$id] on the second page shown below, but its not working (as per the printout):
First page url
https://example.com/test.php?id=1548393
First page code
<?php
session_start();
$id = $_GET['id'];
$_SESSION[$id] = "mysecretstringline";
?>
Second page url
https://example.com/test2.php?id=1548393
Second page code
<?php
session_start();
$id = $_GET['id'];
if(isset($_SESSION[$id])){
echo "working";
}else{
echo "not working";
}
?>
i found problem we can not use numeric index for $_SESSION
but we can use number in $_SESSION by convert number to roman numerals
first page url
https://example.com/test.php?id=1548393
first page code
<?php
session_start();
$roman_id = romanic_number($_GET['id']);
$_SESSION[$roman_id] = "mysecretstringline";
function romanic_number($integer, $upcase = true)
{
$table = array('M'=>1000, 'CM'=>900, 'D'=>500, 'CD'=>400, 'C'=>100, 'XC'=>90, 'L'=>50, 'XL'=>40, 'X'=>10, 'IX'=>9, 'V'=>5, 'IV'=>4, 'I'=>1);
$return = '';
while($integer > 0)
{
foreach($table as $rom=>$arb)
{
if($integer >= $arb)
{
$integer -= $arb;
$return .= $rom;
break;
}
}
}
return $return;
}
?>
second page url
https://example.com/test2.php?id=1548393
second page code
<?php
session_start();
$roman_id = romanic_number($_GET['id']);
if(isset($_SESSION[$roman_id])){
echo "working";
}else{
echo "not working";
}
function romanic_number($integer, $upcase = true)
{
$table = array('M'=>1000, 'CM'=>900, 'D'=>500, 'CD'=>400, 'C'=>100, 'XC'=>90, 'L'=>50, 'XL'=>40, 'X'=>10, 'IX'=>9, 'V'=>5, 'IV'=>4, 'I'=>1);
$return = '';
while($integer > 0)
{
foreach($table as $rom=>$arb)
{
if($integer >= $arb)
{
$integer -= $arb;
$return .= $rom;
break;
}
}
}
return $return;
}
?>
output
working
thanks #gre_gor and #Katie
Could be that in your normal code (this just looks like a quick mockup), you have a space after ?> somewhere. That could cause issues.
<?php
// start.php
session_start();
$id = $_GET['id'];
$_SESSION[$id] = "mysecretstringline";
and
<?php
// next.php
session_start();
$id = $_GET['id'];
if (isset($_SESSION[$id])) {
echo "working";
} else {
echo "not working";
}
works for me. Notice no ?> characters.
UPDATE:
The following might be of interest regarding session name constraints (can a php $_SESSION variable have numeric id thus : $_SESSION['1234’])
You have that issue in your example you could just add an id_ and then do the same check when validating/getting the session.

PHP tables not printing out?

I'm calling a specific function, either getTaskList0, getTaskList1, or getTaskList2, each the same as below, with the number after task referring to the getTaskList number (in TaskManagerDAO):
function getTaskList0(){
$lst=array();
$con=$this->getDBConnection();
$result = $con->query("SELECT name, score FROM task0 ORDER BY score DESC");
$i = 0;
$counter=0;
while (($row =$result->fetch_row()) && ($counter<5)) {
$rec = new Task($row[0],$row[1]);
$lst[$i++]=$rec;
$counter++;
}
return $lst;
}
Task:
<?php
class Task{
public $name;
public $score;
function __construct($name,$score) {
$this->name = $name;
$this->score = $score;
}
}
The function is called in here:
<?php
session_start();
if(!class_exists('Action')){
include_once 'Action.php';
}
if(!class_exists('TaskManagerDAO')){
include_once 'TaskManagerDAO.php';
}
class Action_DisplayList implements Action{
public function execute($request){
if(!isset($_SESSION['functCount']))
$_SESSION['functCount']=0;
$functCount=$_SESSION['functCount'];
$functionName="getTaskList{$functCount}";
echo $functionName;
$dao = new TaskManagerDAO();
$names = $dao->$functionName();
$_SESSION['names'] = $names;
$last = sizeof($names);
$start = 0;
$_SESSION['start'] = $start;
$_SESSION['last'] =$last;
header("Location: tasklist.php");
}
}
?>
I'm trying to call the function by putting a variable at the end of the function name as a string and then calling the function. This works as I don't get any errors, but the list does not show up in the table, which is what this code is supposed to do:
<?php
if(isset($_POST['Add']) && ($_POST['name']!=="") &&!empty($_POST['Add'])){
include 'Action_Add.php';
Action_Add::execute();
}
$functCount=0;
$_SESSION['functCount']=0;
$names = $_SESSION['names'];
$start=$_SESSION['start'];
$last = $_SESSION['last'];
for($count = $start; $count < $last; $count++){
$name=$names[$count];
echo "<tr>";
echo "<td>".($count+1)."</td>";
echo "<td>".$name->name."</td>";
echo "<td>".$name->score."</td>";
echo "</tr>";
}
?>
EDIT:
I restarted my computer and everything and for the first run load of the page it worked perfectly. After that though, it stopped working though.
Use session_start(); before start using $_SESSION. So in your case, try something like
<?php
session_start();
if(isset($_POST['Add']) && ($_POST['name']!=="") &&!empty($_POST['Add'])){
//.... remaining code here
Note: To use cookie-based sessions, session_start() must be called before outputing anything to the browser.

Generating XML file through PHP results in a minor issue . Please help

In order to generate a XML i am using following Code currently.
.<?php
require ('../dbconfig/dbconfig.php');
$appId = $_GET['id'];
$sqlTabs = "Select _id,tab_title,position from tab_info where app_id=$appId order by position ";
$resultTabs=mysql_query($sqlTabs );
$countTabs=mysql_num_rows($resultTabs);
if($countTabs>0)
{
echo '<application applicationName="sample app">';
echo '<tabs>';
while ($rowTab = mysql_fetch_array($resultTabs) ) {
echo '<tab id="t'.$rowTab['_id'].'" tabtitle="'.$rowTab['tab_title'].'" position="'.$rowTab['position'].'" data="somedata">';
$sqlTabItems = "Select _id as tabitemId,item_type,item_title,item_data from items_info where tab_id=".$rowTab['_id']." and parent_id=0 order by _id ";
$resultTabItems=mysql_query($sqlTabItems);
$countTabItems=mysql_num_rows($resultTabItems);
if($countTabItems>0)
{
$level = 1;
echo '<listItems>';
while ($rowTabItem = mysql_fetch_array($resultTabItems) ) {
echo '<listItem id="'.$rowTabItem['tabitemId'].'" parentId="t'.$rowTab['_id'].'" itemtype="'.$rowTabItem['item_type'].'" itemtitle="'.$rowTabItem['item_title'].'" itemdata="'.$rowTabItem['item_data'].'" level="'.$level.'">';
giveitems($rowTabItem['tabitemId'],$rowTab['_id'],$level);
echo '</listItem>';
}
echo '</listItems>';
}
else
echo 'No Data';
echo '</tab>';
}
echo '</tabs></application>';
}
else
{
echo 'No Data';// no tabs found
}
function giveitems($pitemId,$tabId,$level)
{
$sqlItems = "Select _id,item_type,item_title,item_data from items_info where parent_id=".$pitemId." order by _id ";
$resultItems=mysql_query($sqlItems);
$countItems=mysql_num_rows($resultItems);
$numbers = 0;
if($countItems>0)
{
$level = $level +1;
echo '<listItems>';
while ($rowItem = mysql_fetch_array($resultItems) ) {
echo '<listItem id="'.$rowItem[0].'" parentId="'.$pitemId.'" itemtype="'.$rowItem[1].'" itemtitle="'.$rowItem[2].'" itemdata="'.$rowItem[3].'" level="'.$level.'">';
/*********** Recursive Logic ************/
if(giveitems($rowItem[0],$tabId,$level)==1)
{
echo '</listItem></listItems>';
return 1;
}
else
{
echo '</listItem></listItems>';
return -1;
}
}
}
else
{
echo 'No Data';// no tabs found
return -1;
}
}
?>
Now in this code i want to replace all echo statements with a String variable and then i want to write that String variable content into a file , the porblem is if i define the string variable at the top of the file even then also that string variable cannot accessible from the giveItems functions below.
Pls suggest some solution
To access a global variable from within a function you need to write global $varname; at the top of that function's definition. Example:
function giveitems($pitemId,$tabId,$level) {
global $xmlstring;
// ....
}
However, this is pretty bad practice nowadays and you'd be better off writing a class that will both produce the XML and write it to a file.

Categories