How to access all results from Php loop in an if statement - php

I am trying to figure out why I can only access last result from a loop. I have looked at many post on here and I can only find where OPs are asking how to create the loop
If I have a table named shirts and a column named colors
In the colors column the entiries are:
red
blue
green
and in my php page:
$user = new User();
$userid = $user->data()->id;
$choices = array();
if ($colorResults = $db->query("SELECT * FROM shirts WHERE sellerId = $userid")){
if($colorResults->num_rows){
while($row = $colorResults->fetch_object()){
$choices[] = $row;
}
$colorResults->free();
}
}
foreach($choices as $choice){
if($choice->color == 'red'){
echo 'Yes color is red'
} else {
echo 'No color';
}
}
When i display results
Results:
red
blue
green
Heres the problem
if($choice->color == 'green'){
echo 'Yes color is green'
} else {
echo 'No color';
}
This will output successfully
Yes color is green
but if I change the code to:
if($choice->color == 'red'){
echo 'Yes color is red'
} else {
echo 'No color';
}
This result output will echo
No color
If one of the colors is red why will the if statement only see the last result
and how can I access all results to make the if statement true.

First, I think part of the initial confusion is that $choices is an array of objects, not an object itself, so using if ($choices->color == 'red') will get you a
Notice: Trying to get property of non-object
which you may not see depending on your error reporting setting. But at any rate, if you use if ($choices->color == 'anything') you will always get 'No color.' So I assume that if it matches for green then you must actually be using if ($choice->color == 'green/red/whatever') and the other thing is just a typo.
The part where you have it listing all the colors of all the choices is fine (or at least, it was fine when you originally added it before subsequent edits.)
foreach ($choices as $choice) {
echo $choice->color . '<br>';
}
What it sounds like is happening based on the results you are seeing is that you are checking the value of $choice->color after the foreach loop. $choice will remain set after the foreach loop, but it will always be the last value in the loop. Now, I am not sure exactly what you are going for here, but it looks like you want to list all the colors returned by your query and then check if a particular one is included. You could do that like this:
$color_included = false; // The color you're looking for has not yet been found
foreach($choices as $choice) {
echo $choice->color . '<br>'; // List all the colors from your query
// Check if they are the one you are looking for
if ($choice->color == 'red') $color_included = true;
}
// Print the result
echo ($color_included) ? 'Yes color is red' : 'No color';

Related

MySQL/PHP - Comparing columns of rows in array

hope you are well the problem that i am having is comparing two values in a array the (columns) of rows.
Is there a way to just check those columns match as i am only checking two rows or is a for each loop the only way.
I am able to get all the data and place it into an array but the if statement i am using does not work in comparing.
if ($countReport == 2) {
while ($rowReport = mysqli_fetch_assoc($resultReport)) {
$temp_array[] = $rowReport;
}
//if (in_array("Hello, world",array_count_values($temp_array))){
//echo "working";
//}
}
This is the data in the array, the stats column is what i am trying to compare like are both values equal to "hello world".
[{"abcID":"8","stats":"Hello, world","time":"23:30:00"},
{"abcID":"7","stats":"Hi, world","time":"23:16:00"},]
Try like this
<?
foreach($array as $k1=>$v1)
{
echo $k1; //returned abcID
echo $v2 //returned 8
foreach ($array2 as $k2 => $v2) {
echo $k2; //returned abcID
echo $v2 //returned 7
if($k1==$k2 && $k1=='stats')
{
if($v1==$v2)
$newarray[]=$v1; //added if they are equal or do what u want.
}
}
}
?>
EDIT: (this is my duh moment, I was overthinking this problem from the start.)
The logical process (no functions or loops are necessary) if you only have the two rows returned is to do a literal check:
if($temp_array[0]['stats']!=$temp_array[1]['stats']){
echo "no match";
}else{
echo "duplicate";
}
The following one-liners deliver the same outcome, but do so less efficiently....
Here is a one-liner for your condition statement requiring no loops:
Example 1:
$temp_array=array(
array("abcID"=>"8","stats"=>"Hello, world","time"=>"23:30:00"),
array("abcID"=>"7","stats"=>"Hi, world","time"=>"23:16:00")
);
if(sizeof(array_unique(array_column($temp_array,"stats")))>1){
echo "no match";
}else{
echo "duplicate";
}
// displays: no match
Example 2:
$temp_array=array(
array("abcID"=>"8","stats"=>"Hello, world","time"=>"23:30:00"),
array("abcID"=>"7","stats"=>"Hello, world","time"=>"23:16:00")
);
if(sizeof(array_unique(array_column($temp_array,"stats")))>1){
echo "no match";
}else{
echo "duplicate";
}
// displays: duplicate
The breakdown:
sizeof( // count the size of the remaining array
array_unique( // remove duplicates from array
array_column($temp_array,"stats") // array of values where 'stats' was the key
)
)
Come to think of it, there are probably several ways to skin this cat.
Here's another:
if(current(array_count_values(array_column($temp_array,"stats")))==1){
echo "no match";
}else{
echo "duplicate";
}
I'm not sure it's worth going on and on.

How to check for specific value in database and act upon it. Laravel 4.2

I'm kinda new to Laravel, and I'm wondering how I can check for a specific value in the databse? I have 5 different category id's in my databse, and I wanna do a check on the databse and act differently depending on what the category id is.
I'm thinking something like this:
if ($example = Example::where('category_id', '=', '1')->first()) {
echo "The category id is 1";
}
or maybe:
$example = Example::where('category_id', '=', Input::get('category_id'))->first();
if ($example === 1) {
echo "The category id is 1";
}
I also tried other things, based on what I already have working, but cannot seam to get this feature to work.
You can use firstOrFail() method of Laravel like this:
$example = Example::where('category_id', '=', '1')->firstOrFail();
if ($example) {
echo "The category id is {$example->id}";
}
return "error";
The firstOrFail methods will retrieve the first result of the query;
however, if no result is found, a
Illuminate\Database\Eloquent\ModelNotFoundException will be thrown
UPDATE:
For fetching and checking each rows, use all() method and iterate through each rows to get your desired results.
$examples = Example::all();
foreach($examples as $example) {
if ($example->category_id == 1) {
echo "echo here the 1 thing....";
} elseif($example->category_id == 2) {
echo "echo here the 2 thing....";
} else {
echo "something else"
}
}
Hope this helps!

How to filter foreach array for integers

I have a for-each statement based off a php generated query..
I am trying to figure out how I can make sure all the IDDestinations of the records are the same.
For example in my current query I have 2 records with an IDDestination of 12, one record with an IDDestination of 9 and the last is 3.
I know how to do this in the query but I am trying to generate a message to the user if the IDDestinations are not equivalent.
My code so far.
foreach($results as $row) {
$IDDestination =(int) $row['IDDestination'];
if ($IDDestination == $IDDestination){
echo "<script>alert('All Courses Match Destination.');</script>";
} else {
echo "<script>alert('Courses have different Destinations);</script>";
}
var_dump($IDDestination);
}
This is currently just verifying that each record has an IDDestination Present and tells ME All courses Match.
How can I make it so the INTEGERS are equivalent and give me the same message?
Here's one way; use a variable outside your loop to determine if it's ok or not:
$everything_matches = true;
$id = null;
foreach($results as $row) {
// Set it for the first record.
if($id === null)
$id = $row['IDDestination'];
// If the current iteration's ID matches the first record, $everything_matches
// will stay true, otherwise it's false and we should kill the loop.
if($id != $row['IDDestination']) {
$everything_matches = false;
break;
}
}
// Output your message
$message = $everything_matches ? 'All courses match destination.' : 'Courses have different destinations.';
echo '<script>alert("' . $message . '");</script>';

(PHP+MySQL) How can I echo the column name on a specific condition?

I am using PHP 5.4 with a MySQL database.
This database represents a media library. The table I'm dealing with has one column, "Title", with obvious contents, and then a series of boolean columns, representing the availability of that title on a given platform. So a row looks like
TITLE: "Curb Your Enthusiasm: The Game"
PS4: 0
Atari 2600: 1
Dreamcast: 0
And so on.
The PHP code I would like to write be, in pseudocode,
Echo row[0] (title)
Cycle through other cells in the row
If the cell is '0' or NULL, do nothing
But if the cell is '1', echo the name of that column
So the result would be the echoing of
Curb Your Enthusiasm: The Game (Atari 2600, WonderSwan, Saturn)
It's the fourth statement that I can't quite work out. It seems to require the function mysqli_fetch_field, but I'm not sure of the syntax, and nothing I try after googling quite works.
I'd really appreciate any advice or examples someone could offer!
$database = mysqli_connect(SERVER,USERNAME,PASSWORD,'games');
$query = mysqli_query($database,"SELECT * FROM games` WHERE NAME LIKE '%ZELDA%'");
while ($row = mysqli_fetch_row($query)) {
echo $row[0]; // Echo title
for ($i=0;$i<sizeof($row);$i++) {
if ($row[$i] === '1') {
// ???????
}
}
}
Here is some rough untested code that should hopefully get you going.
while ($row = mysqli_fetch_assoc($query)) {
$columns = array(); // this will track the additional columns we need to display
foreach($row AS $column => $value) {
if($column == "title") {
echo $value; // this is the title, just spit it out
continue;
}
if($value == 1) {
// We have a column to display!
$columns[] = $column;
}
}
if(count($columns)) {
// We have one or more column names to display
echo " (" . implode(", ",$columns) . ")";
}
}
Some things to point out:
Using mysqli_fetch_assoc will allow you access to column names along with the values, which is useful here.
Keep track of the columns you want to display in an array first, this makes it easier at the end of each loop to format the output.
Sounds like you can do something like this:
// Simulates DB fetch
$titles = array(
array(
'TITLE'=>'Curb Your Enthusiasm: The Game',
'PS4'=>0,
'Atari 2600'=>1,
'Dreamcast'=>0
),
array(
'TITLE'=>'Curb Your Enthusiasm: The Book',
'PS4'=>1,
'Atari 2600'=>1,
'Dreamcast'=>0
)
);
foreach($titles as $title){
// get supported platforms
$supportedPlatforms = array();
foreach($title as $titleAttribute=>$titleValue){
if($titleAttribute != 'TITLE' && $titleValue == 1)
$supportedPlatforms[] = $titleAttribute;
}
echo $title['TITLE'] . ' (' . implode(', ', $supportedPlatforms) . ')' . "<br>";
}
Try running it here: http://phpfiddle.org/lite/code/pr6-fwt

Adding commas to a loop within a loop

I'm trying to create a list using a loop within a loop. I have 3 tables.
T1: faculty
T2: keywords
T3: facID, keywordID
I've created a select statement to cross join the rows and spit out something like this:
Faculty Name A
keyword-a keyword-b keyword-c
Faculty Name B
keyword-a keyword-d keyword-f
Everything works great except I need to add commas to the keyword list and my code isn't doing the trick. My keywords are still looping through without the comma.
<?php while ($row = mysql_fetch_assoc($result)) { ?>
<?php if ($row['facID'] !== $lastID ) { ?>
<?php echo $row['facname']; ?><br />
<?php $lastID = $row['facID']; ?>
<?php } ?>
<?php $kwords = array();
foreach($row as $k => $v) {
if (strpos($k, 'kword') === 0) {
$kwords[] = $v;
}
}
echo implode(', ', $kwords);
} ?>
Any suggestions? I'm a noob and I'm hoping it's something very obvious!
There seem to be a few issues with your code, so I'll try to address them all.
First, you have a lot of opening and closing <?php> tags, and it's really messing with the readability of your code. Consider keeping as much code as possible contained into a single <?php> code block. For example, instead of this:
<?php if ($row['facID'] !== $lastID ) { ?>
<?php echo $row['facname']; ?><br />
<?php $lastID = $row['facID']; ?>
<?php } ?>
...you can consolidate all of that PHP code into this:
<?php
if ($row['facID'] !== $lastID ) {
echo $row['facname'] . "<br />";
$lastID = $row['facID'];
}
?>
Next, you're not outputting any sort of visual break after echoing out your implode()ed array. This would lead to the next heading being output on the same line as the output of your previous heading. For example, your first two headings will end up like this:
Faculty Name A
keyword-a keyword-b keyword-cFaculty Name B
keyword-a keyword-d keyword-f
Notice how Faculty Name B is at the end of the line of keywords?
Finally, I think the problem you're reporting is that you're getting two keywords that are linked together. For example, if you had two rows of data with the same facility id, one with keywords keyword-a and keyword-b and another with keyword-c and keyword-d, you would see that output visually without a comma between keyword-b and keyword-c.
In other words, instead of this:
keyword-a, keyword-b, keyword-c, keyword-d
...you're instead seeing this:
keyword-a, keyword-bkeyword-c, keyword-d
This is also caused by the lack of a visual break between implodeed lines, but I believe the problem is deeper than that. I believe you want all keywords for a given facility to be shown on a single line, not broken across multiple lines. For that, you need to move where you reinitialize your array so that it gets reinitialized at the same time you switch to a new heading. Try something like this:
$kwords = array();
while ($row = mysql_fetch_assoc($result)) {
if ($row['facID'] !== $lastID ) {
if ($kwords) {
echo implode(", ", $kwords) . "<br />";
$kwords = array();
}
echo $row['facname'] . "<br />";
$lastID = $row['facID'];
}
foreach($row as $k => $v) {
if (strpos($k, 'kword') === 0) {
$kwords[] = $v;
}
}
}
if ($kwords) {
echo implode(", ", $kwords);
}
echo "<br />";
This still isn't the best code, but you can refactor it.
The idea here is that the array gets output and reset every time the facility changes, so that the array encompasses all keywords for that facility and they all get output together, rather than being reported only as part of the database row they were returned with. After the loop completes, you have to manually report the last row since the usual reporting is taken care of within the loop.

Categories