If condition not checking the condition - php

function pokemon2()
{
include 'details.php';
$damage = $_POST['attack'];
$oppo_health = $_SESSION['oppo_health'];
if($oppo_health < 0)
{
echo "Died!";
}
else
{
$oppo_path = $_SESSION['path'];
echo "<br />";
echo $oppo_path;
echo "<br />";
$oppo_health = $oppo_health - $damage;
echo $oppo_health;
$_SESSION['attack'] = $damage;
$_SESSION['oppo_health'] = $oppo_health;
}
}
The code should display 'Died' if the $oppo_health goes below 0!
But its not happening as it should?? The logic is correct and no errors shown.

You need to start a session by using session_start() method.

Related

Count the instances where a variable equals TRUE

Working on a quiz website where when users submits their answers $perQuestionScore equals true when the answer is correct but false when it is wrong. I'm trying to find the instances where $perQuestionScore equals true in other to total the score but it doesn't seem to work.
My code looks like below
<?php
$perQuestionScore = 0;
if (isset($_POST['grader'])) {
if(isset($_POST[$chosen]))
{
$choice= $_POST[$chosen];
if (strpos($choice, $correctOne) !== false) {
$perQuestionScore++;
echo $_POST[$chosen] . "" . " is the correct answer";
} elseif (strpos($choice, $correctOne) == false) { echo $_POST[$chosen] . "" . " is the Wrong answer";
} else {
echo "You did not choose an answer"; {
}
}
}
}
}
echo "<input id=grader' type='submit' name='grader' value='Grade Quiz'>" . "</form>";
echo $perQuestionScore * 10;
}
$conn->close();
?>
I suggest simplifying it to this:
<?php
$perQuestionScore = 0; //initialize var
if ($choice == $correct) {
$perQuestionScore++; //add 1 if correct
}
echo $perQuestionScore * 10; //i guess you want it times 10

isset method not working returns nothing

I am trying to map a collection of JSON files into a database but my isset check is not working in my PHP :
<?php
$con = mysqli_connect("localhost", "root", "", "json_map");
$response = array();
$res = array();
$result = '';
foreach(glob('C:\xampp\htdocs\laravel\awsconfig\app\views\*.json') as $filename)
{
$json = file_get_contents($filename);
if ($json != null)
{
$decoded = json_decode($json, true);
// $decode= var_dump($decoded);
// $ss=$decode["array"];
// echo $decoded['number'];
if (is_array($decoded["configurationItems"]))
{
foreach($decoded["configurationItems"] as $configurationItems)
// for($i=0;$i>sizeof($decoded["configurationItems"]);$i++)
{
$cfi = isset($configurationItems["configuration"]) ? $configurationItems["configuration"] : '';
if (isset($cfi["instanceId"]) && isset($cfi["imageId"]) && isset($cfi["privateDnsName"]) && isset($cfi["publicDnsName"]) && isset($cfi["keyName"]) && isset($cfi["stateTransitionReason"]) && isset($cfi["amiLaunchIndex"]) && isset($cfi["instanceType"]) && isset($cfi["launchTime"]) && isset($cfi["kernelId"]) && isset($cfi["subnetId"]) && isset($cfi["vpcId"]) && isset($cfi["privateIpAddress"]) && isset($cfi["architecture"]) && isset($cfi["rootDeviceType"]) && isset($cfi["rootDeviceName"]) && isset($cfi["virtualizationType"]) && isset($cfi["clientToken"]) && isset($cfi["sourceDestCheck"]) && isset($cfi["hypervisor"]) && isset($cfi["ebsOptimized"]))
{
$instanceId = $configurationItems["configuration"]["instanceId"];
echo "instanceId:", $instanceId, "<br />";
$imageId = $configurationItems["configuration"]["imageId"];
echo "imageId:", $imageId, "<br />";
$privateDnsName = $configurationItems["configuration"]["privateDnsName"];
echo "privateDnsName:", $privateDnsName, "<br />";
$publicDnsName = $configurationItems["configuration"]["publicDnsName"];
echo "publicDnsName:", $publicDnsName, "<br />";
$keyName = $configurationItems["configuration"]["keyName"];
echo "keyName:", $keyName, "<br />";
$stateTransitionReason = $configurationItems["configuration"]["stateTransitionReason"];
echo "stateTransitionReason:", $stateTransitionReason, "<br />";
$amiLaunchIndex = $configurationItems["configuration"]["amiLaunchIndex"];
echo "amiLaunchIndex:", $amiLaunchIndex, "<br />";
$instanceType = $configurationItems["configuration"]["instanceType"];
echo "instanceType:", $instanceType, "<br />";
$launchTime = $configurationItems["configuration"]["launchTime"];
echo "launchTime:", $launchTime, "<br />";
$kernelId = $configurationItems["configuration"]["kernelId"];
echo "kernelId:", $kernelId, "<br />";
$subnetId = $configurationItems["configuration"]["subnetId"];
echo "subnetId:", $subnetId, "<br />";
$vpcId = $configurationItems["configuration"]["vpcId"];
echo "vpcId:", $vpcId, "<br />";
$privateIpAddress = $configurationItems["configuration"]["privateIpAddress"];
echo "privateIpAddress:", $privateIpAddress, "<br />";
$architecture = $configurationItems["configuration"]["architecture"];
echo "architecture:", $architecture, "<br />";
$rootDeviceType = $configurationItems["configuration"]["rootDeviceType"];
echo "rootDeviceType:", $rootDeviceType, "<br />";
$rootDeviceName = $configurationItems["configuration"]["rootDeviceName"];
echo "rootDeviceName:", $rootDeviceName, "<br />";
$virtualizationType = $configurationItems["configuration"]["virtualizationType"];
echo "virtualizationType:", $virtualizationType, "<br />";
$clientToken = $configurationItems["configuration"]["clientToken"];
echo "clientToken:", $clientToken, "<br />";
$sourceDestCheck = $configurationItems["configuration"]["sourceDestCheck"];
echo "sourceDestCheck:", $sourceDestCheck, "<br />";
$hypervisor = $configurationItems["configuration"]["hypervisor"];
echo "hypervisor:", $hypervisor, "<br />";
$ebsOptimized = $configurationItems["configuration"]["ebsOptimized"];
echo "ebsOptimized:", $ebsOptimized, "<br />";
$result = mysqli_query($con, "INSERT INTO configuration(instance_id, image_id, private_dns_name, public_dns_name, key_name, state_transition_reason, ami_launch_index, instance_type, launch_time, kernel_id, subnet_id, vpc_id, private_ip_address,architecture, root_device_type, root_device_name, virtualisation_type, client_token, source_dest_check, hypervisor, ebs_optimised)
VALUES('$instanceId','$imageId', '$privateDnsName' , '$publicDnsName', '$keyName', '$stateTransitionReason', '$amiLaunchIndex', '$instanceType', '$launchTime', '$kernelId', '$subnetId', '$vpcId', '$privateIpAddress', '$architecture', '$rootDeviceType', '$rootDeviceName', '$virtualizationType', '$clientToken', '$sourceDestCheck', '$hypervisor', '$ebsOptimized')") or die("Insert Failed " . ((is_object($con)) ? mysqli_error($con) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));;
} // check if row inserted or not
if ($result)
{
// successfully inserted into database
$response["code"] = 1;
$response["message"] = "successfully updated config table ";
// echoing JSON response
echo json_encode($response);
}
else
{
// failed to insert row
$response["code"] = 2;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
}
}
}
?>
when I use
$cfi = isset($configurationItems["configuration"]) ? $configurationItems["configuration"] : '';
I get oops an error occured no explanation of error
when I use
$cfi = $configurationItems ["configuration"];
I get as above plus undefined index configuration (the error)
isset() will return FALSE if testing a variable that has been set to NULL.
For more details refer link
Instead of having to use isset for every single key that is required for your criteria, you can build a validation array with the required keys and then check if your designated array contains all those keys.
$required_keys = ['instanceId',
'imageId',
'privateDnsName',
'publicDnsName',
'keyName',
'stateTransitionReason',
'amiLaunchIndex',
'instanceType',
'launchTime',
'kernelId',
'subnetId',
'vpcId',
'privateIpAddress',
'architecture',
'rootDeviceType',
'rootDeviceName',
'virtualizationType',
'clientToken',
'sourceDestCheck',
'hypervisor',
'ebsOptimized'];
.........
if (isset($configurationItems['configuration'])) {
if (count(array_intersect_ukey($configurationItems['configuration'], array_flip($required_keys), function($a, $b) {
return -1 * ($a < $b) + ($a > $b);
})) === count($required_keys)) {
.....
}
}
bracket was in wrong place used
$cfi = isset($configurationItems["configuration"]) ? $configurationItems["configuration"] : '';`
works a treat

PHP while numbers in each row

<?php
$result10=mysql_query("SELECT * FROM blog_articles WHERE fk_semikatagori_id = 9") or die(mysql_error());
?>
<?php
$index = 1;
while($row10 = mysql_fetch_array($result10)) {
if($index%2==0) {
echo "<span class=\"f\">";
echo $row10['english_navn'];
echo "</span><br />";
}
else {
echo "<p><span class=\"f\">";
echo $row10['english_navn'];
echo "</span></p><br />";
echo "<p>";
echo $row10['english_tekst'];
echo "</p><br />";
}
$index++;
}
?>
Any ideas how I can display the number for each row?
I want it to start from 1.
I cant display the id from Mysql because it doesnt start from 1.
You could for example use a for() loop instead of a while() loop,
for ($index = 0; $row10 = mysql_fetch_array($result10); $index++)
{
...
echo $index;
}
Then the counter would be echoed.
$index = 1;
while( $row = mysql_fetch_array($result) )
{
// display the number for each row
echo $index;
// other code...
// increment number
$index++;
}
Thanks everyone for the help, it worked.
Here is the code if anyone else can use it.
<?php
$index = 1;
for ($index2 = 1; $row10 = mysql_fetch_array($result10); $index2++)
{
if($index%2==0)
{
echo "<span class=\"f\">";
echo $row10['english_navn'];
echo $index2;
echo "</span><br />";
}
else
{
echo "<p><span class=\"f\">";
echo $row10['english_navn'];
echo "</span></p><br />";
echo "<p>";
echo $index2;
echo $row10['english_tekst'];
echo "</p><br />";
}
$index++;
}
?>
I think the best solution that you can get are the follow:
Make a for statement:
<?php
for($idx=1; $row = mysql_fetch_array($result10); $idx++) {
...
}
?>
as said before or use the follow:
<?php
$idx = 1;
while($row = mysql_fetch_array($result10)) {
...
$idx++;
}
?>
I would recommend you to make a like upgrade in your select statement to get a faster result (if you start get many rows as result):
from: SELECT * FROM blog_articles WHERE fk_semikatagori_id = 9
to:
SELECT
english_navn
, english_tekst
FROM blog_articles
WHERE
fk_semikatagori_id = 9
Because you are using just these 2 columns into your loop but you are making MySQL engine get all columns from this table.
I hope it help you.

PHP rank and choice actions

I am trying to make a textbased game, but I can't seem to figure out of why this code down is not working.
It has a mysqli connection in the core file.
It has values for the chances in the database.
Rank is set in the database.
I don't get any errors, only the "Success" and "Failure" messages not showing up.
Code:
<?php
include_once "core.php";
function checkRandom($chance){
return rand(1, 100) <= (int)$chance;
}
$userid = '1';
$getAllQuery = $data->query("SELECT * FROM players WHERE id = '$userid'") or die($data->error);
while ($getall = $getAllQuery->fetch_assoc()) {
$rank = $getall['rank'];
$chance1 = $getall['crime_chance1'];
$chance2 = $getall['crime_chance2'];
$chance3 = $getall['crime_chance3'];
$chance4 = $getall['crime_chance4'];
$chance5 = $getall['crime_chance5'];
$chance6 = $getall['crime_chance6'];
}
if (isset($_POST['crime'])) {
$choice = $_POST['crime'];
$pass = 0;
$fail = 0;
if ($choice == 1 && $rank <= 1) {
echo "3esd";
if (checkRandom($chance1)) {
echo "Success";
} else {
echo "Failure";
}
} else {
if ($choice == 2 && $rank <= 2) {
if (checkRandom($chance2)) {
echo "Success";
} else {
echo "Failure";
}
}
}
}
echo "<form method='POST' action='#'>";
if ($rank >= 1) {
echo "<label><input type='radio' name='crime' value='1'>Crime 1 " . $chance1 . "% chance</label><br />";
if ($rank >= 2) {
echo "<label><input type='radio' name='crime' value='2'>Crime 2 " . $chance2 . "% chance</label><br />";
if ($rank >= 3) {
echo "<label><input type='radio' name='crime' value='3'>Crime 3 100% chance</label><br />";
}
}
}
echo "<input type='submit'>
</form>";
?>
I would really appreciate some help. :D
This code seems to work fine except under the following cases:
1) Nothing is handling Rank 3+ as the IF statements are <= 1 or <= 2 and 3 is > then 1 and 3.
2) If you select the first option, and you are not rank 1, the code won't return anything, because the first IF statement is limited to the selected choice being 1 AND the Rank being <= 1.
3) If you select the second option, and you are not rank 2, the code won't return anything, because the second IF statement is limited to the selected choice being 1 AND the Rank being <= 2.
see the following addition
}ELSE{ # condition not handled
ECHO "WE ARE HERE";
if ($choice == 1 && $rank <= 1) {
echo "3esd";
if (checkRandom($chance1)) {
echo "Success";
} else {
echo "Failure";
}
} else {
if ($choice == 2 && $rank <= 2) {
if (checkRandom($chance2)) {
echo "Success";
} else {
echo "Failure";
}
}ELSE{ # condition not handled
ECHO "WE ARE HERE";
}
}

PHP Simple HTML DOM Parser Dies

I am screen scraping page with a bunch of subpages using Simple HTML DOM Parser. For some reason it parses the first 40 subpages just fine but when it comes to number 41 it dies with no error.
I have made this test page and tried to log everything I do in my script aswell as some of the venets in the Simple HTML DOM Parser but I haven't been able to find the error.
Does anyone have an idea why it does when parsing URL number 41? Or does anyone know of some cases Simple HTML DOM Parser will fail?
My test page: http://snuzzer.dk/pub/shdp/parse.php
This is my script and I use a non-modified version of Simple HTML DOM Parser.
The interesting stuff happens in get_lections() and I have markede where I call Simple HTML DOM Parser.
define("LECTION_STATUS_REGULAR", 0);
define("LECTION_STATUS_CHANGED", 1);
define("LECTION_STATUS_CANCELLED", 2);
define("LECTION_DOCUMENTS_NONE", 0);
define("LECTION_DOCUMENTS_TRUE", 1);
define("AMOUNT_OF_WEEKS_IN_A_YEAR", 52);
include_once("simple_html_dom.php");
function clean_text($text)
{
$text = trim($text);
$text = strip_tags($text);
$text = html_entity_decode($text, ENT_QUOTES, "UTF-8");
$text = utf8_decode($text);
return $text;
}
function get_links_for_lections($weeks)
{
echo "Finding links<br /><textarea style=\"width:70%;height:150px;\">";
foreach($weeks as $week)
{
// **
//
// THIS IS WHERE I CALL SIMPLE HTML DOM PARSER
//
// **
echo " * Retrieving HTML...\n";
$html = file_get_html("http://www.lectio.dk/lectio/285/SkemaNy.aspx?type=elev&elevid=2444366210&week=" . $week['week'] . $week['year']);
echo " * HTML retrieved...\n";
$lections_regular = $html->find('a[class="s2skemabrik s2bgbox s2withlink"]');
$lections_changed = $html->find('a[class="s2skemabrik s2bgbox s2changed s2withlink"]');
$lections_cancelled = $html->find('a[class="s2skemabrik s2bgbox s2cancelled s2withlink"]');
$lections = array_merge($lections_regular, $lections_changed, $lections_cancelled);
foreach($lections as $lection)
{
$links[] = "http://www.lectio.dk" . $lection->href;
}
}
echo "</textarea>
<hr />";
return $links;
}
function get_lections($links)
{
// Create array to hold lections
$lections = array();
// Loop through links
$num = 1;
foreach($links as $link)
{
echo $num . ". " . $link . "<br />
<textarea style=\"width:70%;height:150px;\">";
// Initialize lection
$lection = array();
$lection['status'] = LECTION_STATUS_REGULAR;
$lection['documents'] = LECTION_DOCUMENTS_NONE;
echo " * Retrieving HTML...\n";
$html = file_get_html($link);
echo " * HTML retrieved\n";
// Loop through rows
foreach($html->find("tr") as $row)
{
echo " * New cell\n";
// Get name of row
$row_name = $row->find("th");
$row_name = $row_name['0']->innertext;
echo " - Row name: \"" . $row_name . "\"\n";
if ($row_name == "Type:")
{
echo " - Checking type...\n";
// Row tells what type it is
$cell = $row->find("td");
$content = $cell['0']->innertext;
$lection['type'] = clean_text($content);
echo " - Type checked\n";
}
else if ($row_name == "Titel:")
{
echo " - Checking title...\n";
// Row tells the title
$cell = $row->find("td");
$content = $cell['0']->innertext;
$lection['title'] = clean_text($content);
echo " - Title checked\n";
}
else if ($row_name == "Hold:")
{
echo " - Checking subject...\n";
// Row tells what the subject is
$cell = $row->find("td");
$content = $cell['0']->innertext;
$lection['subject'] = clean_text($content);
echo " - Subject checked\n";
}
else if ($row_name == "Lærere:")
{
echo " - Checking teachers...\n";
// Row tells who the teacher is
$cell = $row->find("td");
$content = $cell['0']->innertext;
$lection['teachers'] = clean_text($content);
echo " - Teachers checked\n";
}
else if ($row_name == "Lokaler:")
{
echo " - Checking location...\n";
// Row tells the location
$cell = $row->find("td");
$content = $cell['0']->innertext;
$lection['location'] = clean_text($content);
echo " - Location checked\n";
}
else if ($row_name == "Note:")
{
echo " - Checking note...\n";
// Row contains a note
$cell = $row->find("td");
$content = $cell['0']->innertext;
$lection['note'] = clean_text($content);
echo " - Note checked\n";
}
elseif ($row_name == "Dokumenter:")
{
echo " - Checking documents...\n";
// Row contains the documents
$cell = $row->find("td");
$content = $cell['0']->plaintext;
$content = clean_text($content);
if ($content)
{
// We can't get the titles of the documents as we are not logged in
// Instead we tell the user that there are documents available
$lection['documents'] = LECTION_DOCUMENTS_TRUE;
}
echo " - Documents checked\n";
}
else if ($row_name == "Lektier:")
{
echo " - Checking homework...\n";
// Row contains the homework
$cell = $row->find("td");
$content = $cell['0']->innertext;
$lection['homework'] = clean_text($content);
echo " - Homework checked\n";
}
else if ($row_name == "Vises:")
{
echo " - Checking status (part 1)...\n";
// Row tells where the lection is shown
$cell = $row->find("td");
$content = $cell['0']->plaintext;
$content = clean_text($content);
if (strstr($content, ","))
{
// If the above is true, the lection is NOT REGULAR
// Now we know that the lection is either changed or cancellde
// We assume it is changed
// Below we check if the lection is cancelled (Where $row_namme == "Status:")
$lection['status'] = LECTION_STATUS_CHANGED;
}
echo " - Status (part 1) checked\n";
}
}
// Add lection to array of lections
$lections[] = $lection;
print_r($lection);
echo " - Lection added!</textarea><br /><br />";
$num += 1;
}
return $lections;
}
function get_weeks($amount_of_weeks)
{
$weeks = array();
// Current week
$week_now = date('W');
$year_now = date('Y');
// Demo
$week_now = 44;
// Last week to fetch
$last_week = $week_now + $amount_of_weeks;
// Add weeks to array
for ($i = $week_now; $i <= $last_week; $i++)
{
$week = array();
if ($i > AMOUNT_OF_WEEKS_IN_A_YEAR)
{
// Week is next year
$week['week'] = $i - AMOUNT_OF_WEEKS_IN_A_YEAR;
$week['year'] = $year_now + 1;
}
else
{
// Week is in this year
$week['week'] = $i;
$week['year'] = $year_now;
}
// Add week to weeks
$weeks[] = $week;
}
return $weeks;
}
$weeks = get_weeks(5);
$links = get_links_for_lections($weeks);
$lections = get_lections($links);
echo "<hr />";
print_r($lections);
echo "<hr />";
I ran this and it worked fine, I got up to 96. If I had to guess I'd say you reached max excution time. Try adding this at the top: set_time_limit(0);
Otherwise try changing your error reporting and post any errors here.

Categories