I'm trying to return a value to an android application in JSON format using a web service. For some reason, my code is only returning "Invalid login, please try again". I'm positive that the username is being entered, and I'm positive the tasks are returning properly. Using test code, which I've included as commented lines, I verify that the service will return one set of data to the application. It appears that the problem is with my foreach loop, but I don't see how. It's pretty simple stuff. Obviously it isn't iterating, or my count would be increasing and I wouldn't receive the Invalid Login error. The only thing I can figure is that I would need to use a nest foreach loop, but I haven't had much success with that, either.
Thanks in advance for the help, guys!
Here is the foreach loop...
//for reach task returned, add to array for later output
foreach ($row2['Description'] as $t)
{
$taskDisplay = array('task' => $t);
$taskCount++;
}
and the count...
if ($taskCount > 0)
{
echo json_encode($taskDisplay);
}
else
{
echo "Invalid login, please try again";
}
here is the code in full
$taskDisplay = array();
$taskCount = 0;
//do this portion if app gives key value "PART_ONE"
if ($result['part'] == "PART_ONE")
{
//if username was entered, check user credentials
if(array_key_exists('user', $result)) {
$usercheck = $con->prepare("Select * from Employee
Where usr = ?
and pass = ?");
$usercheck -> execute(array($result['user'], $result['password']));
$row = $usercheck -> fetch();
//if username was verified, select tasks from database
if($row['usr'])
{
$task = $con->prepare("Select * from Tasks
where Assigned_Employee = ?");
$task -> execute(array($result['user']));
$row2 = $task -> fetch();
$statusCode = "Success";
//$taskDisplay = $row2['Description'];
//for reach task returned, add to array for later output
foreach ($row2['Description'] as $t)
{
$taskDisplay = array('task' => $t);
$taskCount++;
}
}
else
{
$statusCode = "Fail";
//bail if invalid username entered
exit;
}
//$arr = array('task' => $taskDisplay, 'status_code' => $statusCode);
//echo json_encode($arr);
if ($taskCount > 0)
{
echo json_encode($taskDisplay);
}
else
{
echo "Invalid login, please try again";
}
}
}
To foreach over all rows you'll want fetchAll(). Then you want to access the Description column in each row:
$row2 = $task->fetchAll();
// etc...
foreach ($row2 as $t)
{
$taskDisplay[] = array('task' => $t['Description']);
$taskCount++;
}
Related
Im writing a page in HTML/PHP that connects to a Marina Database(boats,owners etc...) that takes a boat name chosen from a drop down list and then displays all the service that boat has had done on it.
here is my relevant code...
if(isset($_POST['form1'])){//if there was input data submitted
$form1 = $_POST['form1'];
$sql1 = 'select Status from ServiceRequest,MarinaSlip where MarinaSlip.SlipID = ServiceRequest.SlipID and BoatName = "'.$form1.'"';
$form1 = null;
$result1 = $conn->query($sql1);
$test = 0;
while ($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$values1[] = array(
'Status' => $row['Status']
);
$test = 1;
}
echo '<p>Service Done:</p><ol>';
if($test = 1){
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
echo '</ol>';
}else{
echo 'No service Done';
}
the issue im having is that some of the descriptions of sevice are simply Open which i do not want displayed as service done, or there is no service completed at all, which throws undefined variable: values1
how would I stop my script from adding Open to the values1 array and display a message that no work has been completed if values1 is empty?
Try this
$arr = array();
if (empty($arr))
{
echo'empty array';
}
We often use empty($array_name) to check whether it is empty or not
<?php
if(!empty($array_name))
{
//not empty
}
else
{
//empty
}
there is also another way we can double sure about is using count() function
if(count($array_name) > 0)
{
//not empty
}
else
{
//empty
}
?>
To make sure an array is empty you can use count() and empty() both. but count() is slightly slower than empty().count() returns the number of element present in an array.
$arr=array();
if(count($arr)==0){
//your code here
}
try this
if(isset($array_name) && !empty($array_name))
{
//not empty
}
You can try this-
if (empty($somelist)) {
// list is empty.
}
I often use empty($arr) to do it.
Try this instead:
if (!$values1) {
echo "No work has been completed";
} else {
//Do staffs here
}
I think what you need is to check if $values1 exists so try using isset() to do that and there is no need to use the $test var:
if(isset($values1))
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
Or try to define $values1 before the while:
$values1 = array();
then check if it's not empty:
if($values1 != '')
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
All you have to do is get the boolean value of
empty($array). It will return false if the array is empty.
You could use empty($varName) for multiple uses.
For more reference : http://php.net/manual/en/function.empty.php
I was doing this code for my project and it seems that I can't get the values of the query into $currentRow. All that saved into the variable $currentrow is 22 which is the number rows in the database. I want to have access to all the query results. Please help. Here's the code.
public function getBSIConfig(){
$conn = oci_connect("472proj","system","//localhost/XE");
$sql = oci_parse($conn,"SELECT conf_id, conf_key, conf_value FROM bsi_configure");
oci_execute($sql);
echo "0";
while($currentRow = oci_fetch_all($sql,$res)){
echo "1.5";
echo $currentRow;
if($currentRow["conf_key"]){
echo "1";
if($currentRow["conf_value"]){
$this->config[trim($currentRow["conf_key"])] = trim($currentRow["conf_value"]);
echo "2";
}else{
$this->config[trim($currentRow["conf_key"])] = false;
echo "3";
}
}
}
}
And the output is only:
0
1.5
22
The results from this function are stored in the 2nd argument, rather than returned directly. See if this works for you:
$results = array();
$numResults = oci_fetch_all($sql, $results);
foreach ($results as $result) {
if ($result["conf_key"]) {
// etc ...
}
}
Read this http://php.net/manual/en/function.oci-fetch-all.php , you might get an idea what's wrong.
I am trying to GET different rows from different columns in php/mysql, and pack them into an array. I am able to successfully GET a jason encoded array back IF all values in the GET string match. However, if there is no match, the code echos 'no match', and without the array. I know this is because of the way my code is formatted. What I would like help figuring out, is how to format my code so that it just displays "null" in the array for the match it couldn't find.
Here is my code:
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode($fbaddra);
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['addr'];
} else {
$fbaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['addr'];
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
UPDATE: The GET Request
I would like the GET request below to return the full array, with whatever value that didn't match as 'null' inside the array.
domain.com/api/core/engine.php?a=fbaddra&facebook=username&facebookp=pagename
The GET above currently returns null.
Requests that work:
domain.com/api/core/engine.php?a=fbaddra&facebook=username or domain.com/api/core/engine.php?a=fbaddra&facebookp=pagename
These requests return the full array with the values that match, or null for the values that don't.
TL;DR
I need assistance figuring out how to format code to give back the full array with a value of 'null' for no match found in a row.
rather than assigning as 'null' assign null. Your full code as follows :
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode('no match');
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
You can even leave else part altogether.
Check your code in this fragment you not use same names for variables:
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = 'null';
}
$fbaddr not is same as $fpaddr, this assign wrong result to if statement.
It was the mysql query that was the problem.
For those who come across this, and need something similar, you'll need to format your query like this:
** MYSQL QUERY **
if ($_GET['PUTVALUEHERE']) {
$g = $_GET['PUTVALUEHERE'];
$gq = $mysqli->real_escape_string($g);
$q1 = "SELECT * FROM `addrbook` WHERE `facebookp` = '".$gq."' OR `facebook` = '".$gq."'";
}
** PHP CODE **
if($_GET['PUTVALUEHERE']{
echo json_encode($row['addr']);
}
Like the title says, PHP is really confusing me on a simple if comparison statement that's returning the opposite of what it should be returning. I'm trying to compare 2 datetime's that are first converted to strings:
//Fetched db query, this returns 2012-06-23 16:00:00
$databaseDateTime = strtotime($row['time']);
//This now returns 1340481600
//today's date and time I'm comparing to, this returns 2012-06-22 17:14:46
$todaysDateTime = strtotime(date("Y-m-d H:i:s"));
//this now returns 1340399686
Great, everything works perfect so far. Now here's where things get hairy:
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
And this returns 'past', which of course it shouldn't. Please tell me I'm missing something. My project kind of depends on this functionality being airtight.
**EDIT***
Thanks guys for taking the time to help me out. Let me post the entire code because a few of you need more context. The request is coming from an IOS5 to my backend code and json is being sent back to the phone.
<?php
//all included files including $link to mysqli_db and function sendResponse()
function getEvents($eventType, $eventArray) {
global $link;
global $result;
global $i;
global $todaysDateTime;
foreach ($eventArray as $key => $value) {
$sqlGetDeal = mysqli_query($link, "SELECT time FROM deals WHERE id='$value' AND active='y' LIMIT 1") or die ("Sorry there has been an error!");
while ($row = mysqli_fetch_array($sqlGetDeal)) {
//compare times to check if event already happened
$databaseDateTime = strtotime($row['time']);
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
$result[$i] = array(
'whenDeal' => $eventType,
'time' => $databaseDateTime,
);
$i++;
}//end while
}//end foreach
}
if (isset($_GET['my'])) {
//$_GET['my'] comes in as a string of numbers separated by commas e.g. 3,2,6,3
$myDeals = preg_replace('#[^0-9,]#', '', $_GET['my']);
$todaysDateTime = strtotime(date("Y-m-d H:i:s"));
$result = array();
$kaboomMy = explode(",", $myDeals);
$i = 1;
if ($myEvents != "") {
getEvents('future', $kaboomMy);
}//end if
sendResponse(200, json_encode($result));
} else {
sendResponse(400, 'Invalid request');
} //end $_POST isset
?>
Found a quick hack around the issue. I just added a local variable to my function and rearranged my compare statement
//added local variable $eventTyppe to function
$eventTyppe;
changed compare from:
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
to:
if ($todaysDateTime < $databaseDateTime ) {
$eventTyppe = $eventType;
} else {
$eventTyppe = 'past';
}
Notice if I rearrange compare:
if ($databaseDateTime < $todaysDateTime ) {
$eventTyppe = 'past';
} else {
$eventTyppe = $eventType;
}
I still get the same error. This is the weirdest thing I've ever seen and the first PHP bug I've run into (I'm assuming it's a PHP bug).
Could you print the values of the times right before this line?
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
Since that one is declared as global I'm wondering if is it coming back incorrectly.
this is taking me too long to figure out. I am using Codeigniter to query a database.
The model does this
function currentfunction($id)
{
$query = $this->db->get_where('mytable', array("id =" => $id));
if($query->num_rows() > 0){
return $query->result_array();
}else {
return false;
}
}
The controller
$this->load->model('Display');
$results = $this->Display->currentfunction($id);
$this->load->view('current_items', array('currentitems' => $results));
The view
foreach($currentitems as $row){
echo $row['name']
///....do more
}
works just fine EXCEPT IF no rows are returned
then
Message: Invalid argument supplied for foreach()...
How do I handle the if...else...scenario
I tried this Q-A, but doesn't work for me. PlsHlp.
Just do:
if(is_array($currentitems)) {
foreach($currentitems as $row){
echo $row['name']
///....do more
}
}
else
{
echo "No items in database!";
}
You are getting an error because foreach expects its first argument to be an array. If there are no items in the database however your functions returns false.
This is because when you run your code:
$query = $this->db->get_where('mytable', array("id =" => $id));
if($query->num_rows() > 0){
return $query->result_array();
}else {
return false;
}
when there are no rows returned the above code works fine it just doesnt work in the view where you try to run a for loop.
This for loop should not be run if there are no rows returned. yet you are trying to run a forloop even though there are no rows to work with.
My suggestion is changing the code like so:
$query = $this->db->get_where('mytable', array("id =" => $id));
if($query->num_rows() > 0){
return $query->result_array();
}else {
$noResults = true;
}
in the view you will have something like this before your for loop:
if($noResults != true){
foreach($currentitems as $row){
echo $row['name']
///....do more
}
}
else{
//do something
echo "No items in database!";
}
Hope this helps.
PK
Why don't you just do this:
function currentfunction($id)
{
return $this->db->get_where('mytable', array("id =" => $id));
}
In the view, if there are no results, an empty array will be returned and foreach won't throw an error:
foreach($currentitems->result_array() as $row)
{
echo $row['name']
///....do more
}
Much cleaner IMO.
If you want to show an error message in your view, you can do:
if($currentitems->num_rows() > 0)
{
foreach($currentitems->result_array() as $row)
{
echo $row['name']
///....do more
}
}
else
{
// Error message
}
This is better than checking if there are results with if/else twice, like halfdan and Pavan are suggesting.