set maximum of items that you can make in function - php

How can I say in/with the follow (see below) function that you can make max 3 items? And if you will make more than three items the function will stop and you get a warning?
function addSection() {
global $compid;
$sectionOb = new Item();
$sectionOb->i_id_pk = $sectionOb->newId();
$sectionOb->i_mod_comp_id_fk = $compid;
$sectionOb->c_titel = '';
$sectionOb->c_content = '';
$sectionOb->i_sort = $sectionOb->newSort($compid);
$sectionOb->insert();
}
if($action == 'add') {
addSection();
}
<a href="<?php echo $_SERVER['REQUEST_URI'] ?>&action=add" />new section</a>

Use a static counter variable:
function limited() {
static $invocationcount = 0;
++$invocationcount;
if($invocationcount <= 3) {
echo "You have called this function $invocationcount times.";
}
else {
echo "Stop doing that!";
}
}
See it in action.

If you are not too concerned about URL spoofing, I would add a counter variable in the URL which is passed to the addSection() method like so:
function addSection($count) {
if ($count >= 3) { return $count; }
global $compid;
$sectionOb = new Item();
$sectionOb->i_id_pk = $sectionOb->newId();
$sectionOb->i_mod_comp_id_fk = $compid;
$sectionOb->c_titel = '';
$sectionOb->c_content = '';
$sectionOb->i_sort = $sectionOb->newSort($compid);
$sectionOb->insert();
// Return incremented count
return $count + 1;
}
// Retrieve the last count from the URL
$count = isset($_GET['count']) ? intval($_GET['count']) : 0;
// Increment the count if the action is add and the addSection method suceedes
if($action == 'add') {
$count = addSection($count);
}
// Add count to the URL so we know what it is
<a href="<?php echo $_SERVER['REQUEST_URI'] ?>&action=add&count=<?php echo $count; ?>" />new section</a>

Thanks a lot for help!! I have do it as follow:
function limit() {
global $compid;
$i = 0;
++$i;
$a_all = page1::page2Id($compid);
$i = sizeof($a_all);
if($i <= 2) {
$sectionOb = section();
$sectionOb->i_id_pk = $sectionOb->newId();
$sectionOb->i_mod_comp_id_fk = $compid;
$sectionOb->c_titel = '';
$sectionOb->c_content = '';
$sectionOb->i_sort = $sectionOb->newSort($compid);
$sectionOb->insert();
return true;
}
else {
return false;
}
}

Related

sum all value keep same id

My problem is I have some value using explode, so if I want display value in database using explode, I must use foreach. The problem is I don't want all showing up, because I want sum all the value to keep same id.
$customer_sql_query = "SELECT * FROM winner_delivery ";
$customer_sql_result = mysqli_query($connection,$customer_sql_query);
while ($customer = mysqli_fetch_array($customer_sql_result)){
$ecommercelist = "";
$snacklist = "";
if ($customer['ecommercelist'] != "") {
$ecommercelist = $customer['ecommercelist'];
}
else if ($customer['status'] == "delivered") {
$snacklist = $customer['deliverysnacklist'];
}
else {
$snacklist = $customer['usersnacklist'];
}
if ($ecommercelist){
$ecommercelist_array = explode('~',$ecommercelist);
$i = 0;
foreach ($ecommercelist_array as $ecommercelist_row) {
if ($i % 2 == "1"){
$alternatecolor = "#EEEEEE";
}
else {
$alternatecolor = "#FFFFFF";
}
$selection_array = explode('|',$ecommercelist_row);
$selection_entry = $selection_array[0];
$temp_qty = $selection_array[1];
$temp_producttitle = $product_ob[$selection_entry]['producttitle'];
$temp_imageurl = $product_ob[$selection_entry]['imageurl'];
$temp_weighttitle = $product_ob[$selection_entry]['weighttitle'];
$temp_productid = $product_ob[$selection_entry]['productid'];
$count=$count_qty[$selection_entry] += $temp_qty;
$i++;
?>
<li>
<div class="picture"><?=$temp_productid ?></div>
<div class="weighttitle" nowrap>x<?=$count ?></div>
</li>
<?
}
}
}
Actually I have many time adjust to make better, but is the result!
btw this my database for ecommerlist

PHP PDO Pagination not refreshed

im quite new to PHP and im trying to make a pagination, the code works! but i need to click on the button twice to make the page refreshed/change. how do i fix this?
view/main/user/userlist.php
<?php
$_SESSION['pagelim'] = 10;
$_SESSION['page'] = $_GET['halaman'];
if ($_SESSION['page'] == '') {
$_SESSION['pos'] = 0;
$_SESSION['page'] = 1;
} else {
$_SESSION['pos'] = ($_SESSION['page']- 1) * $_SESSION['pagelim'];
}
$itemcount = listpetugas::getlisted();
$pagecount = ceil(listpetugas::getlisted()/$_SESSION['pagelim']);
for ($i=1;$i<=$pagecount;$i++)
{ ?>
<?php
if ($i!=$pagecount){
echo " <ul class='pagination'><li><a href='?controller=main&action=userlist&halaman=$i' onclick='myFunction()'>$i</a></li></ul>";?>
<?php }
else{
echo "$i";
} ?>
<?php } ?>
model/userdb.php
public static function listemup()
{
if ($_SESSION['pos'] =='' && $_SESSION['pagelim'])
{
$pos = 0;
$lim = 10;
}
else {
$pos = $_SESSION['pos'];
$lim = $_SESSION['pagelim'];
}
$list = [];
$db = FirstFire::StartConnection();
$req = $db->query("SELECT * FROM randomity LIMIT $pos,$lim");
$rowcount = $req->rowCount();
foreach ($req->fetchAll() as $post) {
$list[] = new listpetugas($post['name'],$post['email'],$post['adress'],$post['wow']);
}
return $list;
}
JS
<script>
function myFunction() {
location.reload();
}
</script>
sorry for the messy code.

i get chechbox values but if i won`t select one of them it does not send into db although it keep a record,dose not show what should i do?

<input type="checkbox" name="f[]"value="sport">
<input type="checkbox" name="f[]"value="reading">
<input type="checkbox" name="f[]"value="arguments">
<input type="checkbox" name="f[]"value="tv">
and this is the php:
if(isset($_POST['f'])){
if(in_array("sport",$_POST['f'])){
$sport = $_POST['f'];
$sport = 1;}
if(in_array("reading",$_POST['f'])){
$reading = $_POST['f'];
$reading = 1;}
if(in_array("arguments",$_POST['f'])){
$argument = $_POST['f'];
$argument = 1;}
if(in_array("tv",$_POST['f'])){
$tv = $_POST['tv'];
$tv = 1;}
$problem = false;
} else{
$e = false;
$sport = 0;
$reading = 0;
$argument = 0;
$tv = 0;
}
so what is wrong? what should i do?problem comes when i won`t select any of those checkboxes! plus it dose not send to mysql it set record but does not show that! even the code says that if none of them were checked get them value of 0! and it must get the 0 in mysql but it refuse to do that....
Try this instead of your code,
if (isset($_POST['f'])) {
if (in_array("sport", $_POST['f'])) {
$sport = 1;
} else {
$sport = 0;
}
if (in_array("reading", $_POST['f'])) {
$reading = 1;
} else {
$reading = 0;
}
if (in_array("arguments", $_POST['f'])) {
$argument = 1;
} else {
$argument = 0;
}
if (in_array("tv", $_POST['f'])) {
$tv = 1;
} else {
$tv = 0;
}
$problem = false;
}

PHP return an pagination object and displaying the links when called

I have this pagination class which I converted from a normal procedural function to a class since I started learning OOP. In the old procedural way, the function worked fine but I can't get this new class version to display on the screen
class Pagination {
public function __construct() {
}
/**
* This function is called whenever the there are several records to be displayed in the table
* This saves the page extending further down the page creating a long list of results
* when all the results can be spread across multiple pages
*/
public function pagination_one($total_pages, $page, $webpage) {
// Maximum number of links per page. If exceeded, google style pagination is generated
$max_links = 6;
$h=1;
if($page>$max_links) {
$h=(($h+$page)-$max_links);
}
if($page>=1) {
$max_links = $max_links+($page-1);
}
if($max_links>$total_pages) {
$max_links=$total_pages+1;
}
echo '<div class="page_numbers">
<ul>';
if($page>"1") {
echo '<li class="current">First</li>
<li class="current">Prev</li> ';
}
if($total_pages!=1) {
for ($i=$h;$i<$max_links;$i++) {
if($i==$page) {
echo '<li><a class="current">'.$i.'</a></li>';
}
else
{
echo '<li>'.$i.' </li>';
}
}
}
if(($page >="1")&&($page!=$total_pages)) {
echo '<li class="current">Next</li>
<li class="current">Last</li>';
}
echo '</ul> </div>';
}
and elsewhere in another class I want to create a new instance of that class and pass the method in the return along with some parameters
public function paging() {
if($this->getcount != 0) {
$this->paging = new Pagination();
return $this->paging->pagination_one($this->total_pages, $this->page, 'news');
}
}
When I try I var_dump() it comes up as NULL where I expect to see some pagination on the screen.
What have i got to change to be able to display the pagination? Do I have to created some variables in the Pagination class for $total_pages, $page and $webpage and initialise them in the constructor and remove them from the pagination_one method?
You do
return $this->paging->pagination_one...
when you are not returning anything in pagination_one -method, hence null.
I fixed it myself by removing the private variables in the class and changing the constructor.
The class now looks like this
class Pagination {
public function __construct($total_pages, $page, $webpage) {
$this->total_pages = $total_pages;
$this->page = $page;
$this->webpage = $webpage;
}
/**
* This function is called whenever the there are several records to be displayed in the table
* This saves the page extending further down the page creating a long list of results
* when all the results can be spread across multiple pages
*/
public function pagination_one() {
// Maximum number of links per page. If exceeded, google style pagination is generated
$max_links = 6;
$h = 1;
if($this->page > $max_links) {
$h=(($h + $this->page) - $max_links);
}
if($this->page >= 1) {
$max_links = $max_links + ($this->page - 1);
}
if($max_links > $this->total_pages) {
$max_links = $this->total_pages + 1;
}
$paging = '';
$paging .= '<div class="page_numbers">
<ul>';
if($this->page > "1") {
$paging .= '<li class="current">First</li>
<li class="current">Prev</li> ';
}
if($this->total_pages != 1) {
for ($i=$h; $i < $max_links; $i++) {
if($i == $this->page) {
$paging .= '<li><a class="current">'.$i.'</a></li>';
}
else {
$paging .= '<li>'.$i.' </li>';
}
}
}
if(($this->page >= "1" ) && ($this->page != $this->total_pages)) {
$paging .= '<li class="current">Next</li>
<li class="current">Last</li>';
}
$paging .= '</ul> </div>';
return $paging;
}
}
function pagination($sql_total_row, $post_per_page,$current_page=1, $url='', $lasturl = '', $parameter ='paging') {
$number_page = ceil($sql_total_row / $post_per_page);if($number_page<=1) return false;
$uls ='<ul class="pagination pagination-sm">';
$a = parse_url($url);
if(isset($a['query']))$url .= '&';else $url .= '?';
$url .= $parameter.'=';
$urls = '';
$distanc = 5;
$f = $current_page-$distanc;
$l = $current_page+$distanc;
$li = function($n,$link,$current_page){ return $current_page==$n ? '<li class="active"><span>'.$n.'</span><li>' : '<li>'.$n.'</li>'; };
for ($i = $current_page; $i > 0; $i--){
if($i>$f or $i < $distanc)
$urls = $li($i,$url.$i.$lasturl,$current_page). $urls;
else{
$i = $distanc;
$urls = '<li><span>...</span><li>'.$urls;
}
}
for ($i = $current_page+1; $i < $number_page; $i++){
if($i<$l or $i > $number_page - $distanc)
$urls .= $li($i,$url.$i.$lasturl,$current_page);
else{
$i = $number_page - $distanc;
$urls.= '<li><span>...</span><li>';
}
}
return $uls.$urls.'</ul>';
}
usage:
$total_row_sql = 1500; //required - get from mysql: SELECT FOUND_ROWS();
$row_display = 50; //required
$parameter_paged = (isset($_GET['paging'])) ? $_GET['paging'] : 1; // required
$custom_url = '/wordpress_url/?'; //custom
$hash = '#target_element_id'; //custom
$name_paramerter_paging = 'paging'; //custom
echo pagination($total_row_sql,$row_display,$parameter_paged,$custom_url,$hash,$name_paramerter_paging);
Result:
view result using pagination
========================================================================
Example if using loop from database:
function select( $table, $field='*', $where='', $order='') {
$sql = "select SQL_CALC_FOUND_ROWS $field from $table";
if($where) $sql.= " where $where";
if($order) $sql.= " order by $order";
$items = $wordpress_mysql->get_results( $sql );// custom: default result object, if u want parse array: ( $sql, ARRAY_A);
$sql_posts_total = $wordpress_mysql->get_var( "SELECT FOUND_ROWS();" );
return (object)['result'=>$items, 'total_rows'=>$sql_posts_total];
}
$result = select('user');
$data_items = $result->result;// foreach show database if u want
$sql_posts_total = $result->total_rows;
$post_per_page = 50;
$parameter_paged = (isset($_GET['paging'])) ? $_GET['paging'] : 1;
echo pagination($sql_posts_total,$post_per_page,$parameter_paged);

How to get the next row in mysqli result?

I want to get the next row in a cycle of a mysql result to write a list with the next and previous element code like this example:
<?php $previous = null;
$next = null;
while ($row = $result->fetch_assoc()) {
$next = ??????????????? // how to get it?
?>
<li code="<?php echo $row['code']; ?>" previous="<?php echo $previous; ?>" next="<?php echo $next; ?>">Hello world!</li>
<?php
$previous = $row['code']; // previous is easy to get...
} ?>
Not sure with MySQLi but here is how I do it in PDO:
$data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
for($i = 0; $i < count($data); $i++) {
$next = isset($data[$i+1]) ? $data[$i+1] : null;
}
if there is no fetchAll in mysqli then do:
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
if ( ! empty($data)) {
for($i = 0; $i < count($data); $i++) {
$next = isset($data[$i+1]) ? $data[$i+1] : null; // next
$prev = isset($data[$i-1]) ? $data[$i-1] : null; // previous
$curr = isset($data[$i]) ? $data[$i] : null; //current
}
}
How about something on the lines of this:
SELECT * FROM table WHERE id > '$currentID' ORDER BY id LIMIT 1;
to get the single next possible row.
Look at this solution, what do you think about it? it works, but will be more slow? this algorithm requires at least double pass or not? what do you think?
$db = DB::getConnection();
$result = $db->query( "SELECT * FROM objects" );
$next = null;
$previous = null;
$temp_previous = null;
$print = false;
$row = null;
$fetchit = false;
$code = null;
echo "<ul>";
while (true)
{
if ($print) {
if ($fetchit) {
$row = $result->fetch_assoc();
$next = $row['code'];
}
echo "<li code='$code' next='$next' previous='$previous'>{$row['description']}</li>" . endl();
$previous = $temp_previous;
$print = false;
}
else {
if (!$fetchit)
$row = $result->fetch_assoc();
$code = $row['code'];
$temp_previous = $row['code'];
$print = true;
$fetchit = true;
}
if(!is_array($row)) break;
}
echo "</ul>";

Categories