php & input checkbox store value of each loop - php

I have a page that will display the names of people from one data base that is joined with another that tracks when two names are linked. Every thing works fine. However; I cannot make the data or specifically the right user name ($id2u) and a string ($permissions) transfer from the input boxes when the user selects one. The onclick event should then show the data fields as per the permission string. The problem is the displayed info is always the last user in the DB that was ran through the loop. Am trying to get the info to carry forward on the onclick event when a check box is clicked so that their info is displayed.
This is he function to call the display of data.
function display1(type) {document.getElementById("pi").style.display = "none"
document.getElementById(type).style.display = ""}
This is the call to the DB that generated the input boxes for each person.
$result1 = mysql_query('SELECT * FROM level1 LEFT JOIN linkreq ON level1.idnumber = linkreq.idme ORDER BY LEAST(lname, fname) DESC');
for ($i = mysql_num_rows($result1) - 1; $i >= 0; $i--){
if (!mysql_data_seek($result1, $i)){echo "Cannot seek to row $i: " . mysql_error() . "\n";continue;}
if (!($row = mysql_fetch_assoc($result1))) {continue;}
if($_SESSION["idnumber"] == $row['id2u']){
if($row['returnack'] == 0){$id2u = $row['idme']; echo'<font color="#FF6600">*</font> '.$row['title'].' '.$row['fname'].' '.$row['mname'].' '.$row['lname'].' '.$row['suffex'].'<br />';}
else{
$permissions = $row['permissions'];
parse_str($permissions);
$permissions;
$id2u = $row['idme'].' ';
echo '<input type="checkbox" value = " .$id2u. " onClick="display1(\'pi\');"> '
.$row['title'].' '.$row['fname'].' '.$row['mname'].' '.$row['lname'].' '.$row['suffex'].'
<br />';}}}
This is the data that gets displayed onclick(pi) but displays last user not the selected one. Basically if the $id2u variable data would carry over from the check box this would work. As can manually force it by setting $id2u = xxxxxx; just before the query.
$result2 = mysql_query('SELECT * FROM pi WHERE idnumber = "'.$id2u.'"');
for ($i = mysql_num_rows($result2) - 1; $i >= 0; $i--){
if (!mysql_data_seek($result2, $i)){echo "Cannot seek to row $i: " . mysql_error() . "\n";continue;}
if (!($row = mysql_fetch_assoc($result2))) {continue;}
echo '<br>row #'.$row['idnumber'];
if($id2u == $row['idnumber']){echo'...// PRINTS OUT DATA //...}}
</span>
I know this should be in mySQLi but for now just need to get it to work will convert later.

Why don't you use a while() loop ?
$query = mysql_query("...");
while($row = mysql_fetch_array($query))
{
...
}
This always works fine for me :)

Related

PHP Limit rows returned by MySQL and do something if last row returned

I didn't know exactly how to word this question but by do something I mean that I would like to hide or not show my "next" button that is shown below. I have a script that pulls all the images from MySQL and prints them to my page by 30 images per page and the next 30 will create a new page that is activated by my back/next buttons. My "back" button has a if statement if $startrow isn't >= 0 than it won't show but I would like the same concept with my next button when the last row in my database is shown and it hides my next button.
I was thinking if you can detect the first empty row or the last row of the database and if so hide the next button. Otherwise it keeps adding 30 to $startrow when nothing is shown on screen.
I found a script helping me with this here but it didn't tell me how to hide the next button.
<?php
$startrow = $_GET['startrow'];
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
$startrow = 0;
} else {
$startrow = (int)$_GET['startrow'];
}
?>
<?php
$db = mysqli_connect("localhost", "root", "", "media");
$uploaded = mysqli_query($db, "SELECT * FROM images LIMIT $startrow, 30");
while ($row = mysqli_fetch_array($uploaded)) {
echo "<div class='img_container'>";
echo "<li><img class='img_box' src='uploads/images/".$row['image_title']."' ></li>";
echo "</div>";
}
$prev = $startrow - 30;
if ($prev >= 0) {
echo '<div class="prevRow">Back</div>';
}
echo '<div class="nextRow">Next</div>';
?>
You could try something like
$num_rows = 30; // rows on a page
$db = mysqli_connect("localhost", "root", "", "media");
// get total possible rows
$res = mysqli_query($db, "SELECT count(id) FROM images");
$row = $res->fetch_row();
$total_rows = $row[0];
$res->close();
$uploaded = mysqli_query($db, "SELECT * FROM images LIMIT $startrow, $num_rows");
while ($row = mysqli_fetch_array($uploaded)) {
. . .
}
$prev = $startrow - $num_rows;
if ($prev >= 0) {
echo '<div class="prevRow">Back</div>';
}
if ( $startrow+$num_rows < $total_rows ) {
echo '<div class="nextRow">Next</div>';
}
Potentially a little faster than the answer from #RiggsFolly, you can modify your existing query to count the rows.
SELECT SQL_CALC_FOUND ROWS * FROM images LIMIT $startrow, 30
Then, after the query returns, you run a second query to get the answer:
SELECT FOUND_ROWS()
The FOUND_ROWS() function returns the number of rows the previous query would have returned, without LIMIT (or an offset).
This is probably not as fast as your original query would be in isolation, but should be slightly faster than SELECT COUNT(...) ... followed by your original query. With small data sets, though, any differences will likely be below measurable limits.
See also https://dev.mysql.com/doc/refman/5.7/en/information-functions.html
You can also combine these things into a stored procedure that accepts items per page and page number, and returns all of the records along with metadata items such as the total number of pages.

echo key value from a row before postgres php while loop

Can't believe this is giving me a problem but here it is. An example of the query and code is:
$sql = "SELECT
o.order_id, o.order_number, o.broker_id, o.agent_id
FROM orders o";
$sql_res = safe_query($sql);
/* I want to echo broker_id and angent_id only once here,
before the while loop, because the values are all the same */
while ($row = pg_fetch_array($sql_res)){
echo $order_number;
}
Assume broker and agent id numbers are each the same in every row. I don't want to echo them every time in the loop. I just want them to echo one time before the loop. Since they are the same, it does not matter which row they are echoed from.
I figured out a different way for a means to an end. It works well.
$sql = "SELECT
o.order_id, o.order_number, o.broker_id, o.agent_id
FROM orders o";
$sql_res = safe_query($sql);
$count = 0;
while ($row = pg_fetch_array($sql_res)){
if ($count == 0) {
echo $broker_id;
echo $agent_id;
}
echo $order_number;
$count += 1;
}
I realize I'm echoing the broker and agent IDs inside the while loop, but it's only an echo the first time through, and I can display them at top. And then every unique order is echoed. Visually, it accomplished what was needed for the end user.

How to sum up values in a php column

Im trying to sum up all the values in this data base but for some reason i cant do i, I looked all over stack overflow and tried multiple methods but none seem to work. My current code is
<?php
error_reporting(0);
//INCLUDES//
include 'config.php';
//INCLUDES//
//DATA FETCH//
$rank=$_POST['R'];
$drank=$_POST['DR'];
//DATA FETCH//
//MYSQL STUFF//
$con=mysqli_connect($ip,$login,$password,$dbname);
for ($i = $rank; $i <= $drank; $i++) { // LOOP UNTIL 20 IS MET
$s=mysqli_query($con, "SELECT sum(rankprice) FROM cost WHERE rank='$i'");
if($s === FALSE) { //CHECK IF DATA IS THERE
die('Error: ' . mysqli_error($con)); // IF NOT THERE SEND ERROR
}
$row = mysqli_fetch_array($s); //PUT DATA IN ROW
echo $row[0];
}
?>
It connects to the database no problem. When I use echo $row[0]; it prints all the values of the column in order. Ive tried putting it into an array and printing it but it seems that doesnt work either. The only way it seems to work is when I add ALL the values in the column by removing WHERE rank='$i' in the SQL code which I dont want to do. Please help !
Try the following query :
$rankarr = array();
for ($i = $rank; $i <= $drank; $i++) { // LOOP UNTIL 20 IS MET
$rankarr[] = $i;
}
$rankarr = implode(',', $rankarr);
$s=mysqli_query($con, "SELECT sum(rankprice) As myrank FROM cost WHERE rank in ($rankarr)");
if($s === FALSE) { //CHECK IF DATA IS THERE
die('Error: ' . mysqli_error($con)); // IF NOT THERE SEND ERROR
}
$row = mysqli_fetch_array($s); //PUT DATA IN ROW
You now want to get the sum value of rankprice in one same rank. So the result of sum() will differ from the rank in one sql. You should tell mysql by adding group by clause, which group the table by rank and get the sum() of each group.
$s=mysqli_query($con, "SELECT sum(rankprice) FROM cost WHERE rank='$i' GROUP BY rank ");

PHP getimagesize, Mysql fetch from DB and update field

I've been a lot around this site the last couple of days, and found a lot of useful tips for a newbie to php as I am (this is my second day :) ) Therefore I'll sure hope you gurus can help me finishing this script.
What do I have:
I have this table within my Mysql:
------------------------------![Sql Tabels][1]
----------------------
Would should it do:
The script have to get some table rows where the "diemensions" field is emty IS NULL
Now the script have to find the image size and spit it out in this format widthxheight the x between the width and height is important.
Where the image is not to be grabt, it should just pass by, and take the next one.
When it's done:
It have grabt the image size and updated the "dimensions" field in the DB
Sources for my code:
How to determine the picture size, then selectively insert into the database? php
Update MySql Field (if field is not empty, go to next one)
http://dk1.php.net/manual/en/function.getimagesize.php
The PHP it self
<pre><code>
<?php
# first we check, if gd is loaded and supports all needed imagetypes
function gd_get_info() {
if (extension_loaded('gd') and
imagetypes() & IMG_PNG and
imagetypes() & IMG_GIF and
imagetypes() & IMG_JPG and
imagetypes() & IMG_WBMP) {
return true;
} else {
return false;
}
}
$username = "";
$password = "";
$database = "";
$db_hostname = "";
mysql_connect("$db_hostname","$username","$password") or die(mysql_error());
mysql_select_db("$database") or die(mysql_error());
//check if the starting row variable was passed in the URL or not
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
//we give the value of the starting row to 0 because nothing was found in URL
$startrow = 0;
//otherwise we take the value from the URL
} else {
$startrow = (int)$_GET['startrow'];
}
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM tx_gallery_previews WHERE dimensions IS NULL ORDER BY gallery_id ASC LIMIT $startrow, 10") or die(mysql_error());
// store the record of the "example" table into $row
while($row = mysql_fetch_array($result)){
//$row = mysql_fetch_array($result))
$pid = $row['preview_id'];
$gid = $row['gallery_id'];
$imgfile = $row['preview_url'];
$dimens = $row['dimensions'];
/*
echo $row['gallery_id'];
echo $row['preview_url']. "\r\n<br />"; */
extract($row);
//print $pid. " ".$imgfile." ";
//print "".$dimens."<br />";
$blah = getimagesize("$imgfile");
$type = $blah['mime'];
$width = $blah[0];
$height = $blah[1];
if (isset($width)) {
echo $pid. " ".$imgfile." ".$width. "x".$height. "\n"."<br />";
mysql_query("UPDATE into tx_gallery_previews (preview_id,gallery_id,preview_url,dimensions) VALUES ($pid,$gid,$imgfile,$width."x".$height)
ON DUPLICATE KEY UPDATE dimensions=VALUES('"$width."x".$height"')");
}
else{ echo "$pid <img src=\"$imgfile\" width=\"90\">Image not found"."<br />"; }
}
// close connection
mysql_close($connection);
$prev = $startrow - 10;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
echo 'Previous ';
//now this is the link..
echo 'Next';
?>
</pre></code>
Seen but couldn't make it work
http://dk1.php.net/manual/en/function.getimagesize.php
Post by "james dot relyea at zifiniti dot com 07-Feb-2009 08:49"
But seems to be the right ideer for my script.
XXXXXXXXXXXXXXXXX
When you answer this topic, please explane wich part does what.
Best Regards
Joakim

Paginator Class

everyone. I am working on a site with smarty templates using php and a mysql database.
This is a more specific question than my first one which asked how to pass methods to a class. I thought it would be easier to repackage the question than edit the old one.
I have written a paginator script for my image gallery which displays images on the page. If a user has selected a category then only images in a particular category are shown and the results are always paginated.
The script is shown below.
$page_num = (isset($_GET['page_num']))?$_GET['page_num']:1; //if $_GET['page_num'] is set then assign to var $page_num. Otherwise set $page_num = 1 for first page
$category = (isset($_GET['req1']))?$_GET['req1']:'null'; //if $_GET['req1'] is set assign to $category other set $category to null
$items_pp = 5;
$total = $db->num_images_gallery($category); //returns the number of records in total('null') or in a particular category('category_name')
$pages_required = ceil($total/$items_pp); //total records / records to display per page rounded up
if($page_num > $pages_required){//in case the current page number is greater that the pages required then set it to the amount of pages required
$page_num = $pages_required;
}
if($page_num < 1){//in case the current page num is set to less that one set it back to 1
$page_num = 1;
}
$limit = "LIMIT " .($page_num - 1)*$items_pp . "," . $items_pp . ""; //if 5 results pre page and we on page 3 then LIMIT 10,5 that is record 10,11,12,13 and 14
$result = $db->get_images_gallery($category,$limit);
$i = 0;
while($row = $result->fetch_assoc()){
$images[$i]['file'] =$row['file'];
$images[$i]['file_thumb'] = str_replace('.','_thumbnail.',$row['file']);//show the thumbnail version of the image on the page
$images[$i]['title'] = $row['title'];
$images[$i]['description'] = $row['description'];
$i++;
}
if(!empty($images)){
$smarty->assign('images',$images);}else{
$smarty->assign('message',"There are no images to display in the ".ucwords(str_replace('_',' ',$category))." category");}
if($total > 0 && $pages_required >= 1){//only display this navigation if there are images to display and more than one page
$smarty->assign('page_scroll',$page_num . ' of ' . $pages_required);
$page_scroll_first = "<a href='".$_SERVER['REDIRECT_URL'] . "?page_num=1"."' >FIRST</a> <a href='".$_SERVER['REDIRECT_URL'] . "?page_num=" . ($page_num-1)."' ><<PREVIOUS</a>";
$page_scroll_last = " <a href='".$_SERVER['REDIRECT_URL'] . "?page_num=". ($page_num+1) . "'>NEXT>></a> <a href='" . $_SERVER['REDIRECT_URL'] . "?page_num=".$pages_required."'>LAST</a>";
if($page_num == 1){$page_scroll_first = "FIRST <<PREVIOUS";}
if($page_num == $pages_required){$page_scroll_last = "NEXT>> LAST";}
$smarty->assign('page_scroll_first',$page_scroll_first);//just use if statements to set the values for page scroll first and page scroll last and then assign them here
$smarty->assign('page_scroll_last',$page_scroll_last);
$smarty->assign('page_num',$page_num);
}
The script calls on two methods from my database class:
$db->num_images_gallery which looks like this:
function num_images_gallery($cat='null'){
$query = ($cat == 'null')?
"SELECT COUNT(*) AS images FROM images
LEFT JOIN image_categories ON (images.image_categories_id = image_categories.id)
WHERE images.gallery='1' AND image_categories.gallery = '1'"//no images should be shown in a category which is not intended to be shown at all
:
"SELECT COUNT(*) AS images FROM images
LEFT JOIN image_categories ON (images.image_categories_id = image_categories.id)
WHERE category = '{$cat}'
AND images.gallery='1' AND image_categories.gallery = '1'";
$result = $this->connection->query('SELECT COUNT(*) AS images FROM (?)',$x);
$row = $result->fetch_assoc();
$row_count = $row['images'];
echo $row_count;
return $row_count;
}
and the method $db::get_images_gallery() which looks like this:
function get_images_gallery($category,$limit){
$query = ($category=='null')?
"SELECT `file`,title,images.description,sizes,images.gallery,category FROM images
LEFT JOIN image_categories ON (images.image_categories_id = image_categories.id) WHERE images.gallery='1' AND image_categories.gallery = '1' {$limit}"
:
"SELECT `file`,title,images.description,sizes,images.gallery,category FROM images
LEFT JOIN image_categories ON (images.image_categories_id = image_categories.id)
WHERE category = '{$category}' AND images.gallery='1' AND image_categories.gallery = '1' {$limit}";
$result = $this->connection->query($query);
return $result;
}
I now want to create a class called paginate and put this script in it so i can display my site products paginated.
The main problem is that i need to use different functions to get the num of prodducts in my product table and then return the paginated results. How do i turn the script above into a class where i can change the functions which are used. I almost got an answer on my previous question, but the question was not specific enough.
Thanks
andrew
There's a Smarty Add-On for pagination.
You can find it here: http://www.phpinsider.com/php/code/SmartyPaginate/
For a quick example, extracted from the linked page:
index.php
session_start();
require('Smarty.class.php');
require('SmartyPaginate.class.php');
$smarty =& new Smarty;
// required connect
SmartyPaginate::connect();
// set items per page
SmartyPaginate::setLimit(25);
// assign your db results to the template
$smarty->assign('results', get_db_results());
// assign {$paginate} var
SmartyPaginate::assign($smarty);
// display results
$smarty->display('index.tpl');
function get_db_results() {
// normally you would have an SQL query here,
// for this example we fabricate a 100 item array
// (emulating a table with 100 records)
// and slice out our pagination range
// (emulating a LIMIT X,Y MySQL clause)
$_data = range(1,100);
SmartyPaginate::setTotal(count($_data));
return array_slice($_data, SmartyPaginate::getCurrentIndex(),
SmartyPaginate::getLimit());
}
index.tpl
{* display pagination header *}
Items {$paginate.first}-{$paginate.last} out of {$paginate.total} displayed.
{* display results *}
{section name=res loop=$results}
{$results[res]}
{/section}
{* display pagination info *}
{paginate_prev} {paginate_middle} {paginate_next}
Regarding your question about mixing the DB class and the Paginator class, it's all ok:
Your DB class will handle fetching data from DB
The SmartyPaginate class will handle the pagination
And your index.php just make the calls to each one where appropriate to set things out.
The idea is to keep responsibilities isolated.
Your DB class won't handle pagination, nor will your pagination class contain DB code.
From your other question, I think you were trying to do something too much convoluted for the problem at hand.
I'd suggest you to move all code that is DB-related inside your DB handling class and outside your index.php
This, for example:
$limit = "LIMIT " .($page_num - 1)*$items_pp . "," . $items_pp . ""; //if 5 results pre page and we on page 3 then LIMIT 10,5 that is record 10,11,12,13 and 14
This is DB logic, it generates (part of) an SQL string, so move it around.
It depends on 2 parameters, so find a way to get them available.
In this case, I'd suggest just passing both as parameters.
Instead of:
$result = $db->get_images_gallery($category,$limit);
Use:
$result = $db->get_images_gallery($category,$no_items, $page);
Also, your pager navigation rule should be inside your paginator class..
if($total > 0 && $pages_required >= 1){//only display this navigation if there are images to display and more than one page
$smarty->assign('page_scroll',$page_num . ' of ' . $pages_required);
$page_scroll_first = "<a href='".$_SERVER['REDIRECT_URL'] . "?page_num=1"."' >FIRST</a> <a href='".$_SERVER['REDIRECT_URL'] . "?page_num=" . ($page_num-1)."' ><<PREVIOUS</a>";
$page_scroll_last = " <a href='".$_SERVER['REDIRECT_URL'] . "?page_num=". ($page_num+1) . "'>NEXT>></a> <a href='" . $_SERVER['REDIRECT_URL'] . "?page_num=".$pages_required."'>LAST</a>";
if($page_num == 1){$page_scroll_first = "FIRST <<PREVIOUS";}
if($page_num == $pages_required){$page_scroll_last = "NEXT>> LAST";}
$smarty->assign('page_scroll_first',$page_scroll_first);//just use if statements to set the values for page scroll first and page scroll last and then assign them here
$smarty->assign('page_scroll_last',$page_scroll_last);
$smarty->assign('page_num',$page_num);
}
In this case, I hope the Add-On will handle it automatically for you.
You could then move this whole block, which does all your logic for fetching and preparing images data to a function (inside your ImageGalery class if you have one)
$total = $db->num_images_gallery($category); //returns the number of records in total('null') or in a particular category('category_name')
$pages_required = ceil($total/$items_pp); //total records / records to display per page rounded up
if($page_num > $pages_required){//in case the current page number is greater that the pages required then set it to the amount of pages required
$page_num = $pages_required;
}
if($page_num < 1){//in case the current page num is set to less that one set it back to 1
$page_num = 1;
}
$limit = "LIMIT " .($page_num - 1)*$items_pp . "," . $items_pp . ""; //if 5 results pre page and we on page 3 then LIMIT 10,5 that is record 10,11,12,13 and 14
$result = $db->get_images_gallery($category,$limit);
$i = 0;
while($row = $result->fetch_assoc()){
$images[$i]['file'] =$row['file'];
$images[$i]['file_thumb'] = str_replace('.','_thumbnail.',$row['file']);//show the thumbnail version of the image on the page
$images[$i]['title'] = $row['title'];
$images[$i]['description'] = $row['description'];
$i++;
}
Finally, on your index.php, all you have to do is:
Validate the parameters you received
Call your ImageGalery class to fetch the galery data (pass the parameters it needs)
Call your Pagination class to do the pagination (setting up navigation links, etc)
Set the Smarty template variables you need
And display it.
There is still lots of room for improvement, but I hope those few steps will help get your Image Galery code more clear.

Categories