I have an Array $column with two values: value and sum.
The array is ordered based on sum.
I want to store the first sum that is above 10 and stop the array so it is not storing the other values which are later in the array.
I tried different things including break; but this influences the rest of the script below it or is not working.
Does anyone know how to solve this?
<?php
foreach ($column as $value => $item) {
if ($item['sum'] >= 10) {
echo "First value above 10";
// store value in Database and stop string so next values won't go into DB
} else {
echo "lower than 10 and do nothing";
}
echo $item['value'] . " - " . $item['sum'] . " <br />";
}
?>
You are on the right track. If I understand you still need to keep looping even after the fact you have found your first value over ten. You just need to store a boolean flag in that case keeping track of the fact whether or not you already found one:
<?php
$itemFound = false;
foreach ($column as $value => $item) {
if (!itemFound && $item['sum'] >= 10) {
echo "First value above 10";
// query on connnection here
$itemFound = true;
}
echo $item['value'] . " - " . $item['sum'] . " <br />";
}
?>
If you need help with the database query, you are going to need to give more information about your local configuration.
Related
With the foreach loop, I wanna count how many results are displayed. For example, if it's displaying
Jack Ane
Steve Jobs
Sara Bill
I want to echo that there are 3 results.
Likewise, if it's like
Marc Kil
Bill Smith
I want to echo that there are 2 results.
It's a bit tricky for me becasue this is my code:
<div>
<?php
$container = array();
if (is_array($row))
{
foreach ($row as $data) {
if(!isset($container[$data->first_name . $data->last_name])) {
$container[$data->first_name . $data->last_name] = $data;
echo $data->first_name . " " .$data->last_name . "</div>";
}
}
}
?>
</p>
</div>
How exactly would I be able to do that? Since these values are coming straight from the database, I was thinking of doing a database count but there are duplicate values in the database since I'm logging the views of users with the first and the last name. So when I try to do it, say for example there are 20 Jack Ane in my database. Then it shows me all of the 20 Jack Ane's instead of just one because I just want it once.
Sorry if it's confusing.
Thanks.
I traditional use the count() to do that if you dont use any :
foreach ($row as $data) {
if(!isset($container[$data->first_name . $data->last_name])) {
$container[$data->first_name . $data->last_name] = $data;
echo $data->first_name . " " .$data->last_name . "</div>";
}
}
echo "Results: " . count($row);
Hope that help you.
I suggest you to rewrite your query. If you will do this in right way, you will get faster solution, with no needs to new array and unnecessary "isset" checks.
The reason you get duplicated data from query may be:
1 - Wrong query logic
2 - Query is OK, but you need to use DISTINCT or GROUP BY to remove duplicates
If you use PDO, you can then get number of returned rows just by using rowCount() method
$sql="SELECT * from table WHERE blablabla";
$result = $this->db->query($sql);
$result->rowCount(); // here
Then you can fetch $result->fetchAll(); and print data.
You can to do a SELECT DISTINCT or a GROUP BY across the two columns to have the database do the work and eliminate the duplicate checking in your PHP. To do this you can use something like the following:
SELECT DISTINCT first_name, last_name FROM users;
SELECT first_name, last_name FROM users GROUP BY first_name, last_name;
DISTINCT is more succinct while GROUP BY supports more flexibility.
In your example, since you are building an associative array, you can just do a count() after the loop, but you will have cleaner code if you have the database do it:
$count = count($container);
You could do an easy variable that increments inside your foreach that gives you the exact count, then use the variable to create actions depending on it's value. Because if you count the container and you wish to filter out the results inside the container, you won't get the filtered amount.
<?php
$container = array();
if (is_array($row))
{
$count = 0;
foreach ($row as $data) {
if(!isset($container[$data->first_name . $data->last_name])) {
$container[$data->first_name . $data->last_name] = $data;
echo $data->first_name . " " .$data->last_name . "</div>";
$count++;
}
}
}
if ($count > 0) {
echo "There were $count results.";
}
?>
use:
echo "Results: " . count($container);
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
I have a table named getinvolved and in this table there are various fields and values, obviously. One such is named The Route and contains text separated by commas. For the sake of this we'll say they are Spot 1, Spot 2, Spot. Yes the spaces matter.
Now, in my code I first break this value up into an array based on the commas: $route = explode(",", $row['Content']); Content is the name of the row that contains the Spot 1, Spot 2, Spot text value. This all works fine, I have echo'd this and it appears perfectly.
Next comes the tricky bit, I have multiple other entries that are instead of being labelled The Route are instead labelled Route. This is an entry for each possible spot, while the current route is Spot 1, Spot 2, Spot it could always change to Spot 2, Spot 1, Tops.
Each possible entry has it's own row: Name, Type, Content. Type is where Route is set, Name is the name of the spot, and Content contains a Google Maps URL to show the spot in Google Maps Street View.
What I'm trying to do is take my array $route[] which currently contains Spot 1, Spot 2, Spot and check those values against all others. I've created a separate array $echoroute[] and this contains the actual route with all the information.
My code is as follows:
$sql = mysqli_query($link, "SELECT * FROM getinvolved WHERE Type='Route'");
$echoroute = array_fill(0,count($route),""); #Gives $echoroute[] 3 empty elements as $route will always contain 3 elements at the moment.
$i = 0;
$max = count($route);
if($sql)
{
foreach($route as $ii)
{
while($row = mysqli_fetch_assoc($sql))
{
if($row['Name'] == $ii)
{
$echoroute[$i] = "<a href='" . $row['Content'] . "' target='_blank'>" . $row['Name'] . "</a> --> ";
echo $i . " / " . $max . "<br />";
$i+=1;
if($i==($max)) {break 2;} else {break 1;}
}
}
}
}
I'm unable to figure out why but at present during running this code all that happens is it will go through the if as $sql passes, it enters the first and second while loops and then gets to the if($row['Name'] == $route[$i]) part. Here it seems to work fine until it actually enters the if statement (the value in $row['Name'] is equal to the one in $route[$i]).
$total is increased as where I ask it to echo it does, but only once. The code ends and displays the following:
0 / 3
3
The 1 represents the $total variable, which should go through 3 times according to while($total<$max).
The / is me adding a separator for ease of reading.
The 3 is the $max variable, or count($route), the total number of spots included in the $route array.
And finally the trailing 3 is a count() function of $echoroute letting me know there are 3 elements in that array.
Ultimately, my question is, why does $total never get to 2 and finish the loop as I would require?
This took a while to write, so I hope you understand I've put a bit of thought into this, I wrote this a while ago, and it needs some updating and this is where I am currently at.
EDIT:
Have narrowed this down now! Using several echo functions, it appears that the last run through starts, but only makes it as far as the while statement. It never actually enters the while statement. Currently I have two results echo'd and the last result just so happens to be at the bottom of the table. It's the last one to be used before the while($row = statement ends of it's own accord. Am I trapping the while statement or do I need to release it or something? I'm really confused and so close to having the final piece!
You initialize $echoroute with count($route) elements (3 in your example).
You loop over a condition and increase value of $i and $total if a condition is met.
At this point, into the while loop where $total and $i values are 2 ( while condition is met 2 < 3 ) and if they enter the if condition you get 3 value for $i and $total and if you echo $echoroute[$i] then you've got an error, because $echoroute is a 3 element array and you are pointing to a fourth element (remember array indices start from 0 ).
I think this is why you are not getting you expected output.
i'd write it this way, since there is chance (following Moor laws) that the loop on $total never ends
$sql = mysqli_query($link, "SELECT * FROM getinvolved WHERE Type='Route'");
$echoroute = array_fill(0,count($route),""); #Gives $echoroute[] 3 empty elements as $route will always contain 3 elements at the moment.
$i = 0;
$total = 0;
$max = count($route);
if($sql)
{
while($row = mysqli_fetch_assoc($sql))
{
if($row['Name'] == $route[$i])
{
$echoroute[$i] = "<a href='" . $row['Content'] . "' target='_blank'>" . $row['Name'] . "</a> --> ";
$i++;
$total++;
if ($total>$max) break;
echo $total . " / " . $max . "<br />" . $echoroute[$i] . count($echoroute);
}
}
}
I'm trying to code an array that displays a certain set of products depending on the gender of the logged in user. The arrays not really the problem but the parts where I'm going to have to check the database then create the conditional statement from the results is the main problem i think.
Here is my code:
<?php
include"config.php" or die "cannot connect to server";
$gender=$_POST['gender'];
$qry ="SELECT * FROM server WHERE gender ='$gender'";
$result = mysql_query($qry);
$productdetails;
$productdetails1["Product1"] = "£8";
$productdetails1["Product2"] = "£6";
$productdetails1["Product3"] = "£5";
$productdetails1["Product4"] = "£6";
$productdetails1["Product5"] = "£4";
$productdetails2["Product6"] = "£8";
$productdetails2["Product7"] = "£6";
$productdetails2["Product8"] = "£5";
$productdetails2["Product9"] = "£6";
$productdetails2["Product10"] = "£4";
if (mysql_num_rows($result) = 1) {
foreach( $productdetails1 as $key => $value){
echo "Product: $key, Price: $value <br />";
}
}
else {
foreach( $productdetails2 as $key => $value) {
echo "Product: $key, Price: $value <br />";
}
}
?>
You if statement is wrong. = is an assignment operator, you should use a comparison operator like == or ===
What happens with the current code?
Some tips:
First try echoing $gender, to make sure it is getting through. It is submitted through post, what happens if nothing is being posted? Where is this coming from? You should try to use get instead. This seems like something you'd give someone a link to therefore post doesn't make sense here. You could always have both, and just get post if it exists otherwise use get otherwise default to 'male' or 'female' depending on your audience.
Next, what is your query outputting? It might be empty at this point if gender is not giving anything back. It seems like you are querying for all rows where gender = whatever was passed, but then your if statement is asking was there anything returned? Then all you are doing is going to the arrays, but you shouldn't be doing that you should be outputting what you got from the DB. Assuming you do actually have products in the table called server you should do something like this:
$products = mysql_query("SELECT * FROM server WHERE gender ='$gender");
while($product = mysql_fetch_array($products)){
echo $product['name'] . " " . $product['price']. " " . $product['gender'];
echo "<br />";
}
On that note. You should really call your table something else, like product not just "server" unless by server you mean a table filled with instances of waiters or computer hardware.
I've been pulling my hair out on this one all afternoon. Basically, I have a long table of values (stored in SQL) and I want to go through the entire table and count the number of times each value shows up. I've called the values "pid" integers.
The best way I thought of to do this was to create an array with the PIDs as the key of the array, and the number of times each PID has occured in the table as the value at that key. Then go through the entire list and either add the PID to the array if it didn't already exist, or increment the click value if it already exists. The goal is to then figure out which PID has the highest number of clicks.
It sounds straightforward, and it is! I think I must have an error in my syntax somewhere because everything seems right. This is my first time working with arrays in PHP so be nice :)
Thanks so much!
$tabulation = array();
while ($row = mysql_fetch_array($result)) {
$pid = $row[1];
//if this post isn't in the tabulation array, add it w a click value of 1
if ( !isset( $tabulation[$pid] ) ){ array_push( $tabulation[$pid], 1 ); }
//if this post is already in the tabulation array, incrment its click value by 1
else {
$t = $tabulation[$pid]; $t++; $tabulation[$pid] = $t;
}
}
$highestClicksValue = -1;
$highestClicksPID = -1;
foreach ($tabulation as $pid => $clicks){
if ($clicks > $highestClicksValue){ $highestClicksPID = $pid; }
printf("PID: ". $tabulation[$pid] . " clicks: " . $tabulation[$clicks] . "<br />");
}
I know you're looking for a PHP answer, but have you considered that this is what SQL is best at?
select pid,count(*)
from theTable
group by pid
order by count(*) desc
Just a thought...
Why are you using the array key and value as keys for $tabulation in the last foreach?
This should work...
$tabulation = array();
while ($row = mysql_fetch_array($result)) {
$pid = $row[1];
//if this post isn't in the tabulation array, add it w a click value of 1
if ( ! isset( $tabulation[$pid] ))
$tabulation[$pid] = 1;
//if this post is already in the tabulation array, incrment its click value by 1
else
$tabulation[$pid]++;
}
arsort($tabulation);
$highestClicksValue = reset($tabulation);
$highestClicksPID = key($tabulation);
foreach ($tabulation as $pid => $clicks){
print("PID: ". $pid . " clicks: " . $clicks . "<br />");
}