Writing a PHP if Blank statement - variables

I'm new to PHP so this will sound basic to most people but I need to write the code for when a variable returns nothing (blank).
My variable is $winner, but sometimes there is no winner, in this case it just leaves the page blank, I would like it so if there is no winner then it will display "no winner".
This is my attempt:
if empty($winner) {
echo "no winner";
}

You can make a function to check the variable's valaue with null or empty...
function IsEmptyString($Season){
return (!isset($Season) || trim($Season)==='');
}
This function can be used to check the same.

Just use:
if (!$winner) { // will catch "", null
echo "no winner"
}

Related

How to check if boolean false

I am new to java.. Please help me for the below
I need to print "Authentication failed" when Boolean is false. But the below code is displaying both Success & Failed messages even authentication is successful.
*
switch(choice){
case 1:
System.out.println("Enter the username");
String name = scan.nextLine();
System.out.println("Enter the password");
String password = scan.nextLine();
Boolean result = true;
for(Account a :accountArray )
{
result = a.authentication(name, password);
if(result)
{
System.out.println("Authentication successful");
}
else
{
result=false;
}
}
if(!result)
{
System.out.println("Authentication failed");
}
break;
*
Current Output:
Enter the username
vicky
Enter the password
vicky123
Authentication successful
Authentication failed
It would seem from the output you show, you have more than one Account in accountArray, and what is happening is that one of the accounts in the array matches, but the last one does not. So as you loop over accountArray, it sets result according to that account. One of the accounts in the array succeeds (you print "Authentication successful" once), and the last one does not match. After the loop you print "Authetication failed", as that last check set result to false.
Probably what you want it to put a break; after printing "Authentication successful" -- once you find an account that matches, you're done and don't want to look at any of the later accounts in the vector. But as you never say what you are actually trying to do, it is hard to say.
In addition, the else clause in the loop is redundant -- it runs if result is false, so setting it to false again is pointless. Your code will also leave result as true if the accountArray is empty, and not print any message; that may or may not be sensible.

Else without If error... and I don't know why

The code below is action taken when a button is clicked on a simple form. The problem comes with the one if/else block. The If line is not terminated. The Else line is not terminated. But I have a consistent error that my Else exists without an If. I can't see why. I need someone smarter than me to identify what is going on here.
Thank you in advance!
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
FileFilter filter;
filter = new FileNameExtensionFilter("Comma Separated Value files","csv","txt");
JFileChooser chooser;
chooser = new JFileChooser();
chooser.addChoosableFileFilter(filter);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int showDialog = chooser.showDialog(this, null);
File selectedFile = chooser.getSelectedFile();
String filename;
filename = selectedFile.getAbsolutePath();
if (filter.accept(selectedFile))
{
jTextField2.setText(filename);
jTextField2.setBackground(Color.white);
else
jTextField2.setText("You Did NOT Select a CSV File.");
jTextField2.setForeground(Color.black);
jTextField2.setBackground(Color.red);
}
}
You are missing the bracket '}' after "jTextField2.setBackground(Color.white);" and else.code is here
if (filter.accept(selectedFile))
{
jTextField2.setText(filename);
jTextField2.setBackground(Color.white);
}
else
{
jTextField2.setText("You Did NOT Select a CSV File.");
jTextField2.setForeground(Color.black);
jTextField2.setBackground(Color.red);
}
The SYNTAX for if-else Block looks like this:-
if {
// statements
} else {
//statements
}
Now if you are having only ONE statement inside the if Or else part then you can afford to skip the curly braces{ } otherwise you surely need to put those curly braces as compiler looks for it can terminate the execution of if statement.
However, it is always recommended to use the braces even if u have only ONE statement inside the if or else part as it improves the readability of the code.
You need to close your "if" and "else" blocks.
Example: if {} else {}.
if (filter.accept(selectedFile)) {
jTextField2.setText(filename);
jTextField2.setBackground(Color.white);
} else {
jTextField2.setText("You Did NOT Select a CSV File.");
jTextField2.setForeground(Color.black);
jTextField2.setBackground(Color.red);
}
The if's closing bracket is missing just before the else.

NHibernate Criteria Filtering

I use this code to filter database records
if (!string.IsNullOrEmpty(_searchCriteria.MessageType))
{
var messageType = (AutotransferMessageType)Enum.Parse(typeof(AutotransferMessageType), _searchCriteria.MessageType, true);
if (Enum.IsDefined(typeof(AutotransferMessageType), messageType))
{
criteriaQuery.CreateAlias("AutotransferInputRecord", "AutotransferInputRecord")
.Add(
Restrictions.Eq(
"AutotransferInputRecord." + AutotransferLogSearchCriteria.MessageTypePropertyName,
messageType));
}
else
{
criteriaQuery.Add(Restrictions.IsNull("AutotransferInputRecord"));
}
}
AutotransferMessageType is enumerable type
public enum AutotransferMessageType
{
[DisplayName("MT202")]
[DatabaseName("MT202")]
MT202,
[DisplayName("MT210")]
[DatabaseName("MT210")]
MT210,
//...
}
My filter outputs the results when I enter MT202, for example. (It's the right behavior).
When I input just number, for example, 202, I get no results (It's the right behavior too).
But when I try to input some line, "mt", for example, I get error
Unexpected application error has been occured:
'Requested value 'mt' was not found.'
How to make the filter do not show any results when I input a line?
Your error is coming from the line that parses the enum. Use Enum.TryParse instead:
AutotransferMessageType msgEnum;
var enumPrasedOk = Enum.TryParse(_searchCriteria.MessageType, true, out msgEnum);
if(enumPrasedOk){
//Do something
}else{
//Handle case where enum was not found for some reason (if need be)
}
Also please note that you can not look up the enum this way using it's description (in your case they are the same so it is ok).

PDO login script won't work

I changed this login script to PDO. Now it passes the username but get's stuck fetchAll line. I need help please. thanks
<?php
session_start();
include_once"includes/config.php";
if (isset($_POST['admin_login'])) {
$admin_user = trim($_POST['admin_user']);
$admin_pw = trim($_POST['admin_pw']);
if ($admin_user == NULL OR $admin_pw == NULL) {
$final_report.="Please complete all the fields below..";
} else {
$check_user_data = $db->prepare("SELECT * FROM `admin`
WHERE `admin_user`='$admin_user'");
$check_user_data->execute();
if ($check_user_data->fetchColumn() == 0) {
$final_report.="This admin username does not exist..";
} else {
$get_user_data = $check_user_data->fetchAll($check_user_data);
if ($get_user_data['admin_pw'] == $admin_pw) {
$start_idsess = $_SESSION['admin_user'] = "".$get_user_data['admin_user']."";
$start_passsess = $_SESSION['admin_pw'] = "".$get_user_data['admin_pw']."";
$final_report.="You are about to be logged in, please wait a few moments...";
header('Location: admin.php');
}
}
}
}
?>
Not checking return value prepare() or execute() for false. You need to check for SQL errors and handle them, stopping the code instead of continuing on blithely.
Not using query parameters in the prepared statement, still interpolating $_POST content into the query unsafely. You're missing the benefit of switching to PDO, and leaving yourself vulnerable to SQL injection attack.
You're storing passwords in plaintext, which is unsafe. See You're Probably Storing Passwords Incorrectly.
Do you really need to SELECT * if you only use the admin_pw column? Hint: no.
PDOStatement::fetchAll() returns an array of arrays, not just one array for a row. Read the examples in the documentation for fetchAll().

Powershell and SQL parameters. If empty string, pass DBNull

I got this parameter:
$objDbCmd.Parameters.Add("#telephone", [System.Data.SqlDbType]::VarChar, 18) | Out-Null;
$objDbCmd.Parameters["#telephone"].Value = $objUser.Telephone;
Where the string $objUser.Telephone can be empty. If it's empty, how can I convert it to [DBNull]::Value?
I tried:
if ([string]:IsNullOrEmpty($objUser.Telephone)) { $objUser.Telephone = [DBNull]::Value };
But that gives me the error:
Exception calling "ExecuteNonQuery" with "0" argument(s): "Failed to convert parameter value from a ResultPropertyValueCollection to a String."
And if I convert it to a string, it inserts an empty string "", and not DBNull.
How can this be accomplished?
Thanks.
In PowerShell, you can treat null/empty strings as a boolean.
$x = $null
if ($x) { 'this wont print' }
$x = ""
if ($x) { 'this wont print' }
$x = "blah"
if ($x) { 'this will' }
So.... having said that you can do:
$Parameter.Value = $(if ($x) { $x } else { [DBNull]::Value })
But I'd much rather wrap this up in a function like:
function CatchNull([String]$x) {
if ($x) { $x } else { [DBNull]::Value }
}
I don't know about powershell, but in C# I would do something like this:
if ([string]::IsNullOrEmpty($objUser.Telephone))
{
$objDbCmd.Parameters["#telephone"].Value = [DBNull]::Value;
}
else
{
$objDbCmd.Parameters["#telephone"].Value = $objUser.Telephone;
}
Always append +"" at the end of db values...
$command.Parameters["#EmployeeType"].Value= $ADResult.EmployeeType + ""
Many years later, let me clarify:
Josh's answer shows a helpful simplification for testing strings for emptiness (relying on PowerShell's implicit to-Boolean conversion[1]), but it is unrelated to Tommy's (the OP's) problem.
Instead, the error message
"Failed to convert parameter value from a ResultPropertyValueCollection to a String."
implies that it is the non-null case that caused the problem, because $objDbCmd.Parameters["#telephone"].Value expects either a string value or [DBNull]::Value, whereas $objUser.Telephone is of type [ResultPropertyValueCollection], i.e. a collection of values.
Thus, in the non-null case, a string value must be assigned, which must be derived from the collection; one option is to take the first collection element's value, another would be to join all values with a separator to form a single string, using, e.g., [string]::Join(';', $objUser.Telephone) or, if joining the elements with spaces is acceptable (not a good idea with multiple phone numbers), simply with "$($objUser.Telephone)".[2]
Detecting an empty collection via [string]:IsNullOrEmpty() actually worked, despite the type mismatch, due to how PowerShell implicitly stringifies collections when passing a value to a [string] typed method parameter.[2]
Similarly, using implicit to-Boolean conversion works as expected with collections too: an empty collection evaluates to $false, a non-empty one to $true (as long as there are either at least two elements or the only element by itself would be considered $true[1])
Therefore, one solution is to use the first telephone number entry:
$objDbCmd.Parameters["#telephone"].Value = if ($objUser.Telephone) {
$objUser.Telephone[0].ToString() # use first entry
} else {
[DBNull]::Value
}
Note: If $objUser.Telephone[0] directly returns a [string], you can omit the .ToString() call.
In PowerShell v7+ you can alternatively shorten the statement via a ternary conditional:
$objDbCmd.Parameters["#telephone"].Value =
$objUser.Telephone ? $objUser.Telephone[0].ToString() : [DBNull]::Value
[1] For a comprehensive summary of PowerShell's automatic to-Boolean conversions, see the bottom section of this answer.
[2] When implicitly converting a collection to a string, PowerShell joins the stringified elements of a collection with a single space as the separator by default; you can override the separator with the automatic $OFS variable, but that is rarely done in practice; e.g., array 'foo', 'bar' is converted to 'foo bar'; note that this conversion does not apply when you call the collection's .ToString() method explicitly, but it does apply inside expandable (interpolating) strings, e.g., "$array".