PHP: make a 'fake'/custom statement in while - php

I have this while loop.
while($show = $queryActivities->fetch()){ echo $show["name"]."<br>"; }
This takes data from the query and outputs the names..
Now is it possible to make a custom/fake data? I would like to make one if theres no data/statement in the $queryActivities then it should make a custom one called "name" with value "Nothing here.."
Is this possible? Can you do that?
I know I can do if($queryActivities->rowCount == 0){ echo "Nothing here" ; }
But I more thought of creating a custom data, so it runs the while loop, with the custom data, that only gets made if theres nothing in $queryActivities.
Something like..:
if($queryActivities->rowCount == 0){
# ..MAKE CUSTOM DATA..
# ..SOMETHING LIKE THIS MAYBE: ..
# $queryActivities = MAKE ARRAY WITH name => 'Nothing here'.. (just a thought)
}
while ($show = $queryActivities->fetch()){
echo $show["name"]."<br>";
}
Something like this, just what I imagine, although I dont know really how.
Thank you

Retrieve your data to an array, and then print it out. In between these two steps, you can modify it as desired.
This is more orderly, anyhow. I don't like retrieving from the DB and displaying in one step
You could either have an if/else that checks if the array is empty and prints a default message, or creates a default entry with a 'name' property that then is displayed with the same output loop as normal data. I'd prefer the first, but we'll do the second style since that's what you asked about.
Here's one simple solution.
$activities=array();
while($show = $queryActivities->fetch()){ $activities[]=$show; }
if(empty($activities)){ $activities=array(array('name'=>'None Found')); }
foreach($activities as $activity){
echo $activity['name']."<br>";
}
I think just using an if/else is a better solution. Depending on your output style, though, this might involve more code repetition.
$activities=array();
while($show = $queryActivities->fetch()){ $activities[]=$show; }
if(empty($activities)){
echo "None found <br>";
}
else{
foreach($activities as $activity){
echo $activity['name']."<br>";
}
}

Related

PHP 7 - IF statements doesn't seem to work while trying to detect KEYS in $_SESSION arrays

[PHP 7.1]
Below you can see my PHP code. My problem comes from my difficult to understand why the second IF statement doesn't work with the array $_SESSION['items'], but does work with the testing array $zoo (I just created $zoo to make tests in place of $_SESSION['items']).
I've an AJAX script that send POST data to the PHP code and then logs the response to the browser console in order to let me review the results. Everything was working fine with my tests, all changes done to other arrays where executed with fine results, the only issue I couldn't understand and solve, even after extensively searching for some clues on the web and trying different things, is the misterious ways of the $_SESSION array that doesn't seem to like to expose its keys to lurking IF statements... And I got here trying to detect the existence of a key inside an array in order to increment its value. Something I already did before with other arrays that weren't $_SESSION arrays and it worked just fine.
session_start();
$_SESSION['items'] = array();
$zoo['animals'] = array('tiger'=>2,'lion'=>3);
if(isset($_POST['item_name'])) {
if (isset($_SESSION['items'][$_POST['item_name']]) || array_key_exists($_POST['item_name'], $_SESSION['items'])) {
$_SESSION['items'][$_POST['item_name']]['qnt']++;
} else {
$_SESSION['item_name'][$_POST['item_name']] = array('model'=>$_POST['item_model'], 'qnt'=>1);
}
echo json_encode($_SESSION['items']);
exit();
}
This is a simplified version of your code with just the important stuff
session_start();
$_SESSION['items'] = array(); //items is now emtpy
if (isset($_SESSION['items'][$_POST['item_name']]) || array_key_exists($_POST['item_name'], $_SESSION['items'])) {
}
This should make it a bit easier to see, so it's simply because items is an empty array. Do to assigning it as such before the condition.
To fix it, either remove this line:
$_SESSION['items'] = array();
OR better yet:
$_SESSION['items'] = isset($_SESSION['items']) ? $_SESSION['items'] : [];
OR even
if(!isset($_SESSION['items'])) $_SESSION['items'] = [];
It's up to you how you fix it, but I am certain you don't want to reset that to an empty array. It's a very easy mistake to make, and a hard one to find because it's technically legal PHP code. I just have a built in debugger in my head now, from years of coding ... lol ... Most times I can literally picture in my mind how something will execute.
Cheers!
As noted by #artisticphoenix -
session_start();
// Check to see if there is a session variable before clearing it
// You only want to initialize it once
if (!isset($_SESSION['items'])) {
$_SESSION['items'] = [];
}
$zoo['animals'] = array('tiger'=>2,'lion'=>3);
if(isset($_POST['item_name'])) {
// This test is sufficient to check if the session variable has been set
if (isset($_SESSION['items'][$_POST['item_name']])) {
$_SESSION['items'][$_POST['item_name']]['qnt']++;
} else {
$_SESSION['items'][$_POST['item_name']] = array('model'=>$_POST['item_model'], 'qnt'=>1);
}
echo json_encode($_SESSION['items']);
exit();
}
$_SESSION['item_name'] should be $_SESSION['items']

Foreach loop that loops through $_POST data instead of static isset($_POST["name"]......)

So here I am again trying to find better ways of doing things. 90% of tutorials do things the normal way below:
if (isset($_POST['name']) && isset($_POST['password'])) {
// Does some stuff...
}
It is fine but it does seem too static since I prefer something far more dynamic. For example lets say looping through all $_POST arrays within a contact form. This way I can change the name or the fields to whatever I want or add more...my code will always handle the rest.
I know a foreach loop would come in handy but, as someone new to the world of programming and php I thought you could show me how something like this is done. So how do I replace the above with a for loop? I am not sure where to start.
try this:
$check=true;
if(isset($_POST)){
foreach($_POST as $key=>$value){
if(!isset($_POST[$key]){
$check = false;
break;
}
}
}
based on $check you can verify if it was properly sent or not.
Another approach is to have a sort of verification because it is possible you might not get the key in $_POST
$keys =array("input1","input2");
$check=true;
if(isset($_POST)){
foreach($keys as $input){
if(!array_key_exists($input,$_POST)){
$check = false;
break;
}
}
}
Well you could try something like this :-
<?php
$inputNames = array("input1","input2");
foreach($inputNames as $input)
{
if (isset($_POST["$input"]) && isset($_POST["$input"])) {
// Does some stuff...
}
}
?>
Make an array with the names of all your input tags, and then simply do a foreach between them. In this way, you always only need to edit the names array.
You can always use foreach loop like that:
foreach($_POST as $key => $value){ echo '$_POST["'.$key.'"] = "'.$value.'"'}
But remember, that anyone, can modify your form, prepare some post statement and send data that can create little mess with your code. So it`s good way to validate all fields.
Dynamic validation is of course possible, but you need to do it right!

array_intersect() Argument is not an array

I have developed this small code to check if 2 text, one from a database and the other from an outside imput have common words.
The problem is that I get a message "Argument is not an array".
I cannot see where is the problem.
I also need to check if the 2 messages if should have the same words are in the same sequence.
Please help to understand where is the mistake.
Thanks
$checkMsg=strip_tags($_POST['checkMsg']); // message from input form
$message // message from database
$MsgWords = preg_split("/[\s,]+/", $checkMsg);
if(!empty($checkMsg)){
foreach ($MsgWords as $Neword)
{ $Neword = trim($Neword);
echo " $Neword";
}
$word = preg_split("/[\s,]+/", $message);
foreach ($word as $currentWord)
{
$currentWord = trim($currentWord);
echo " $currentWord";
}
$intersect=array_intersect( $Neword ,
$currentWord);
echo" Your common words are: $intersect";}else{echo "No common words";}
As others have said you're comparing the strings not the array. Your code should be something like this (you'll have to probably change this a little its just an example)
$checkMsg=strip_tags($_POST['checkMsg']); // message from input form
$message // message from database
$MsgWords = preg_split("/[\s,]+/", $checkMsg);
if(!empty($checkMsg)){
$intersect=array_intersect($message,$MsgWords);
if (count($intersect)>1) {
//only show output if there are matches
echo "Words in common are:<br />";
foreach ($intersect as $Neword) {
$Neword = trim($Neword);
echo $Neword."<br />";
}
} else {
echo "There are no words in common";
}
}
Okay, so firstly you're looping through the two arrays and changing the value, but the way you have it, you are just changing a temp copy of the value, not the value in the array. To do that, you need to use the & sign in the foreach() to tell it to use a reference variable in the loop, like this:
foreach ($MsgWords as &$Neword) { //added the & sign here.
$Neword = trim($Neword);
}
Do the same thing to the other foreach() loop too.
Secondly, your array_intersect() call is looking at the single strings, not at the whole arrays. You need it to look at the arrays:
//your incorrect version:
$intersect=array_intersect( $Neword, $currentWord);
//corrected version, using your variable names.
$intersect=array_intersect( $MsgWords, $word);
That should solve your problems.
[EDIT]
Also, note the array_intersect() outputs an array (ie the array of the intersection between the two input arrays). You can't use echo() to print an array directly. If you try, it will just show the word 'Array'. You need to convert it into a string first:
//your incorrect code.
echo "Your common words are: $intersect";
//corrected code:
echo "Your common words are: ".implode(',',$intersect);
I would also note that your coding style is very messy and hard to read. I strongly recommend trying to tidy it up; follow some kind of indentation and variable naming rules. Otherwise it will be very hard to maintain.

How do I use multiple list()/each() calls in a while loop?

I'm working with 3 different arrays (although I'm only testing with two for the time being) and I'm trying to process the arrays on $_POST. I'm currently using:
while(list($key_member,$member)=each($_POST['member_ids'])
&& list($key_amount,$amount)=each($_POST['payment_amounts']))
{
echo "MEMBER: $member<br>";
echo "AMOUNT: $amount<br><br>";
}
If I use one list() on either array it will print the info for that particular item. However, if I attempt to use multiple list() commands in the while, only the last list()ed item gets filled properly. Is list() doing some trickery in the background that's preventing it from working in a while loop?
Obviously the "easy" solution would be to use an index and simply force the issue, but I prefer enumerating -- and I'm honestly just curious as to
What am I doing wrong, and/or what is "broken" with list()?
bug? dunno.
here's a workaround.
while(list($key_member,$member)=each($_POST['member_ids'])){
list($key_amount,$amount)=each($_POST['payment_amounts']);
echo "MEMBER: $member<br>";
echo "AMOUNT: $amount<br><br>";
}
You could extract each array's keys using array_keys(), which produces an indexed array, then keep separate loop counters for each array:
$member_ids = array_keys($_POST['member_ids']);
$amounts = array_keys($_POST['payment_amounts']);
$mi = 0;
$am = 0;
while(1) {
...
$mi++
$am++;
if (count($member_ids) >= $mi) && (count(amounts) >= $am) {
break;
}
}
&& is evaluated in a short-circuit manner, the first statement to return false jumps out of it. In your case it stops to iterate as soon as the first array is at its end. list should work fine here, as it's a language construct which assigns variables.

PHP verify if every $array[$key] is not empty

So, i have this code that seems to be doing the mechanical work correctly, avoiding to write on tables if one or more fields from a form are left empty, but the echos and messages aren't working as they supposed to:
SOLUTION TO THE PROBLEM:
I don't believe this will be useful to anyone, but just for the record, the solution is simple:
$campos = array('nome','morada','email','telemovel','codigopostal','vat');
foreach ($campos as $key => $campo) {
$campos[$key] = $_GET[$campo];
if(!isset($_GET[$campo])|| empty($_GET[$campo])){
header("Location: ../index.php?erro=".$campo);
$verifica=FALSE;
die();
}else{
$verifica=TRUE;
}
}
This will give me some problems, not what i really wanted but solves the logical problems i was having. Thanks to you all guys.
$campos = array('nome','morada','email','telemovel','codigopostal','vat');
foreach ($campos as $key => $campo) {
$campos[$key] = ($_GET[$campo]);
while(list($key, $campo)= each($campos))
if(!isset($_GET[$campo])|| $_GET[$campo]==""){
echo("não preencheu um dos campos");
$verifica = FALSE;
die();
}else{
echo $_GET[$campo]." \r\n";}
$verifica = TRUE;
}
if($verifica==TRUE){
some irrelevant code.
}
As i said, the code itself is working flawlessly, BUT if i only left 2 empty fields on the form, the echo $_GET[$campo] will be working even though the variable $verifica will be set as FALSE
AN HINT:
One of the fields is making the code to fail, is the second one, so, if i do this:
../phcexport.php?nome=myname&morada=&codigopostal=postcode&email=#.com&vat=12312­3&telemovel=00800
And ignore the second value from the array, the code will work like a charm, i can try as many combinations as i can as long as i left the second field empty, it will work properly, giving me the error "some field is empty", in this case i know it is, the "morada" is empty, and if i fill it in the code says "its ok, all filled in" BUT the "morada" should be the last to be filled so the code works. Funny... (I'm sorry about all the text to describe the problem, i'm Portuguese)
EDIT2: For the rest of the code i need to use $campos[$key], so attribute a key to the arrays is essencial.
The problem is that you reset $verifica in the else. So regardless if you set it once to FALSE, the last foreach iteration will determine the outcome. But you can "simplify" the whole approach to:
$verify = array_search(0, array_map("strlen", $campos)) === false;
This simply checks for the string length of each array entry. If none of them is 0, then the expression will return true for $verify;
instead of doing $_GET[$campo]=="", you can maybe use the empty function :
empty($_GET[$campo])
This should address all problems related to different data types.
Your also maybe running in a problem because you're using a variable named $campo in two different loops, try changing the variable name in the while loop to see if it works better.
Check the exact value of $campo that is causing the incorrect behaviour, then consult this table to make sure you are using the right kind of comparison
http://www.php.net/manual/en/types.comparisons.php#types.comparisions-loose
try following solution, empty fields can not pass the test
<?php
$campos = array('nome', 'morada', 'email', 'telemovel', 'codigopostal', 'vat');
$verifica = TRUE;
foreach ($campos as $campo) {
if (!isset($_GET[$campo]) || empty($_GET[$campo])) {
echo "não preencheu um dos campos" ;
$verifica = FALSE;
break;
} else {
echo $_GET[$campo] ."\r\n";
}
}
if ($verifica == TRUE) {
// some irrelevant code.
} else {
die();
}

Categories