Codeigniter not properly processing a foreach loop - php

I've got about 10 rows in my db and 3 of which have status == to 'Pass'. The problem I've noticed with the code below is with the foreach loop. It's not wanting to work properly. I can't even get the script to send the jSON data back to the browser which means the script isn't processing past the foreach statement. Does anybody know how to fix this?
public function logsig() {
header('Content-type:application/json');
$postedUser = $this->input->post('username');
$password = $this->input->post('password');
$hashedPass = $this->encrypt->sha1($password);
$query = $this->db->query("SELECT * FROM users WHERE username = '{$postedUser}' AND password = '{$hashedPass}'");
foreach ($query->result() as $row) {
if ($row->status == "Pass") {
if ($query->num_rows() > 0) {
$this->session->set_userdata('logged', "1");
$this->session->set_userdata("username", "{$postedUser}");
echo json_encode(array('session_state' => true));
} else {
echo json_encode(array('session_state' => false));
}
} elseif ($row->status == "Fail" || "Pending") {
exit;
}
}
}

You're echoing the JSON in each iteration of the loop. This will make something like this:
{"session_state": true}{"session_state": false}
This is not valid JSON.
You need to build an array, and then echo json_encode() (just once) after the loop.
Also your elseif should be this:
elseif ($row->status == "Fail" || $row->status == "Pending")

Replace elseif ($row->status == "Fail" || "Pending") { with
elseif ($row->status == "Fail" || $row->status == "Pending") {
You are missing $row->status == in your second condition of elseif block

Related

PHP unreachable if statement in foreach

I have this code I have set up that is supposed to read from JSON and output each array. Except when I use my foreach loop, I have an unreachable if statement. It's supposed to reach it if "type" is "rawbr".
I have confirmed that this has nothing to do with foreach by placing the same message in a row.
I wish to output this:
UnknownUser3: hey hxor? [To you]
Welcome to chat!
Here is my code:
innerchat.php:
<?php
session_start();
function tf($oz){
if($oz == 0){
return false;
} else if($oz == 1){
return true;
}
}
if(isset($_GET["room"]) && file_exists("data/".$_GET["room"].".json")){
$jsonF = file_get_contents("data/".$_GET["room"].".json");
$jsonD = json_decode($jsonF, true);
echo count($jsonD["msg"]);
// echo $jsonD["msg"][1]["type"];
foreach($jsonD["msg"] as $key => $message){
if($message["visibility"] !== "all"){
if(isset($_SESSION["ts_user"]) && $_SESSION["ts_user"] == $message["visibility"] && $message["type"] != "rawbr"){
echo "<font color='".$message["color"]."'><b><u>".$message["from"].":</u></b></font> ".htmlspecialchars($message["cont"])." [To you]<br />";
} else if($message["type"] === "message" && $message["visibility"] === "all"){
echo "<font color='".$message["color"]."'><b><u>".$message["from"].":</u></b></font> ".htmlspecialchars($message["cont"])." [normal message]<br />";
} else if($message["type"] === "rawbr" && $message["visibility"] === "all"){
echo $message["cont"]."<br />";
}
}
}
}
kb6k.json (the room we're working with)
{"name":"KillerBot 6000","desc":"A room with very harsh moderation. Proceed with caution!","max":600,"color":"#e0e0e0","whispersenabled":true,"forbiddenCommands":["/milk", "/bal"],"msg":[{"cont":"hey, hxor?","time":1,"color":"black","type":"message","visibility":"HxOr1337","from":"UnknownUser1"},{"cont":"Welcome to the chat!","time":0,"type":"message","color":"black","visibility":"HxOr1337","from":"Test"}]}
I know it couldn't possibly do anything to do with the JSON itself, since the other values are nearly identical apart from "visibility"
Ok, so I figured out that I put those if statements in $message["visibility"] !== "all"
The code:
<?php
session_start();
if(isset($_GET["room"]) && file_exists("data/".$_GET["room"].".json")){
$jsonF = file_get_contents("data/".$_GET["room"].".json");
$jsonD = json_decode($jsonF, true);
// echo $jsonD["msg"][1]["type"];
foreach($jsonD["msg"] as $key => $message){
if($message["visibility"] !== "all"){
if(isset($_SESSION["ts_user"]) && $_SESSION["ts_user"] == $message["visibility"] && $message["type"] != "rawbr"){
echo "<font color='".$message["color"]."'><b><u>".$message["from"].":</u></b></font> ".htmlspecialchars($message["cont"])." [To you]<br />";
}
} else {
if($message["type"] === "message" && $message["visibility"] === "all"){
echo "<font color='".$message["color"]."'><b><u>".$message["from"].":</u></b></font> ".htmlspecialchars($message["cont"])." [normal message]<br />";
} else if($message["type"] === "rawbr" && $message["visibility"] === "all"){
echo $message["cont"]."<br />";
}
}
}
}

if condition with foreach loop for array in php

is it any way to stop this repeated data.
if ($employees_csa[0]->csa_taken == 2 && $employees_csa[1]->csa_taken == 2 && $employees_csa[2]->csa_taken == 2 && $employees_csa[3]->csa_taken == 2 && $employees_csa[4]->csa_taken == 2 && $employees_csa[5]->csa_taken == 2 && $employees_csa[6]->csa_taken == 2 && $employees_csa[7]->csa_taken == 2) {
echo "data";
}
i tried for key range(0 , 8)
like this
foreach (range(0, count($employees_csa)) as $number) {
if ($employees_csa[$number]->csa_taken == 2) {
echo "data";
}
}
i tried that way not get any succes. i any another way to write easy condition.
You can loop arrays out of the box:
$all_taken = true;
foreach ($employees_csa as $employee) {
if ($employee->csa_taken != 2) {
$all_taken = false;
break;
}
}
if ($all_taken) {
echo 'data';
}
Another approach would be array_reduce() but this doesn't abort looping when there's already an answer:
$all_taken = array_reduce($employees_csa, function ($all_taken, $employee) {
if ($employee->csa_taken != 2) {
return false;
}
return $all_taken;
}, true);
if ($all_taken) {
echo 'data';
}
Alternatively, you could do it like this using array_column to pull out all the csa_taken properties, then reducing to 1 item if they are all the same with array_unique() and then checking that the same value is the expected number 2 with reset().
$csa_taken = array_column($employees_csa, 'csa_taken');
if (reset($csa_taken) === 2 && count(array_unique($csa_taken)) === 1) {
echo 'data';
}
Reusable function version: https://3v4l.org/4kYiE
A simple for-loop could work
$condition_met=true;
for($i=0;$i<8;++$i){
if( $employees_csa[$i]->csa_taken != 2){
$condition_met=false;
break;
}
}
if($condition_met===true){
//success
}
else{
//fail
}
A simple method could be done like
foreach($employees_csa as $singleEmployee){
if($singleEmployee->csa_taken == 2){
echo "data";
}
}

I'm trying to check a form's input to make sure the fields aren't blank or contain specific words. Anyone know why this code isn't working?

This is the "contactprocess.php" file that the form posts to:
$result = "";
foreach ($_POST as $key => $val) {
if(($val != "") || (strpos($val,'http') == false) || (strpos($val,'seo') == false)){
$result = "clear" ;
}
}
if ($result == '') {
header("location: contact.php");
}
The code ignores the "header("location: contact.php");" line and continues on with the rest of the script. How else can this be written?
In your if-branch where you attempt to redirect, you need exit; to prevent the script from continuing execution:
if ($result == '')
{
header("location: contact.php");
exit;
}

Multiple else if not working correctly PHP

I'm having an issue with a login script. The rest of it works fine, but there is something odd happening here. The issue is that even though $IPCHK is returning true the elseif function does not execute. It only executes when I set $IPCHK to jibberish. Any help would be great. Thanks in advance
if ($Numrows == 0)
{
if ($Fail >= 3)
{
$Connection = connectToDb();
//return true, false,pending
$IPCHK = checkIP();
$IPCHK = true; //forcing it to be true and still broke
//If no ip id there
if($IPCHK == false)
{
$IP = getIP();
$Query = "INSERT INTO ip VALUES ('','$IP',Now())";
mysqli_query($Connection, $Query)
or die(error(mysqli_error($Connection)));
echo "You have failed to login too many times";
echo "<br />Please <a href='login.php'>try again</a> later.";
$Lock = true;
}
//If ip is there but timer is not up
elseif ($IPCHK == 'pending')
{
echo "You have failed to login too many times";
echo "<br />Please <a href='login.php'>try again</a> later.";
$Lock = true;
}
//Timers Up
elseif ($IPCHK == true) //here does not execute when it returns true
{
$_SESSION['FailedLogin'] = 0;
$Lock = false;
}
else
{
error("End of if check");
}
}
else
{
$Fail = 3 - $Fail;
$_SESSION['FailedLogin'] = $_SESSION['FailedLogin'] + 1;
$Error = $Error."<br />You have ".$Fail." attempts remaining";
}
}
In your Condition you have
elseif ($IPCHK == 'pending')
then
elseif ($IPCHK == true)
the second else will never execute because $IPCHK == 'pending' means also that $IPCHK == true
if you want to execute your second else you have to change the seconde condition to somethig like this
elseif($IPCHK == 'done')
or simply use === like this
elseif($IPCHK === 'pending')
then
elseif($IPCHK === true)
Lamari Alaa is correct, and the relevant documentation entry on type juggling can help understand why.
The following script outputs: boolean = string:
$test = true;
if( $test == 'pending' ) {
echo 'boolean = string';
} else if ( $test ) {
echo 'boolean != string';
}
This is because the string 'pending' is being coerced into a boolean value before being compared to the boolean value true. Since it evaluates as true, the first condition is taken. Consider replacing == 'pending' to === 'pending'

If / else if / else with query to a database resulting false.

I have a select box with an option for All, and then a list of users.
What I'm struggling with is creating something like this. I have most of it except trying to query the database to for it to check if the variable is in the database.
if ($variable == 'All') { code here }
else if ($variable != 'ALL' != *[result in database]*) { code here }
else { code here }
I have most of it except trying to query the database to for it to check if the variable is in the database.
Any suggestions how I can encorporate a query of a mySQL database in my if statement.
Thanks
if ($variable == 'All') {
... do something ...
} else {
$sql = "SELECT ...";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if ($row['somefield'] == 'whatever') {
... do something else ...
} else {
... do something even "elser" ...
}
}
You can't use operators like that.
Replace:
else if ($variable != 'ALL' != *[result in database]*) { code here }
With:
else if ($variable != 'ALL' AND $variable != *[result in database]*) { code here }

Categories