I have created a function in which I have taken if and else-if ladder when first two condition false it gets turn to third condition. Third condition contains two dates and one categoryid but query shows blank answer.
My function is:
public function getfeestransonedate()
{
$odate=array_key_exists('odate',$_GET) ? date('Y-m-d',strtotime($_GET["odate"])) : null;
$sdate=array_key_exists('sdate',$_GET) ? date('Y-m-d',strtotime($_GET["sdate"])) : null;
$edate=array_key_exists('edate',$_GET) ? date('Y-m-d',strtotime($_GET["edate"])) : null;
$pdate=array_key_exists('pdate',$_GET) ? date('Y-m-d',strtotime($_GET["pdate"])) : null;
$qdate=array_key_exists('qdate',$_GET) ? date('Y-m-d',strtotime($_GET["qdate"])) : null;
$categoryid=array_key_exists('categoryid',$_GET) ? : null;
//echo $categoryid; die;
try {
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->SELECT('#__expense_transaction.expense_category_id, #__expense_transaction.date, #__expense_transaction.ammount as tamount, #__expense_transaction.transaction_details, #__expense_transaction.id, #__expenses_category_master.category_name');
$query->FROM('#__expense_transaction, #__expenses_category_master');
//var_dump(array($sdate,$edate,$odate));
if($sdate && $edate) {
$query->where('#__expense_transaction.date BETWEEN "'.$sdate.'" AND "'.$edate.'" AND #__expenses_category_master.id = #__expense_transaction.expense_category_id');
// echo $query; die;
} elseif($odate) {
$query->where('#__expense_transaction.date = "'.$odate.'" AND #__expenses_category_master.id = #__expense_transaction.expense_category_id');
//echo $query; die;
}
elseif($pdate && $qdate) {
$query->where('#__expense_transaction.date BETWEEN "'.$pdate.'" AND "'.$qdate.'" AND #__expense_transaction.expense_category_id = "'.$categoryid.'" AND #__expenses_category_master.id = #__expense_transaction.expense_category_id');
//echo $query; die;
} else {
echo 'Swapnil';
}
// echo $query; die;
$db->setQuery((string)$query);
$this->feestrans_data = $db->loadObjectList();
if ($error = $db->getErrorMsg()) {
throw new Exception($error);
}
}
catch (JException $e) {
if ($e->getCode() == 404) {
// Need to go thru the error handler to allow Redirect to work.
JError::raiseError(404, $e->getMessage());
}
}
}
Tell me if my query for third condition is right or wrong.
First note (and completely wrong):
Try writing elseif(condition) not else if(condition).
More info here: http://www.php.net/manual/en/control-structures.elseif.php
Second note (and this is your actual issue):
You first need to check if $_GET[key] exists and only then convert it to date value. Otherwise it'll return PHPs default date value (1970-01-01) not null of false as you probably expected.
So You should do like this:
$odate=array_key_exists('odate',$_GET) ? date('Y-m-d',strtotime($_GET["odate"])) : null;
$sdate=array_key_exists('sdate',$_GET) ? date('Y-m-d',strtotime($_GET["sdate"])) : null;
$edate=array_key_exists('edate',$_GET) ? date('Y-m-d',strtotime($_GET["edate"])) : null;
Related
I am really new at php and i came across this code.
Right now it checks for the hwid of a user and grants permission to a zip file if the hwid is in the valid users.
How can i make so the non valid users gets another zipfile to download?
Code:
`
$VALID_USERS = [
'BB12313-25DC-5132-BCEA-B23123123123',
''
];
$IS_REQUEST_ALLOWED = false;
if(!isset($_POST['hwid']) && !isset($_GET['hwid'])) { die(); }
$USER_HWID = '0';
if(isset($_POST['hwid'])) {
$USER_HWID = $_POST['hwid'];
} else {
$USER_HWID = $_GET['hwid'];
}
$USER_HWID = trim($USER_HWID);
$USER_HWID = strtoupper($USER_HWID);
foreach($VALID_USERS as $USER) {
$USER = strtolower($USER);
$HWID = strtolower($USER_HWID);
if($HWID === $USER) {
readfile('./ZIPFILE.zip'); die();
}
}
`
Assuming other code functions properly, your if clause at the end should look like this:
if($HWID === $USER) {
readfile('./ZIPFILE.zip'); die();
} else {
readfile('OtherFile.zip'); die();
}
After you compare $HWID === $USER, offer a different file in the ELSE added below.
foreach($VALID_USERS as $USER) {
$USER = strtolower($USER);
$HWID = strtolower($USER_HWID);
if($HWID === $USER) {
readfile('./ZIPFILE.zip'); die();
} else { //not a valid user
readfile("./invalid_file.zip");die();
}
}
Note that this will give "invalid_file.zip" to anyone who doesn't meet the criteria ($HWID===$USER) (maybe, see below).
Also, die() is rather a nasty way to exit (it doesn't even tell the user why it's leaving ...).
Please also take a look at your $VALID_USERS array. Surely you don't mean to have a null value in there?
Finally, what about the case of someone else who isn't null or "BB12313-25DC-5132-BCEA-B23123123123"?
You might wish to reconsider the use of this code.
Replace your entire foreach loop with this one if block. Since you are keeping your VALID_USERS in an array, you can use in_array() to quickly check if you user is there, the loop is unnecessary.
This:
foreach($VALID_USERS as $USER) {
$USER = strtolower($USER);
$HWID = strtolower($USER_HWID);
if($HWID === $USER) {
readfile('./ZIPFILE.zip'); die();
}
}
Becomes:
if (in_array($USER_HWID, $VALID_USERS, true)) {
readfile('./ZIPFILE.zip'); die();
} else {
readfile('./SomeOtherZIPFILE.zip'); die();
}
You will also notice that the 3rd paramter to in_array() has been set true in this example. This enables strict type comparison, to match the original codes '===' check.
I have 4 parameter in my URL. I retrieve the url parameter from my url that is given. With every parameter I'm changing the path to a directory and get different images.
My sample url look like this:
www.sample.com?cat=section1&language=de&prices=pl
The code is working but it's a spagheti code.
Is there a solution to make is less DRY ? How do I retrieve multiple url parameter ?
if(isset($_GET["cat"])) {
switch ($cat) {
case 'section1':
if(isset($_GET["language"])) {
$language = htmlspecialchars($_GET["language"]);
if($language == "de") {
if(isset($_GET["prices"])) {
$prices = htmlspecialchars($_GET["prices"]);
if($prices == "pl"){
$files=glob('pages/section1/dp/low/*.jpg');
}
else {
$files=glob('pages/section1/dn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/dn/low/*.jpg');
}
}
elseif ($language == "en") {
if(isset($_GET["prices"])) {
$prices = htmlspecialchars($_GET["prices"]);
if($prices == "pl"){
$files=glob('pages/section1/ep/low/*.jpg');
}
else {
$files=glob('pages/section1/en/low/*.jpg');
}
}
else {
$files=glob('pages/section1/en/low/*.jpg');
}
}
elseif ($language == "cz") {
if(isset($_GET["prices"])) {
$prices = htmlspecialchars($_GET["prices"]);
if($prices == "pl"){
$files=glob('pages/section1/cp/low/*.jpg');
}
else {
$files=glob('pages/section1/cn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/cn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/cn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/dn/low/*.jpg');
}
break;
case 'section2':
//the same like in section 1, path is .../section2/...
break;
case section3:
//the same like in section 1, path is .../section3/...
break;
default:
//the same like in section 1
break;
}
else {
//the same like in section 1
}
The path d=german, e=english, c=czech, p=prices, n=noprices
You could shorten/remove many if else statements with just doing the checks:
$lang_code = $language[0];
There you have your first letter, you can do the same with every GET parameter.
So you can use that as in:
$files=glob('pages/section1/'.$lang_code.'p/low/*.jpg');
You can do the same for everything else.
P.s.: don't forget to sanitze any user input i.e.:
$language=mysqli_real_escape_string($conn, $_GET['language']);
I'd probably do something like this:
<?php
$allowedCat = ['section1', 'section2'];
$allowedLanguage = ['pl', 'en', 'cz'];
$allowedPrice = ['pl', '??'];
$cat = (isset($_GET["cat"])) ? $_GET["cat"] : null;
$language = (isset($_GET["language"])) ? $_GET["language"] : null;
$prices = (isset($_GET["prices"])) ? $_GET["prices"] : null;
if (!in_array($cat, $allowedCat)) throw new \Exception('Invalid `cat`');
if (!in_array($language, $allowedLanguage)) throw new \Exception('Invalid `language` option.');
if (!in_array($prices, $allowedPrice)) throw new \Exception('Invalid `price` option.');
$someVar1 = ($prices === 'pl') ? 'p' : 'n';
$someVar2 = $language[0];
$files = glob("pages/{$cat}/{$someVar1}{$someVar2}/low/*.jpg");
Think that should be self explanatory. Translates one to one really. Was not certain on how the other price option was specified...
Hello I'm having trouble thinking of a way to set custom variables with there $_GET counterpart in a cleaner way than below, this is a post-back for the url http://example.com/postback.php?id={offer_id}&offer={offer_name}&session={session_ip}&payout={payout} after running I get all $_GET with either their data or nil for all variables: $id, $offer, $session, $payout obviously i am a php newbie, please go easy on me! Thanks, any help would be great.
if (s('id')) {
$id = $_GET["id"];
} else {
$id = 'nil';
}
if (s('offer')) {
$offer = $_GET["offer"];
} else {
$offer = 'nil';
}
if (s('session')) {
$session = $_GET["session"];
} else {
$session = 'nil';
}
if (s('payout')) {
$payout = $_GET["payout"];
} else {
$payout = 'nil';
}
function s($name) {
if(isset($_GET["$name"]) && !empty($_GET["$name"])) {
return true;
}
return false;
}
Use extract: http://php.net/manual/de/function.extract.php
// Assuming $_GET = array('id' => 123, etc.)
extract($_GET);
var_dump($id);
// And later in your code
if (isset($id)) {
// Do what you need
}
maybe you can use a universal wrapper
<?php
function getValue($key, $fallback='nil') {
if(isset($_GET[$key]) $val = trim($_GET[$key]);
else $val = null;
return ($val) ? $val : $fallback;
}
and then you can handle it easyer by
<?php
$id = getValue('id'); ...
isset is not needed, and maybe you can use the ternary operator.
$id = !empty($_GET["id"]) ? $_GET["id"] : null;
$offer = !empty($_GET["offer"]) ? $_GET["offer"] : null;
$session = !empty($_GET["session"]) ? $_GET["session"] : null;
$payout = !empty($_GET["payout"]) ? $_GET["payout"] : null;
i watching tutorial about developing guestbook with php
this is the code that get the message with the id
public function GetMessage($id)
{
//Database
$id = (int)$id;
$gb_host = 'localhost' ;
$gb_dbname = 'guestbook' ;
$gb_username = 'root';
$gb_password = '' ;
$connection = mysqli_connect($gb_host , $gb_username , $gb_password,$gb_dbname);
$querycheck = mysqli_query($connection,"SELECT * FROM `messages` WHERE `id` = $id");
if($querycheck)
{
$message = mysqli_fetch_assoc($querycheck);
return $message;
}
else
{
mysqli_close($connection);
return NULL;
}
mysqli_close($connection);
}
why in else statment we return NULL instead of False
what's the difference between Null and False ?
The type.
False is boolean and null is a value.
So :
$test = false;
if($test === false) {
//correct
}
$test = null;
if ($test === false) {
//incorrect
} else if ($test === null) {
//correct
}
$test = false;
if(!$test) {
//correct
}
$test = null;
if(!$test) {
//correct
}
More precision in the documentation
Imho in this case and null and false are incorrect, because method should return one type of data!
In our method it should be array not special type (null) or boolean,
and it will be easy to use this method elsewhere, because everytime we know that we works with array, and we don't have write something like this:
$messages = $dao->GetMessage(27);
if (is_array($messages)) {
// ...
}
if (is_null($messages)) {
$messages = []; // because wihout it foreach will down
}
foreach ($messages as $message) {
// ...
}
And as for me it's pretty straightforward:
if we have data at db we'll receive not empty array,
if we don't have data at db - we'll receive empty array.
It's obviously!
I am trying to GET different rows from different columns in php/mysql, and pack them into an array. I am able to successfully GET a jason encoded array back IF all values in the GET string match. However, if there is no match, the code echos 'no match', and without the array. I know this is because of the way my code is formatted. What I would like help figuring out, is how to format my code so that it just displays "null" in the array for the match it couldn't find.
Here is my code:
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode($fbaddra);
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['addr'];
} else {
$fbaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['addr'];
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
UPDATE: The GET Request
I would like the GET request below to return the full array, with whatever value that didn't match as 'null' inside the array.
domain.com/api/core/engine.php?a=fbaddra&facebook=username&facebookp=pagename
The GET above currently returns null.
Requests that work:
domain.com/api/core/engine.php?a=fbaddra&facebook=username or domain.com/api/core/engine.php?a=fbaddra&facebookp=pagename
These requests return the full array with the values that match, or null for the values that don't.
TL;DR
I need assistance figuring out how to format code to give back the full array with a value of 'null' for no match found in a row.
rather than assigning as 'null' assign null. Your full code as follows :
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode('no match');
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
You can even leave else part altogether.
Check your code in this fragment you not use same names for variables:
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = 'null';
}
$fbaddr not is same as $fpaddr, this assign wrong result to if statement.
It was the mysql query that was the problem.
For those who come across this, and need something similar, you'll need to format your query like this:
** MYSQL QUERY **
if ($_GET['PUTVALUEHERE']) {
$g = $_GET['PUTVALUEHERE'];
$gq = $mysqli->real_escape_string($g);
$q1 = "SELECT * FROM `addrbook` WHERE `facebookp` = '".$gq."' OR `facebook` = '".$gq."'";
}
** PHP CODE **
if($_GET['PUTVALUEHERE']{
echo json_encode($row['addr']);
}