Reputation: 487
I have the following code to count the number of rows in a database and to return the result to a user:
// Connect to database and select
$mysqli = mysqli_connect($config['db_hostname'], $config['db_username'], $config['db_password'], $config['db_name']);
$mysqli->set_charset('utf8');
$select = 'SELECT COUNT(*) AS wines FROM ft_form_4 WHERE feu_id = "'.$feuid.'"';
$response = mysqli_query($mysqli, $select) or die("Error: ".mysqli_error($mysqli));
$result = mysqli_fetch_array($response, MYSQLI_ASSOC);
$wines = (int)$result[wines];
echo $wines;
// Return 0 for no entries
if ($wines = 0) {
echo 'You currently have no wines entered, your current total entry fee is <strong>£0</strong>.';
}
elseif ($wines = 1) {
echo 'You currently have 1 wine entered, your current total entry fee is <strong>£135</strong>.';
}
elseif ($wines > 1) {
$fee = $wines * 135;
echo 'You currently have '.$wines.' wines entered, your current total entry fee is <strong>'.$fee.'</strong>.';
}
When I run the code, the result is echoed as 3 in the first bit (which I have just put in for testing) which is correct, but it always displays the second line, saying there is one wine entered and the entry fee is £135. It doesn't seem to recognise the 3 as a number.
I have tried a second lot of code using mysqli_num_rows, but I'm not having any luck with that either.
Upvotes: 1
Views: 116
Reputation: 111
Maybe a smarter approach?
$fee = $wines * 135;
echo 'You currently have '.($wines > 0 ? $wines : 'no').' wine'.($wines != 1 ? 's' : '').' entered, your current total entry fee is <strong>£'.$fee.'</strong>.';
Explained:
($wines > 0 ? $wines : 'no')
What we do, inside the parentheses, is that we evaluate the first part:
$wines > 0
If that is true, the value after the '?' (if) will be output, if false the value after ':' (else) will be output.
Same goes, finding out whether or not to echo the s in wine*s*:
($wines != 1 ? 's' : '')
If $wines == 1 we don't echo the s in wine*s*:
Upvotes: 1
Reputation: 1043
The comparison is wrong, you should use ==
instead of =
Upvotes: 0
Reputation: 7475
Use "==" instead of "="
if ($wines == 1) {
As, ==
is comparison operator and a single =
will just assign the value 1
to $wines
.
Upvotes: 0
Reputation: 111
You need to use the '==' comparator
// Return 0 for no entries
if ($wines == 0) {
echo 'You currently have no wines entered, your current total entry fee is <strong>£0</strong>.';
}
elseif ($wines == 1) {
echo 'You currently have 1 wine entered, your current total entry fee is <strong>£135</strong>.';
}
elseif ($wines > 1) {
$fee = $wines * 135;
echo 'You currently have '.$wines[0].' wines entered, your current total entry fee is <strong>'.$fee.'</strong>.';
}
Upvotes: 0
Reputation: 1446
elseif ($wines = 1) {
will always be true as you are assigning the value 1 to $wines, try:
elseif ($wines == 1) {
Upvotes: 0