Wrong parameter count for max() - php

I'm trying to show the max value of column teams from mysql. Above the while loop I've selected teams from my mysql table and then as you can see in my code below I have included max($teams) - but it is returning an error? Where am I going wrong.
while ($rows = mysql_fetch_assoc($result)) {
$teams = $rows['teams'];
if($teams > "1") {
echo '<div class="bestbettor">'.'<span class="redtext">'."Bettor: ".'</span>'. $rows['username'].'</div>';
echo '<div class="bestbettor">'.'<span class="redtext">'." Bet: ".'</span>'.max($teams). " team accumulator".'</span>'.'</div>';
}
}

you must pass an array to max().
$teams = $rows['teams']; // saves as string.
if your teams were delimited by a comma then you could do something like:
$teams = explode(",",$rows['teams']); // saves as array
then you could do max()

If one parameter is given to max() it has to be an array of values of which max() will return the highest value in that array. It seems like you've just given it a single string.

Related

Array_sum of a fetch_row

I am attempting to get the summation of a set of float values in a column of a table. I did a select query that pulls five sets of integers. A while function with a fetch_row is used to get the array. I use a foreach function to get the sum, however, the echo or printf does not give me one single variable. Instead I get an ever increasing value as each integer is added to the summation of the values before it. I have tried the array_sum, which doesn't work either. Please help! I have looked at every possible question in Stackoverflow.
<?php
//Check if at least one row is found
if($results2->num_rows > 0) {
//Loop through results and fetch as an array
$total = 0;
while($rows = $results2->fetch_row()){
foreach($rows as $sum)
$total += $sum;
printf($total.'<br/>');
}
}
?>
You're printing the total inside the loop, so you see all the subtotals. If you just want to see the final result, print it when the loop is done.
foreach ($rows as $sum) {
$total += $sum;
}
printf("%d<br/>", $total);
Also, when you use printf, the first argument is a format string. The values come after, and they get substituted into the format.
You can also use array_sum:
printf("%d<br/>", array_sum($rows));
Note that these are summing up all the columns in each row, not a single column in the whole table.

PHP for each result excluding values from array

I queried a table into an array but I would like to exclude certain values from one of the columns as to spits out each row. For example.
foreach($results as $row)
{
if($row['sku'] != "sku-1"){
echo $row['sku']." ";
}
}
So lets say the table has 4 rows with a value of sku-1, sku-2, sku-3 and sku-4. The above Foreach code would echo out "sku-2 sku-3 sku-4". Is there a way I can make an array of what values I would want to exclude? Like I'd have an array called $skuarray = "sku-2, sku-4" and instead of
if($row['sku'] != "sku-2" || $row['sku'] != "sku-4"){
have that $skuarray in there where it'll echo "sku-1, sku-3"? Thanks!
EDIT
I could somehow exclude it when I query it. I'm querying it from table SKUTABLE and the column is SKU. The problem is I need to exclude unique values from column SKU so I thought if there was an easy way to just throw in all the ones I want to exclude into an array that'd be great.
You could use the array_diff(array1, array2, [...arrayN]) function, which takes at least two arrays, and returns an array of only those values of array1 which are not in any of the subsequent arrays. Example:
$input = array(0=>'sku-1',1=>'sku-2',2=>'sku-3',3=>'sku-4');
$exclude = array('sku-1','sku-3','sku-4');
$result = array_diff($input, $exclude);
print_r($result);
Will print
array(1=>'sku-2');
Use in_array:
$skuarray = array("sku-2", "sku-4");
foreach($results as $row)
{
if(!in_array($row['sku'], $skuarray)){
echo $row['sku']." ";
}
}
You can use array_filter in combination with in_array.
$filtered_results = array_filter($results, function ($row) {
return in_array($row["sku"], $skuarray) === false;
});

How to find out automatically the numeric index of an specific MySQL column in PHP?

I´m new to PHP and SQL and it´s the first time I post here, hope I do it right =)
I need to find out the numeric index from an certain field in my database. Thing is I´m not done with the database structure yet, so for this specific field I´d like to have it automated so I won't have to change the code every time I add or remove columns.
I also need it to have BOTH index types so I can call the columns by name in part of the code and by index for automated parts of it.
I´ve managed to achieve the result I wanted trough an very ugly code, because all the array_search and array_keys I´ve tried didn´t work out for some reason.
Here is the snippet of my working but ugly code. Do you have an more elegant solution?
Thanks in advance for your answers, and for all I´ve learned so far from reading other peoples questions!
$dadosRes = mysqli_query($con, "SELECT * FROM Alunos WHERE Id=1");
$student = mysqli_fetch_array($dadosRes) or die(mysql_error());
$c = 0; // This block is to find out where the column "cont1" is and assign it to $cont1
$d=array_keys($student);
$cont1=0;
foreach ($student as $a=>$b){
if ($a==='cont1') {
$cont1=$d[$c-1];
}
$c++;
}
for ($i=$cont1; $i<$cont1+12; $i+=3) { // Displays the students contacts, each in up to 3 rows
if ($student[$i]) {
echo "<p><ul><li>".$student[$i]."</li>";
if ($student[$i+1]) echo "<li>".$students[$i+1]."</li>";
if ($student[$i+2]) echo "<li>".$students[$i+2]."</li>";
echo "</ul></p>";
}
}
Finding the numeric index:
$student = mysqli_fetch_array($dadosRes,MYSQLI_ASSOC) or die(mysql_error());
$numericIndex = array_search("cont1",array_keys($student));
Giving MYSQLI_ASSOC will force the query to fetch only the associative keys; otherwise it will give you both numeric and associative array.
PHP function, array_search in this case, requires the third parameter set to TRUE:
<?php
$dadosRes = mysqli_query($con, "SELECT * FROM Alunos WHERE Id=1");
$student = mysqli_fetch_array($dadosRes, MYSQLI_BOTH) or die(mysql_error());
$student_keys = array_keys($student);
$cont1 = $student_keys[array_search("cont1", $student_keys, true) - 1];
for ($i=$cont1; $i<$cont1+12; $i+=3) { // Displays the students contacts, each in up to 3 rows
if ($student[$i]) {
echo "<p><ul><li>".$student[$i]."</li>";
if ($student[$i+1]) echo "<li>".$student[$i+1]."</li>";
if ($student[$i+2]) echo "<li>".$student[$i+2]."</li>";
echo "</ul></p>";
}
}
?>
MYSQLI_BOTH is used in the mysqli_fetch_array function because first the array is searched for the column name, then later the array is looped over with numeric indexes. This results in the $student array having integer 0 as the first element and therefore causing array_search to choke. Adding true as the third parameter causes a === comparison unchoking the function. :) (Explanation: PHP array_search consistently returns first key of array )

Looping through resultings record and getting duplicates in foreach

So I am trying what I feel is a simply loop through a record result. My query returns one row of data. I am attempting to simply pull the value of each row from the returning record into a variable called $questions. However, my var $questions when printed out has duplicates in every space. It should read something like Bob|Ted|Joe|Sally and instead it is reading Bob|Bob|Ted|Ted|Joe|Joe|Sally|Sally. Why is the code below running twice in the foreach loop?
while ($row = mssql_fetch_array($result)){
foreach ($row as $col => $value) {
$questions.=$value."|";
}
}
echo "Questions: ".$questions."<br/>";
Here is all you need to do:
$questions = "";
while ($row = mssql_fetch_array($result)){
$questions .= $row['fieldName']."|";
}
echo "Questions: ".$questions."<br/>";
The foreach() in addition to the while() is unnecessary.
The mssql_fetch_array according to PHP doc:
In addition to storing the data in the numeric indices of the result
array, it also stores the data in associative indices, using the field
names as keys.
The result includes a normal array [0...n] with one element for each column, but also an associative array where each value is represented by a key named after the column name.
So if your first column is Id, you could get id from a row in two ways:
$id = $row[0];
# or you could do this
$id = $row['Id'];
This is why you get each value twice when looping through row.

while loop into in array

What am I trying to do is collect data from a while loop, store it into a variable. Then later in my code I see if some variable is equal to one of the values in the array and then to echo out the two other column values I got from the while loop but equal to the row that the value came from. I have tried a bunch different things and am so close but cant get it exactly.
while($row = mysql_fetch_assoc($query)){
$team[] .= "{$row['team']}";
$winslosses .= "({$row['wins']} - {$row['losses']})";
}
this returns something like
$team = (bears, badgers, wildcats)
$winslosses = ((42-24), (55-23), (32-21))
Then later in my code I want to see if its equal to a value in the array then echo $winslosses.
if(in_array(bears, $team) ) {echo '$winslosses';}
This shows all the wins and losses from each team. I want it only show me the record of the bears.
Any help would be great.
You can use array_search() to get the index of an item in an array. You can then use that index when querying $winlosses:
$team = array(bears, badgers, wildcats);
$winslosses = array("(42-24)", "(55-23)", "(32-21)");
$key=array_search(bears, $team);
echo $winslosses[$key]
results in:
(42-24)
Your best bet would be to store them in an associative array.
while($row = mysql_fetch_assoc($query)){
$winslosses[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Hope this helps
Your main problem is that you currently have $winslosses as a string, not an array, so you can't easily pull out the win/loss record for just one team.
There are several ways you could do this. The one that seems easiest to me would be to put it together as one array up front.
Something like...
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Then later on...
if(array_key_exists("bears",$teams)) {
echo $teams["bears"];
}
Or even better, store the wins/losses as a sub-array, so you have structured data that you can format however you want later on.
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = array("wins" => $row['wins'], "losses" => $row['losses']);
}
echo $teams['bears']['wins']; // for example
Use associative array:
while($row = mysql_fetch_assoc($query)){
$team[] = {$row['team']};
$winslosses[$row['team']] = "{$row['wins']} - {$row['losses']}";
}
Then retrieve it like this:
if(in_array(bears, $team) ) {
echo $winslosses['bears'];
}
As a matter of fact, if you do not need the names of the teams in a separate array, you can just use one associative array and then retrieve it.
if (array_key_exists('bears', $winslosses)) {
echo $winslosses['bears'];
}

Categories