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);
}
}
}
Related
I have a 'Pricing History Table' based off MySQL table.
Because we have a lot of alike listings, a lot of these entries appear as duplicates, aside from of course the ItemID.
Here's how I'm currently weeding out duplicates (not really duplicates, but similar listings that have the same SKUs, Y-m-d Date, Previous Price, New Price and Sales Channels. -- and also trying to get a count (see $count logic below) of how many alike/"duplicate" rows were found)
$inventoryhistoryrows = array();
$skuarray = array();
foreach ($pricehistoryarray as $ph_key => $ph_values) {
// defining variables, etc.
. . . . .
$ph_sku_timestamp = $inventoryskus . ' ' . $ph_timestamp . ' ' . $ph_previousprice . ' ' . $ph_newprice . ' ' . $ph_channel;
if (in_array($ph_sku_timestamp, $skuarray)) { continue; }
$skuarray[] = $ph_sku_timestamp;
if(isset($prev)) {
$newcount = $count - $prev;
$prev = $count;
}
else {
$prev = $count;
$newcount = $count;
}
$inventoryhistoryrows[] = array($newcount, $ph_itemid, $inventoryskus, $ph_previousprice, $ph_newprice, $ph_channel, $ph_timestamp);
This is working.... but my $newcount is always one row ahead!
Here's an illustration of output in table:
Note the arrows on the far left side. The $newcount variables are correct but the entire first column needs to moved up by one row.
Meaning, 1 should be removed from the first row. 3 Should be in the first row. 17 Should be in the second row.
I can of course see that the reason why 1 is showing up in the first row is due to this statement
else {
$newcount = $count;
}
Meaning it will always return 1 for the first row, as prev does not exist. But I simply put this there as I was unsure of a proper way to get the data as I wanted.
Anyone have any ideas on how I can do this? In the initial foreach loop for $pricehistoryarray (I suppose this would be the better solution), or a relatively simply method for shifting up only the first column once the $inventoryhistoryrows array is constructed?
Apparently this might be better off in the MySQL Query (see comments)
This seems to be working
SELECT COUNT(*) as count
, itemid
, previousprice
, newprice
, channel
, timestamp
FROM listing_price_history
WHERE listing_price_history.timestamp > DATE_SUB(now(), INTERVAL 30 DAY)
GROUP
BY previousprice
, newprice
, channel
, DATE(timestamp)
ORDER
BY listing_price_history.timestamp DESC
Big thanks to #Cid for the guidance
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.
I run a query, and loop through it modifying one of the fields with the code below. I only need the modified number for a short time, and do not need it to go back to the database. This works correctly, and using the echos printed out the expected values.
while ($d1 = mysqli_fetch_array($d1_query))
{
echo "Before: " . $d1['d1_name'] . ": " . $d1['d1_earn_rate'] . "<br>";
if ( $e1['e_id'] == $h1['e_id'] )
$d1['d1_earn_rate'] = $d1['d1_earn_rate'] * 1.2;
echo "After: " . $d1['d1_name'] . ": " . $d1['d1_earn_rate'] . "<br><br>";
}
Afterwards, I want to calculate the total of a subset of the results. I use mysqli_data_seek to reset the counter to the first row, so I can loop through it. However, when I do, it calculates the total based on the original numbers in the query, not the revised ones.
I have used msqli_data_seek previously with no issues, but this is the first time I have modified data in the results before trying to loop back through it. I don't understand why I'm losing the data.
mysqli_data_seek($d1_query,0);
$counter = 0;
while ($counter < 15)
{
$counter++;
$d1 = mysqli_fetch_array($d1_query);
echo $d1['d1_name'] . ": " . $d1['d1_earn_rate'] . "<br>";
$total_earn_rate += $d1['d1_earn_rate'];
}
You appear to be thinking way too deep here. The matter is pretty simple:
the MySQL server holds a result set in its memory, the result of your previous query
mysqli_fetch_array pulls the data from the MySQL server into PHP's memory and returns it
you're assigning that fetched data to $d1
you're manipulating $d1
you reset MySQL's internal pointer of the result set and repeat the above process
At no point are you manipulating the result set that is held by the MySQL server, and you're always pulling data afresh from said MySQL result set via mysqli_fetch_array. Every time you call that function you'll get the unmodified data from the result set held by MySQL.
I'm working on a search system for my database where I break the search phrase into individual search words, search my mySQL database keyword table for any occurrence of those words, and then output a list of IDs associate with the keyword.
I want to add those ID's to a new array that will also contain a count value and (from a new query) the name of the place belonging to the ID, resulting in:
array(ID, count, name)
For each search word I want to go through this process and if the ID is already in the above array I want to increase the count value and if not, I want to add it with a count value of 1.
When the array is built and all the counting is done, I want to sort it by count and then name, and then output the results.
I've programmed PHP for quite some time but I've never been good with building and manipulating arrays so any help related to building, searching, editing, and sorting a 3-column array is appreciated.
Here's some code below where I'm just trying to insert data into the array and spit it out, which obviously doesn't work:
<?php
$id = 5;
$count = 1;
$name = "PlaceName1";
$arrayPlaces = array($id, $count, $name);
echo "5: " . $arrayPlaces[5] . "<br />";
?>
<?php
$id = 5;
$count = 1;
$name = "PlaceName1";
$arrayPlaces = array(
$id => array(
'count' => $count,
'name' => $name
)
);
echo "5: " . $arrayPlace[5]['name'] . "<br />";
?>
I have a table in phpmyadmin that stores an 'id' (auto inc), 'title' and a 'date'.
I have a webpage where I display the 10 latest items (I simply order by ID).
On that page I print the title and the date. My wish is to also display the number of the posted item, so the first posted item is 1, the second is 2, etc. I cannot simply print the ID from the database because if I delete a row, the numbers aren't straight anymore.
My idea was to put all the data in an array but I have no clue what the best way to do this is and how I could print that item number. So for example when I want to display the 54th item I can easily print $items[54][id] or something and it will show me the number 54 and to display the title I print $items[54][title].
I don't know if there are simpler methods, plus arrays always start at 0, but my items must start at 1.
Besides this page that shows the 10 latest items, there is another page where it gets the title of the item out of the URL. How will I be able to search the title in the array and display the data the same way but only for that requested title?
Thanks in advance!
"SELECT COUNT(id) as cnt FROM mytable";
you can select the count of all database entries.
and then assign it to your iterator
$i = $row['cnt']; // this will hold the ammount of records e.g. 21
// other query
while($row = mysql_fetch_assoc($result)) {
echo $i;
$i--; // this will decrement on every iteration 21, 20 , 19, and so on.
}
First off. I would add a timestamp field to the database and order by that instead as it feels overall more reliable and gives you additional details which may prove handy later.
To create the multidimensional array I would do something like:
$result = mysql_query(...);
$items = array();
while($item = mysql_fetch_assoc($result)) {
$items[] = $item;
}
Now $items[12] for example would give you item number 13 (since it's 0-indexed).
Lastly, to select only the item with a specific title I would use a query which included a WHERE clause, like
"SELECT ... FROM ... WHERE title = '".$title."'"
It's very important to sanitize this variable before using it in the query though.
You can read more about MySQL on a lot of places. A quick googling gave me this: http://www.tutorialspoint.com/mysql/index.htm
You should learn PHP before starting to program in PHP ;) Read and work through the PHP manual and some tutorials!
As to your question it is a simple loop you want to do. One way of doing it as an example.
Fetch the 10 last items from the database in any way you like, following some code, partly pseudo-code.
$markup = '';
for ($i=1; $i<=count($items); $i++)
{
$markup .= 'Item ' . $i . ': ' . $items['date'] . ' - ' . $items['title'];
$markup .= 'read more';
$markup .= PHP_EOL;
}
echo $markup;
I don't know how you print out your data exactly, but I assume there is a loop in there. Simply set a counter that increments by one at every row and print its value.
As for the title search, you'll have to run another query with a WHERE title = '$title' condition, but beware of SQL injection.