php how to limit the result - php

i have that code, and i want to limit the result to 10 max.
how can i do that?
<?php
$actors = rtrim($movie_info[0]->actors, ", ");
if(stristr($actors, ",")) {
$actors = explode(",", $actors);
array_walk($actors, 'add_url_on_tags', '/actor');
echo ul($actors, array("class" => "genres2"));
echo '<div style="clear:both;"></div>';
}elseif(!empty($actors)) {
echo ''.$actors.'<br />';
}else{
echo 'empty';
}
?>
thank for your help!

What you're looking for is $actors = array_slice($actors, 0, 10);
<?php
$actors = rtrim($movie_info[0]->actors, ", ");
if(stristr($actors, ",")) {
$actors = explode(",", $actors);
$actors = array_slice($actors, 0, 10);
array_walk($actors, 'add_url_on_tags', '/actor');
echo ul($actors, array("class" => "genres2"));
echo '<div style="clear:both;"></div>';
} elseif(!empty($actors)) {
echo ''.$actors.'<br />';
} else{
echo 'empty';
}
?>

you should probably do it in your SQL instead of only cherry picking your results via the code above.
select
*
from
yourTable
where
someColumn=SomeCondition
order by
someColumn
limit 10
^^ This is the clause to add.
Will only bring back the first ten results
you can then use it for pagination, by adding one more value like this:
limit 10,10
This will now bring back ten results, but skip the first ten (basically showing results 11-20

Related

Calculating Average (Mean) in PHP

I'm a bit of a beginner with PHP and am implementing a review aggregator system for a few products.
I have created the input fields and am outputting the results from these fields using this code:
{ echo '<div class="review1">Review 1: '; the_field('review1'); '</div>';}
{ echo '<div class="review2">Review 2: '; the_field('review2'); '</div>';}
{ echo '<div class="review3">Review 3: '; the_field('review3'); '</div>';}
{ echo '<div class="review4">Review 4: '; the_field('review4'); '</div>';}
{ echo '<div class="review5">Review 5: '; the_field('review5'); '</div>';}
I want to use PHP to calculate the average (mean) however the number I am using to calculate this is set to 5 as that is the total number of number fields I have. Here is the code I am using
{ echo (get_field('review1')+get_field('review2')+get_field('review3')+get_field('review4')+get_field('review5'))/5;}
The problem with this method is that sometimes the fields will not contain a value so the number to divide by would need to be 1, 2, 3 or 4 instead of 5 depending on the total number of review fields that have a value.
Essentially I need to replace "/5" with "/n" where "n" is the total number of fields with values.
Can anyone please assist?
Regards,
Peter
I would put the values into an array, then filter out non-numeric values, and then do the calculation of the average:
$array = [ 123, 45, null, 17, 236 ];
// $array = [ get_field('review1'), get_field('review2'), etc. ]
$values = array_filter($array, 'is_numeric');
$result = array_sum($values) / count($values);
echo $result; // Output: 105.25
$items = ['1','2','7','',''];
$average = calculateAverage($items);
echo $average;
function calculateAverage($items)
{
$total = 0;
$count = 0;
foreach($items as $item)
{
if(is_numeric($item))
{
$total += $item;
$count++;
}
}
return $total / $count;
}
If the number is empty, it will not add the number to the devider

Why doesn't my query work for retrieving substrings?

Below is my query to show user comments. It works well:
enter
$query='SELECT
customers.cust_id,
customers.f_name,
customers.l_name,
user_comments.comment_txt,
clubs.name_club
from
customers
inner join
user_comments
on customers.cust_id = user_comments.cust_id
inner join
clubs
on user_comments.cust_id = clubs.cust_id
ORDER BY RAND() LIMIT 1,1
';
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$nameclub =$row['name_club'];
$comment =$row['comment_txt'];
echo '<div><img src="images/arrow.gif"> Name : '.$nameclub.'</div>';
echo '<div>'.$comment.'</div><br>';
echo '<div>'.$row['f_name'].' '.$row['l_name'].'</div>';
}
echo '<p style="text-align: left"> Show all comments</ ></p> '; ?>
I now want to show just about 100 characters of a user comment. So I changed my query accordingly, but it does not work:
enter $query='SELECT
customers.cust_id,
customers.f_name,
customers.l_name,
user_comments.comment_txt.substr(comment_txt,1,100) as comment_txt,
clubs.name_club
from
customers
inner join
user_comments
on customers.cust_id = user_comments.cust_id
inner join
clubs
on user_comments.cust_id = clubs.cust_id
ORDER BY RAND() LIMIT 1,1
';
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$nameclub =$row['name_club'];
$comment =$row['comment_txt'];
echo '<div><img src="images/arrow.gif"> Name : '.$nameclub.'</div>';
echo '<div>'.$comment.'</div><br>';
echo '<div>'.$row['f_name'].' '.$row['l_name'].'</div>';
}
echo '<p style="text-align: left"> Show all comments</ ></p> '; ?>
How can I fix my query to just get 100 characters of a comment?
You're using SUBSTR() incorrectly. Replace this:
user_comments.comment_txt.substr(comment_txt,1,100) as comment_txt,
With this:
SUBSTR(user_comments.comment_txt,1,100) as comment_txt,
Edit per comment: to add ... if the text continues past 100 characters, use
CONCAT(SUBSTR(user_comments.comment_txt,1,100), IF(LEN(user_comments.comment_txt) > 100, '...', '')) as comment_txt,
Try this
Replace this
user_comments.comment_txt.substr(comment_txt,1,100) as comment_txt,
To
SUBSTRING(user_comments.comment_txt,1,100) as comment_txt,
Mysql function_substring
Another solution is to use a php function that cuts a string into a number of words:
<?php
function cut_string($string_to_cut, $number_words, $append = "...") {
$string = array();
$string_return = "";
$return_string = "";
$string = explode(" ", $string_to_cut);
if(count($string) < $number_words) {
for($x=0; $x < count($string); $x++) {
$string_return .= $string[$x] . " ";
}
$return_string = substr($string_return, 0, -1);
}
else {
for($x=0; $x < $number_words; $x++) {
$string_return .= $string[$x] . " ";
}
$string = substr($string_return, 0, -1);
$return_string = $string . $append;
}
return($return_string);
}
?>
Note: This is word count based, not character count based.

similar_text() to compare product names to a given string

I am currently trying to play about with some PHP that will compare an array of words/phrases with a user provided word and then return just the word which has the highest percentage..
My code so far is (for the sake of testing):
<?php
$CRProductName = strtoupper("Product 30");
$XProdNames = array("Product 1","Product 2", "Product 300", "Not a product");
echo "Checking product matches for: ".$CRProductName."<br /><br />";
foreach ($XProdNames as $ProductName) {
similar_text($CRProductName,strtoupper($ProductName), $p);
echo "Percentage:".$p."%<br />";
}
?>
This outputs the following:
Checking product matches for: PRODUCT 30
Percentage:84.2105263158%
Percentage:84.2105263158%
Percentage:95.2380952381%
Percentage:60.8695652174%
Which is great and it works, however I would just like it to return the product name with the highest percentage in the results?
Can anyone advise on a good route for me to take?
I tried adding an IF statement to check the value of $p, but the highest percentage may differ every time.
I converted all to uppercase just to make sure it is marking the similarity by content and not by case.
Thanks,
<?php
$CRProductName = strtoupper("Product 30");
$XProdNames = array("Product 1","Product 2", "Product 300", "Not a product");
echo "Checking product matches for: ".$CRProductName."<br /><br />";
$bestMatch = array('score' => 0, 'name' => 'None');
foreach ($XProdNames as $ProductName) {
$p = 0;
similar_text($CRProductName,strtoupper($ProductName), $p);
echo "Percentage:".$p."%<br />";
if($p > $bestMatch['score'])
{
$bestMatch = array('score' => $p, 'name' => $ProductName);
}
}
print_r($bestMatch);
?>
you could always run simlar_text a few times in each loop and average the results as well if you're getting fluxing results.
It's very simple. Just use an if statement to check for the highest value in the foreach loop. then echo the highest value. Here's your code with the minor change:
<?php
$CRProductName = strtoupper("Product 30");
$XProdNames = array("Product 1","Product 2", "Product 300", "Not a product");
echo "Checking product matches for: ".$CRProductName."<br /><br />";
$pHighest = 0;
foreach ($XProdNames as $ProductName) {
similar_text($CRProductName,strtoupper($ProductName), $p);
if ($p > $pHighest) {
$pHighest = $p;
}
}
echo "Percentage:".$pHighest."%<br />";
?>

php - get second row until last row in mysql

Using while loop, i can get all the result in the table and echo it into a html table.
But, i want to skip the first row, and echo the result starting from second row.
How can i do that?
This is my code.
$sql2="select * from table where year = '2015' and month = '2' order by month desc";
$result2=mysqli_query($conn,$sql2);
echo '<table>';
while($row2=mysqli_fetch_assoc($result2))
{
echo '<tr>';
echo '<th>'.$row2['acc_sth_date'].'</th>';
echo '<th>'.$row2['acc_sth_med_ori'].'</th>';
echo '<th>'.$row2['acc_sth_med_new'].'</th>';
echo '<th>'.$row2['acc_sth_operator'].'</th>';
echo '</tr>';
}
echo '</table>';
Help me please master. Thanks
You can achieve that in two ways.
You could use LIMIT statement in your sql query :
$sql2="select * from table where year = '2015' and month = '2' order by month desc LIMIT 1,100";
1 = Start at the 2nd row
100 = Returns a maximum of 100 rows
Add a condition in your while loop :
$firstRow = true;
while ($row2 = mysqli_fetch_assoc($result2))
{
if (true === $firstRow)
{
$firstRow = false;
continue;
}
// ... Rest of your code ...
}
You need to add a variable that is tested and set to true to not allow skipping next time:
$FirstRun=true;
while($row2=mysqli_fetch_assoc($result2))
{
if ($FirstRun){
$FirstRun = false;
}else {
echo '<tr>';
echo '<th>'.$row2['acc_sth_date'].'</th>';
echo '<th>'.$row2['acc_sth_med_ori'].'</th>';
echo '<th>'.$row2['acc_sth_med_new'].'</th>';
echo '<th>'.$row2['acc_sth_operator'].'</th>';
echo '</tr>';
}
}
Use the following code
$sql2="select * from table where year = '2015' and month = '2' order by month desc";
$result2=mysqli_query($conn,$sql2);
$row2=mysqli_fetch_assoc($result2);
$count = count($row2);
$i = 1;
echo '<table>';
while(i>=$count)
{
echo '<tr>';
echo '<td>'.$row2[i]['acc_sth_date'].'</td>';
echo '<td>'.$row2[i]['acc_sth_med_ori'].'</td>';
echo '<td>'.$row2[i]['acc_sth_med_new'].'</td>';
echo '<td>'.$row2[i]['acc_sth_operator'].'</td>';
echo '</tr>';
$i++;
}
echo '</table>';
It will display all rows except the first row.

How to add a seperator between menu items in PHP but not on the end

I'm trying to put an image as a separator between menu items but not on the outside and I'm not sure how to do this.. So it would end up being something like this:
HOME | ABOUT | CONTACT
unfortunately my code puts one after every entry including the last one.
mysql_select_db($database_db_connection, $db_connection);
$query_rsMenu = "SELECT * FROM menu WHERE online = 1 ORDER BY position ASC";
$rsMenu = mysql_query($query_rsMenu, $db_connection) or die(mysql_error());
echo "<ul class='MenuBarVertical'>\n";
while($row_rsMenu = mysql_fetch_assoc($rsMenu)) {
echo (" <li>" . $row_rsMenu['menuName'] . " <img src='SiteFiles/Site/separator.jpg' /> </li>\n");
}
echo "</ul>\n";
mysql_free_result($rsMenu);
Thanks
You could also build an array and use implode when you print it out. This also separates the database model from the view a little better.
mysql_select_db($database_db_connection, $db_connection);
$query_rsMenu = "SELECT * FROM menu WHERE online = 1 ORDER BY position ASC";
$rsMenu = mysql_query($query_rsMenu, $db_connection) or die(mysql_error());
$array = array();
while($row_rsMenu = mysql_fetch_assoc($rsMenu)) {
$array[] = "<li>" . $row_rsMenu['menuName'] . "</li>\n";
}
mysql_free_result($rsMenu);
echo "<ul class='MenuBarVertical'>\n";
echo implode(' <img src="SiteFiles/Site/separator.jpg" /> ', $array);
echo "</ul>\n";
Of course the tags end up between the li instead of inside, but since you are making the li inline I think it will work.
The easy solution is to special case either the last iteration or the first one. The first one is usually easier: set $first = true outside the loop, inside the loop: if (!$first) { print 'separator'; }.
$count = 0;
$dbRows = mysql_num_rows($rsMenu);
while($row_rsMenu = mysql_fetch_assoc($rsMenu)) {
$count++;
echo (" <li><a href=\"../" . $row_rsMenu['menuURL'] . "\">" . $row_rsMenu['menuName'];
if($count < $dbRows)
echo ("</a> <img src='SiteFiles/Site/separator.jpg' /> </li>\n");
}
You could use mysql_num_rows() to get the number of rows from the result set, and build some logic against the result.
Yet another answer :
for ($i = 1; $i <= mysql_num_rows($rsMenu); $i++) {
$row_rsMenu = mysql_fetch_assoc($rsMenu);
// do something;
if ($i == mysql_num_rows($rsMenu) - 1) {
// this is the last element, do something;
}
}

Categories