php,pdo,foreach - foreach

Code:
public static function selectlogin($sq)
{
$db_handler = self::handler();
$res = $db_handler->query($sq);
foreach ($res as $row)
{
$_SESSION['admin_id'] = $row['id'];
}
return $_SESSION['admin_id'];
}
Error Message
Warning: Invalid argument supplied for foreach()
Can anybody fix this?

I am *not aware of the library that you are using, but before the foreach, you have to use same kind of equivalent of mysql_fetch_array() to convert the SQL Result Resource into an array which you can than work on. The reason for the error is because $res contains a Result Resource, not the result itself.

Yep! ... Your $res is a falsy value. NULL or FALSE.
if ($res)
{
for ($res as $row)
{
$_SESSION['admin_id'] = $row['id'];
}
return $_SESSION['admin_id'];
}

can you try this
if (is_array($res))
{
foreach ($res as $row)
{
// store
}
}
We check if array is not empty. and this way its cleaner.

PDO::query() returns a PDOStatement object, or FALSE on failure
var_dump($res); what is output?

Related

Mapping a Stream<List> to another type is returning a Stream<Null>

I'm trying to transform a Stream of a list of one type into a Stream of a list of another type, and having an issue with this.
I have this list of Habits that I'm streaming from Firebase, and I want to accept that stream in a function, and return a new stream that is a list of ViewModels of another type from it. But my function is returning a stream of the wrong type.
Here is my code:
Stream<List<HabitCompletionViewModel>> _getTodaysHabits(
Stream<List<Habit>> habitsStream) {
var result = habitsStream.map((habitsList) {
habitsList.map(
(habit) async {
await _getHabitCompletionsCurrent(habit);
HabitCompletion completion = habit.completions!.firstWhere(
(completion) => completion.date
.dayEqualityCheck(DateTime.now().startOfDate()));
return HabitCompletionViewModel(completion: completion, habit: habit);
},
).toList();
});
return result;
}
I am getting a compile error because the result variable is showing as type Stream<Null> when I hover over it, where I would expect it to be Stream<List<HabitCompletionViewModel>>. Any idea what I'm doing wrong?
Your outer .map call does not have a return statement which is why you are getting a Stream<Null>.
So add a return statement like so:
Stream<List<HabitCompletionViewModel>> _getTodaysHabits(
Stream<List<Habit>> habitsStream) {
var result = habitsStream.map((habitsList) {
// added return statement here
return habitsList.map(
(habit) async {
await _getHabitCompletionsCurrent(habit);
HabitCompletion completion = habit.completions!.firstWhere(
(completion) =>
completion.date.dayEqualityCheck(DateTime.now().startOfDate()));
return HabitCompletionViewModel(completion: completion, habit: habit);
},
).toList();
});
return result;
}
However the above code still has an error because it is now returning a Stream<List<Future<HabitCompletionViewModel>>> instead of the desired Stream<List<HabitCompletionViewModel>>. To solve this you can use .asyncMap instead of .map.
Stream<List<HabitCompletionViewModel>> _getTodaysHabits(
Stream<List<Habit>> habitsStream) {
var result = habitsStream.asyncMap((habitsList) {
return Stream.fromIterable(habitsList).asyncMap(
(habit) async {
await _getHabitCompletionsCurrent(habit);
HabitCompletion completion = habit.completions!.firstWhere(
(completion) =>
completion.date.dayEqualityCheck(DateTime.now().startOfDate()));
return HabitCompletionViewModel(completion: completion, habit: habit);
},
).toList();
});
return result;
}

Adding key value pair to object inside forEach loop

I'm trying to add a thenable result to an object using a forEach loop. I can see the entries when I console.log the results, but when I try to use them for other parts of my code, I get an empty object.
I was getting an error previously telling me that the object's name (results) was not defined. I moved the object outside of the function and now I just get an empty object returned when I try to return the values of the object.
I tried this first:
let results = {};
// Check for all videos in cache (returns [])
const findAllVidsInCache = (videoArray) => {
videoArray.forEach(video => {
check(video).then(res => {
// resultsArray.push(res);
results[video] = res;
return results;
});
});
return results;
}
Then I tried this:
let results = {};
// Check for all videos in cache (returns [])
const findAllVidsInCache = (videoArray) => {
videoArray.forEach(video => {
check(video).then(res => {
// resultsArray.push(res);
results[video] = res;
return results;
});
});
let values = Object.values(results);
return values;
}
But I still keep getting an empty object when the function is called (I'm using devTools to call the function so nothing else should be interfering with it).
What I'm looking for, and what I can see in the console when I log it to the console, is an object that appears like so:
'video1': false,
'video2': false,
'video3': false,
'video4': true,
'video5': false,
...
Up to 12 videos.
Any ideas what I'm doing wrong here?
Try reading about promise handling. return results; returns a promise.

Issue with Zapier Code - Simple if else statement

I have looked over this countless times and yet I get the error "You must return a single object or array of objects.
if (inputData.score === '0') {
output = 'Passed';
} else {
output = 'Failed';
}
return output;
Not sure what I am doing wrong?
David here, from the Zapier Platform team.
In your code, you're returning a string, not a javascript object ({}) or array of objects ([{}, {}]).
change your code to the following:
if (inputData.score === '0') {
output = 'Passed';
} else {
output = 'Failed';
}
return {result: output};

Why does the error method return an error?

I want to validate input corresponding to the following grammar snippet:
Declaration:
name = ID "=" brCon=BracketContent
;
BracketContent:
decCon=DecContent (comp+=COMPARATOR content+=DecContent)*
;
DecContent:
(neg=("!"|"not"))? singleContent=VarContent (op+=OPERATOR nextCon+=VarContent)*
;
My validation looks like that:
#Check
def checkNoCycleInHierarchy(Declaration dec) {
if(dec.decCon.singleContent.reference == null) {
return
}
var names = newArrayList
var con = dec.decCon.singleContent
while(con.reference != null) {
con = getThatReference(con).singleContent
if(names.contains(getParentName(con))) {
val errorMsg = "Cycle in hierarchy!"
error(errorMsg,
SQFPackage.eINSTANCE.bracketContent_DecCon,
CYCLE_IN_HIERARCHY)
return
}
names.add(getParentName(con))
}
}
But when I test this validation with a testCaseit returns me an error message:
Expected ERROR 'raven.sqf.CycleInHierarchy' on Declaration at [-1:-1] but got
ERROR (org.eclipse.emf.ecore.impl.EClassImpl#5a7fe64f (name: Declaration) (instanceClassName: null) (abstract: false, interface: false).0) 'Error executing EValidator', offset null, length null
ERROR (org.eclipse.emf.ecore.impl.EClassImpl#5a7fe64f (name: Declaration) (instanceClassName: null) (abstract: false, interface: false).0) 'Error executing EValidator', offset null, length null
I just can't figure out what's wrong with it so I hope that someone of you might have an idea.
Greetings Krzmbrzl
You test utility tells you that the validator did not produce the expected validation error ("CycleInHierarchy").
Instead, the validator produced the error "Error executing EValidator".
Which means an exception has been thrown when your validator was executed.
It turned out it was an internal error...I'm still not exactly sure what went wrong but I have rewritten my validation method and now it works as expected.
Now the method looks like this:
enter code here#Check
def checkNoCycleInHierarchy(Declaration dec) {
if(dec.varContent.reference == null) {
//proceed only if there is a reference
return
}
var content = dec.varContent
var names = newArrayList
while(content.reference != null && !names.contains(getParentName(content))) {
names.add(getParentName(content))
content = content.reference.varContent
if(names.contains(getParentName(content))) {
val errorMsg = "Cycle in hierarchy!"
error(errorMsg,
SQFPackage.eINSTANCE.declaration_BrCon,
CYCLE_IN_HIERARCHY)
return
}
}
}
I have the suspicion that there was a problem with the usage of my "getThatReference" in this case.
Greeting Krzmbrzl

How to query multiple 'Split' in linq?

I am trying to execute the following call ("api/test/sin=2129VAH99,8974922&sip=108124AG3") from the code below, but I cannot seem to get the call to work, as it keeps responding with 'no data' error.
public HttpResponseMessage Get([FromUri] Query query)
{
var data = db.database_Items.AsQueryable();
if (!String.IsNullOrEmpty(query.sip))
{
var ids = query.sip.Split(',').ToList();
data = data.Where(c => ids.Any(i => (c.SIP != null && c.SIP.Contains(i))));
}
if (!String.IsNullOrEmpty(query.sin))
{
var ids = query.sin.Split(',').ToList();
data = data.Where(c => ids.Any(i => (c.SINs != null && c.SINs.Contains(i))));
}
if (!data.Any())
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
}
return Request.CreateResponse(HttpStatusCode.OK, data);
}
Any help/guidance would be very much appreciated. Many thanks.
Try to change your Url to :
api/test?sin=2129VAH99,8974922&sip=108124AG3

Resources