(sorry for my bad English writing). I've got a problem where I'm stuck with an if and else system that returns the level that you're.
Everything is good, if you have 20 clicks it will tell you that you're level 2, if you have 550 clicks it will tell you're level 6. But when you go up to 1500 clicks it needs to say level 9, but it will still say level 8.
My code:
$levelown = 'Level 1';
function ifElse() {
global $levelown;
global $arrayIP;
if($arrayIP['clicks'] >= 0 && $arrayIP['clicks'] <= 49)
{
$levelown = 'Level 2';
}
/* .... More if and elses with levels */
// This is the problem, this will keep telling me that I'm level 8.
elseif($arrayIP['clicks']>=3000)
{
$levelown = 'Level ' . floor(($score['clicks']/1000)+8);
}
and you are <strong><?php echo $levelown; ?></strong>
Thank you for helping!
The problem that i saw from your current code is that you have
elseif($arrayIP['clicks']>=3000)
{
$levelown = 'Level ' . floor(($score['clicks']/1000)+8);
}
which i think should be
elseif($arrayIP['clicks']>=3000)
{
$levelown = 'Level ' . floor(($arrayIP['clicks']/1000)+8);
}
since $score['clicks'] isn't present you will always end up with level 8
It's probably easier and more readable to make it a switch/case statement like so:
$highscore = $mysqli->query("SELECT id,name,clicks,ip,factory FROM highscore ORDER BY clicks DESC LIMIT 0,50 ");
$ipquery = $mysqli->query("SELECT id,name,clicks,ip,factory FROM highscore WHERE ip = '".$_SERVER['REMOTE_ADDR']."'");
$arrayIP = $ipquery->fetch_array();
$levelown = 1;
function ifElse() {
global $levelown;
global $arrayIP;
switch (true) {
case $arrayIP['click'] > 3000:
$levelown = floor(($arrayIP['click']/1000)+8);
break;
case $arrayIP['click']== 3000:
$levelown = 11;
break;
case $arrayIP['click'] >= 2000:
$levelown = 10;
break;
case $arrayIP['click'] >= 1500:
$levelown = 9;
break;
case $arrayIP['click'] >= 1000:
$levelown = 8;
break;
case $arrayIP['click'] >= 750:
$levelown = 7;
break;
case $arrayIP['click'] >= 500:
$levelown = 6;
break;
case $arrayIP['click'] >= 350:
$levelown = 5;
break;
case $arrayIP['click'] >= 200:
$levelown = 4;
break;
case $arrayIP['click'] >= 50:
$levelown = 3;
break;
case $arrayIP['click'] >= 0:
$levelown = 2;
break;
}
$levelown = "Level " . $levelown;
}
Related
I need to change the value of a text field (Agerisk2) to a number based on the selection of a radio field (Age)
In the text field additional attributes I have
onChange="$Agerisk2"
In the text field default value I have:
//<code>
$Age = [];
$Agerisk2 = null;
switch ($Age) {
case $Age "Under 45 years":
$Agerisk2 = "0";
break;
case $Age "45 – 54 years":
$Agerisk2 = "2";
break;
case $Age "55 – 64 years":
$Agerisk2 = "3";
break;
case $Age "64 years or over":
$Agerisk2 = "4";
break;
default:
$Agerisk2 = null;
break;
}
//</code>
Something isn't quite right and I'd really appreciate some help. Thank you
Your switch statement is invalid. Better use match for it.
Also note your variable naming should match the PSR
$age = 47;
$ageRisk = match (true) {
$age < 45 => 0,
$age >= 45 && $age <= 54 => 2,
$age >= 55 && $age <= 64 => 3,
$age >= 64 => 4,
default => null
};
echo $ageRisk;
prints
2
If you are below PHP 8 you can fallback to switch, which does not look so nice.
switch (true) {
case $age < 45:
$ageRisk = 0;
break;
case $age >= 45 && $age <= 54:
$ageRisk = 2;
break;
case $age >= 55 && $age <= 64:
$ageRisk = 3;
break;
case $age >= 64:
$ageRisk = 4;
break;
default:
$ageRisk = null;
break;
}
i am trying to create dynamic price calculation by distance.My requirment similar like this
so I need a function where I can pass
distance and then get price by distance
From 0 -10km = Rs10rs/km (fixed price)
10-15km = rs10Rs/km
15 -20km = 9rs pre/km
20 -30km = 8.5rs per/km
25 -30km = 8rs per/km
30 -40km = 7.5rs per/km
30km -50km above = 7rs / km
foreach ($usersInfo as $index=> $users)
{
$km= 0;
$ridefrom=$users['ride_from'];
$rideto=$users['ride_to'];//this is from lat long
$tempLatLong = explode(',',$users['ride_from']);
$tempLatLong1 = explode(',',$users['ride_to']);
$key = array('lat','long');
$to = array_combine($key,$tempLatLong);
$from = array_combine($key,$tempLatLong1);
$km=distanceCalculation($from['lat'],$from['long'],$to['lat'],$to['long']).'km';
$usersInfo[$index]['distance'] =$km;
$carprice=10;// price will be change dynamical from back end admin can change this.
if($carprice){
$price=$km*10;
}
else{
$price=$km*9;
}
$usersInfo[$index]['price'] =$price;
return $usersInfo;
}
Try something like this:
function price_per_km($distance, $mode) {
if ($mode == 'car') {
switch (true) {
case $distance <= 10:
return 10*$distance;
case $distance <= 15:
return 10*$distance;
case $distance <= 20:
return 9*$distance;
case $distance <= 25:
return 8.5*$distance;
case $distance <= 30:
return 8*$distance;
case $distance <= 40:
return 7.5*$distance;
default:
return 7*$distance;
}
}
else {
// bike
switch (true) {
case $distance <= 10:
return 12*$distance;
case $distance <= 15:
return 11*$distance;
case $distance <= 20:
return 10*$distance;
case $distance <= 25:
return 9*$distance;
default:
return 8*$distance;
}
}
}
echo price_per_km(5, 'car') . "\n";
echo price_per_km(12, 'car') . "\n";
echo price_per_km(25, 'car') . "\n";
echo price_per_km(35, 'car') . "\n";
echo price_per_km(5, 'bike') . "\n";
echo price_per_km(15, 'bike') . "\n";
echo price_per_km(35, 'bike') . "\n";
Output:
50
120
212.5
227.5
60
165
270
I need a little helping hand in my script. As the title suggests it's about parameters. I have this code:
if (isset($_GET['sendit'])) {
$theusersname = $_GET['theusersname'];
$totalmarks = $_GET['totalmarks'];
$mathsobt = $_GET['mathsobt'];
$physicsobt = $_GET['physicsobt'];
$chemistryobt = $_GET['chemistryobt'];
$computerobt = $_GET['computerobt'];
$englishobt = $_GET['englishobt'];
$totalobt = $mathsobt + $physicsobt + $chemistryobt + $computerobt + $englishobt;
$modulo = ($totalobt / $totalmarks) * 100;
$grade = "";
//for grades
switch ($modulo, $grade) {
case 'A-1'://100% ro 80%
if ($modulo >= 79.5 && $modulo <= 100){
$grade = "A-1";
}
break;
case 'A'://79% to 70%
if ($modulo >= 69.5 && $modulo <= 79.4) {
$grade = "A";
}
break;
case 'B'://69 to 60
if ($modulo >= 59.5 && $modulo <= 69.4){
$grade = "B";
}
break;
case 'C'://59 to 50
if ($modulo >= 49.5 && $modulo <= 59.4){
$grade = "C";
}
break;
case 'D'://49 to 40
if ($modulo >= 39.5 && $modulo <= 49.4){
$grade = "D";
}
break;
case 'F'://32 to rest
if ($modulo >= 33 && $modulo <= 39.4){
$grade = "F";
}
default:
if ($modulo >= 0 && $modulo <= 32.9){
$grade = "N/A";
}
break;
}
//for remarks
switch ($grade) {
case '':
break;
default:
break;
}
$query = "INSERT INTO `report`(`name`, `grade`, `total`, `mathsobt`, `physicsobt`, `chemistryobt`, `computerobt`, `englishobt`, `totalobt`, `modulo`, `remarks`) VALUES ('$theusersname', '$grade', '$totalmarks', '$mathsobt', '$physicsobt', '$chemistryobt', '$computerobt', '$englishobt', '$totalobt', '$modulo', '$remarks')";
$result = mysqli_query($mysqliConn, $query);
// if (mysqli_query($mysqliConn, $query)) {
// echo "New record created successfully";
// } else {
// echo "Error: " . $query . "<br>" . mysqli_error($mysqliConn);
$mysqliConn->close();
// }
The grading switch statement doesn't work. Because I just can't get what parameter I need to give. Same goes for the remarks too. The code may be terrible and don't have sanitization (which in this case I don't need). I'm also a little bit confuse with the strings I passed for cases. I mean does it have an effect on overall?
Thank you.
PS: If there is already a similar answer out there, which i unfortunately i didn't find, i'm ready to view the link. Please post a little explanatory comment.
$modulo && $grade is a boolean expression. Its value is either TRUE or FALSE (and not 'A', 'B' or 'C').
But PHP is a loose-type language and it changes the types of its values as needed before using them. Because of this, 'A' == TRUE and '' == FALSE and your code produces only 'A-1' and 'N/A' grades.
A switch doesn't help here. You should use a sequence of cascaded ifs:
if ($modulo >= 79.5) {
$grade = "A-1";
} elseif ($modulo >= 69.5) {
$grade = "A";
} elseif ($modulo >= 59.5) {
$grade = "B";
} elseif ($modulo >= 49.5) {
$grade = "C";
} elseif ($modulo >= 39.5) {
$grade = "D";
} elseif ($modulo >= 33) {
$grade = "F";
} else {
$grade = "N/A";
}
Read how PHP compare values of different types and read how the switch control structure works.
Here you go
$theusersname = 'theusersname';
$totalmarks = 500;
$mathsobt = 87;
$physicsobt = 82;
$chemistryobt = 75;
$computerobt = 79;
$englishobt = 91;
$totalobt = $mathsobt + $physicsobt + $chemistryobt + $computerobt + $englishobt;
$modulo = ($totalobt / $totalmarks) * 100;
switch ($modulo) {
case $modulo >= 33 && $modulo < 39.5:
$grade = "F";
break;
case $modulo >= 39.5 && $modulo < 49.5:
$grade = "D";
break;
case $modulo >= 49.5 && $modulo < 59.5:
$grade = "C";
break;
case $modulo >= 59.5 && $modulo < 69.5:
$grade = "B";
break;
case $modulo >= 69.5 && $modulo < 79.5:
$grade = "A";
break;
case ($modulo >= 79.5 && $modulo <= 100 ):
$grade = "A-1";
break;
default:
$grade = "N/A";
break;
}
switch ($grade) {
case 'A-1':
$remarks = "You have got A-1 ";
break;
case 'A':
$remarks = "You have got A ";
break;
case 'B':
$remarks = "You have got B ";
break;
case 'C':
$remarks = "You have got C ";
break;
case 'D':
$remarks = "You have got D ";
break;
case 'F':
$remarks = "You have got F ";
break;
default:
$remarks = "You have got nothing";
break;
}
echo $query = "INSERT INTO `report`
(`name`, `grade`, `total`, `mathsobt`, `physicsobt`,
`chemistryobt`, `computerobt`, `englishobt`, `totalobt`,
`modulo`, `remarks`)
VALUES ('$theusersname', '$grade', '$totalmarks', '$mathsobt',
'$physicsobt', '$chemistryobt', '$computerobt', '$englishobt',
'$totalobt', '$modulo', '$remarks')";
OUTPUT
INSERT INTO `report`
(`name`, `grade`, `total`, `mathsobt`, `physicsobt`,
`chemistryobt`, `computerobt`, `englishobt`, `totalobt`,
`modulo`, `remarks`)
VALUES ('theusersname', 'A-1', '500', '87', '82', '75', '79',
'91', '414', '82.8', 'You have got A-1 ')
Before I save my model, I would like to check if $ CONT_CEDULA meets the requirements. If not, then don't save. But when saving, it is as if the variable $ CONT_CEDULA hasn't got any data. I want to know if I'm doing well or need some other event or function. Also, the echo outputs no data.
beforeSave method
public function beforeSave() {
echo $this->$CONT_CEDULA;
switch (strlen($this->$CONT_CEDULA)) {
case 10:
return validarCI($this->$CONT_CEDULA);
break;
case 13:
return validarRUC($this->$CONT_CEDULA);
break;
default:
echo "Numero de caracteres invalidos" ;
return FALSE;
}
SpmContacto model
<?php
class SpmContacto extends \Phalcon\Mvc\Model {
public $CONT_CODIGO;
public $CONT_CEDULA;
public $CONT_RUCIDE;
public $CONT_NOMBRE;
public $CON_ESTADO;
public $CONT_TELEFO;
public $CONT_DIRECC;
public $CONT_AREA;
public $CONT_CARGO;
public $CONT_TIPOXX;
public $CONT_EMAIL;
public $CONT_USUARIO;
public $CONT_CLAVE;
public $CONT_CLAVEE;
public $CONT_FECNACI;
public $CONT_FECINSC;
public $CONT_TIPOCODIGO;
/**
* Initialize method for model.
*/
public function initialize() {
$this->setSchema("SPOLS");
$this->hasMany('CONT_CODIGO', 'SPMREFERENCIA', 'CONT_CODIGO', array('alias' => 'SPMREFERENCIA'));
$this->hasMany('CONT_CODIGO', 'SPTDETALLE', 'CONT_CODIGO', array('alias' => 'SPTDETALLE'));
$this->hasMany('CONT_CODIGO', 'SPTENCABEZADO', 'CONT_CODIGO', array('alias' => 'SPTENCABEZADO'));
}
function validarCI($strCedula) {
$suma = 0;
$strOriginal = $strCedula;
$intProvincia = substr($strCedula, 0, 2);
$intTercero = $strCedula[2];
$intUltimo = $strCedula[9];
if (!settype($strCedula, "float"))
return FALSE;
if ((int) $intProvincia < 1 || (int) $intProvincia > 23)
return FALSE;
if ((int) $intTercero == 7 || (int) $intTercero == 8)
return FALSE;
for ($indice = 0; $indice < 9; $indice++) {
//echo $strOriginal[$indice],'</br>';
switch ($indice) {
case 0:
case 2:
case 4:
case 6:
case 8:
$arrProducto[$indice] = $strOriginal[$indice] * 2;
if ($arrProducto[$indice] >= 10)
$arrProducto[$indice] -= 9;
//echo $arrProducto[$indice],'</br>';
break;
case 1:
case 3:
case 5:
case 7:
$arrProducto[$indice] = $strOriginal[$indice] * 1;
if ($arrProducto[$indice] >= 10)
$arrProducto[$indice] -= 9;
//echo $arrProducto[$indice],'</br>';
break;
}
}
foreach ($arrProducto as $indice => $producto)
$suma += $producto;
$residuo = $suma % 10;
$intVerificador = $residuo == 0 ? 0 : 10 - $residuo;
return ($intVerificador == $intUltimo ? TRUE : FALSE);
}
function validarRUC($strRUC) {
if (strlen($strRUC) != 13)
return FALSE;
$suma = 0;
$strOriginal = $strRUC;
$intProvincia = substr($strRUC, 0, 2);
$intTercero = $strRUC[2];
if (!settype($strRUC, "float"))
return FALSE;
if ((int) $intProvincia < 1 || (int) $intProvincia > 23)
return FALSE;
if ((int) $intTercero != 6 && (int) $intTercero != 9) {
if (substr($strRUC, 10, 3) == '001')
return validarCI(substr($strRUC, 0, 10));
return FALSE;
}
if ((int) $intTercero == 6) {
$intUltimo = $strOriginal[8];
for ($indice = 0; $indice < 9; $indice++) {
//echo $strOriginal[$indice],'</br>';
switch ($indice) {
case 0:
$arrProducto[$indice] = $strOriginal[$indice] * 3;
break;
case 1:
$arrProducto[$indice] = $strOriginal[$indice] * 2;
break;
case 2:
$arrProducto[$indice] = $strOriginal[$indice] * 7;
break;
case 3:
$arrProducto[$indice] = $strOriginal[$indice] * 6;
break;
case 4:
$arrProducto[$indice] = $strOriginal[$indice] * 5;
break;
case 5:
$arrProducto[$indice] = $strOriginal[$indice] * 4;
break;
case 6:
$arrProducto[$indice] = $strOriginal[$indice] * 3;
break;
case 7:
$arrProducto[$indice] = $strOriginal[$indice] * 2;
break;
case 8:
$arrProducto[$indice] = 0;
break;
}
}
} else {
$intUltimo = $strOriginal[9];
for ($indice = 0; $indice < 9; $indice++) {
//echo $strOriginal[$indice],'</br>';
switch ($indice) {
case 0:
$arrProducto[$indice] = $strOriginal[$indice] * 4;
break;
case 1:
$arrProducto[$indice] = $strOriginal[$indice] * 3;
break;
case 2:
$arrProducto[$indice] = $strOriginal[$indice] * 2;
break;
case 3:
$arrProducto[$indice] = $strOriginal[$indice] * 7;
break;
case 4:
$arrProducto[$indice] = $strOriginal[$indice] * 6;
break;
case 5:
$arrProducto[$indice] = $strOriginal[$indice] * 5;
break;
case 6:
$arrProducto[$indice] = $strOriginal[$indice] * 4;
break;
case 7:
$arrProducto[$indice] = $strOriginal[$indice] * 3;
break;
case 8:
$arrProducto[$indice] = $strOriginal[$indice] * 2;
break;
}
}
}
foreach ($arrProducto as $indice => $producto)
$suma += $producto;
$residuo = $suma % 11;
$intVerificador = $residuo == 0 ? 0 : 11 - $residuo;
//echo "$intVerificador == $intUltimo";
return ($intVerificador == $intUltimo ? TRUE : FALSE);
}
function validarID($strId) {
switch (strlen($strId)) {
case 10:
return validarCI($strId);
break;
case 13:
return validarRUC($strId);
break;
default:
return FALSE;
}
}
public function beforeSave() {
echo $this->$CONT_CEDULA;
switch (strlen($this->$CONT_CEDULA)) {
case 10:
return validarCI($this->$CONT_CEDULA);
break;
case 13:
return validarRUC($this->$CONT_CEDULA);
break;
default:
echo "Numero de caracteres invalidos";
return FALSE;
}
//echo $op;
}
public function getSource() {
return 'SPM_CONTACTO';
}
public static function find($parameters = null) {
return parent::find($parameters);
}
public static function findFirst($parameters = null) {
return parent::findFirst($parameters);
}
By default Phalcon wont output any data you "echo" in your controllers or your models. The easy 'workaround' is to die('your output');
If you return a value in a switch, it is unnecessary to add a break; to the end of your case.
public function beforeSave()
{
// check the content of $this->$CONT_CEDULA
var_dump($this->$CONT_CEDULA);
die;
switch (strlen($this->$CONT_CEDULA)) {
case 10:
return validarCI($this->$CONT_CEDULA);
case 13:
return validarRUC($this->$CONT_CEDULA);
default:
// an example to test if your code enters this case.
die("Numero de caracteres invalidos");
return FALSE;
}
}
I am having a small problem with my PHP MySQL Select. The function is inside of a PHP class. Here is the error I get:
Warning: mysql_fetch_array() expects parameter 1 to be resource,
integer given in C:\xampp\htdocs\include\database.php on line 59
Warning: extract() expects parameter 1 to be array, null given in
C:\xampp\htdocs\include\database.php on line 59
The function just simply updates the database to show what browser and OS they visited the site with. The function is called from another file that is called by an AJAX call that uses POST to send the data about the OS and browser that was gathered from a Javascript file. It only fails if there is an entry of the IP address already in the database. If there is no IP Address entry in the database it succeeds in creating one.
Here is my code:
function addStat($browser, $os){
$IE = 0; $Firefox = 0; $Safari = 0; $Opera = 0; $Chrome = 0; $otherb = 0;
$Windows = 0; $Linux = 0; $Mac = 0; $Android = 0; $iOS = 0; $otheros = 0;
$ql = 0; $totalVisits = 0;
$ip = ip2long($_SERVER['REMOTE_ADDR']);
$q1 = mysql_query("SELECT * FROM " . DB_STATS . " WHERE ip='$ip'", $this->connection);
if (mysql_num_rows($q1)==0){
$browser = mysql_real_escape_string($browser);
$os = mysql_real_escape_string($os);
switch($browser){
case "Internet Explorer":
$IE += 1;
break;
case "Firefox":
$Firefox += 1;
break;
case "Safari":
$Safari += 1;
break;
case "Opera":
$Opera += 1;
break;
case "Chrome":
$Chrome += 1;
break;
default:
$otherb += 1;
break;
}
switch($os){
case "Windows":
$Windows += 1;
break;
case "Mac OS X":
$Mac += 1;
break;
case "Linux":
$Linux += 1;
break;
case "Android":
$Android += 1;
break;
case "iOS":
$iOS += 1;
break;
default:
$otheros += 1;
break;
}
$q = $this->query("INSERT INTO " . DB_STATS . " VALUES (null, '$ip', '$Chrome', '$IE', '$Firefox', '$Opera', '$Safari', '$otherb', '$Windows', '$Mac', '$Linux', '$Android' , '$iOS' , '$otheros', 1)");
if ($q == true){
return(1);
}
else{
return(0);
}
}
else if (mysql_num_rows($q1)==1){
extract(mysql_fetch_array($ql));
switch($browser){
case "Internet Explorer":
$IE += 1;
break;
case "Firefox":
$Firefox += 1;
break;
case "Safari":
$Safari += 1;
break;
case "Opera":
$Opera += 1;
break;
case "Chrome":
$Chrome += 1;
break;
default:
$otherb += 1;
break;
}
switch($os){
case "Windows":
$Windows += 1;
break;
case "Mac OS X":
$Mac += 1;
break;
case "Linux":
$Linux += 1;
break;
case "Android":
$Android += 1;
break;
case "iOS":
$iOS += 1;
break;
default:
$otheros += 1;
break;
}
$totalVisits += 1;
$q = $this->query("UPDATE " . DB_STATS . " set Chrome='$Chrome', IE='$IE', Firefox='$Firefox', Opera='$Opera', Safari='$Safari', otherb='$otherb', Windows='$Windows', Mac='$Mac', Linux='$Linux', Android='$Android' , iOS='$iOS' , otheros='$otheros', totalVisits='$totalVisits'");
if ($q == true){
return(1);
}
else{
return(0);
}
}
else{
return(-1);
}
}
I hope everything made sense and that someone will help.
I see it now -- you used $ql (lower case L) when you intend to use $q1. Let this be a lesson against using very short variable names or very similar names.
// $ql was initialized to 0
$ql = 0; $totalVisits = 0;
// $q1 holds the result resource
extract(mysql_fetch_array($q1));
It is not advisable to call extract() on the output of mysql_fetch_array() unless you also specify the second parameter MYSQL_ASSOC as the fetch type. By default it returns both numeric and associative indices for each column.
extract(mysql_fetch_array($q1, MYSQL_ASSOC));
// Or better
extract(mysql_fetch_assoc($q1));
In general, I would probably advise against using extract() in most any situation, since it results in numerous variables dumped into the global namespace, in particular when you have done SELECT * without being specific about which columns are selected. Better to access them via their array:
$row = mysql_fetch_assoc($q1);
echo $row['browser'];