I have codes that should be getting value from mysql database, I can get only one value but I have while loop so it can get value and output data separated with comma. But I only get one value and cannot get multiple value. the result should be like this, // End main PHP block. Data looks like this: [ [123456789, 20.9],[1234654321, 22.1] ] here is the code:
<?php
// connect to MySQL
mysql_connect('localhost','','') or die("Can't connect that way!");
#mysql_select_db('temperature1') or die("Unable to select a database called 'temperature'");
if(ISSET($_GET['t']) && (is_numeric($_GET['t'])) ){
// message from the Arduino
$temp = $_GET['t'];
$qry = "INSERT INTO tempArray(timing,temp) VALUES(".time().",'$temp')";
echo $qry;
mysql_query($qry);
mysql_close();
exit('200');
}
// no temp reading has been passed, lets show the chart.
$daysec = 60*60*24; //86,400
$daynow = time();
if(!$_GET['d'] || !is_numeric($_GET['d'])){
$dayoffset = 1;
} else {
$dayoffset = $_GET['d'];
}
$dlimit = $daynow-($daysec*$dayoffset);
$qryd = "SELECT id, timing, temp FROM tempArray WHERE timing>='$dlimit' ORDER BY id ASC LIMIT 1008";
// 1008 is a weeks worth of data,
// assuming 10 min intervals
$r = mysql_query($qryd);
$count = mysql_num_rows($r);
$i=0;
$r = mysql_query($qryd);
$count = mysql_num_rows($r);
while($row=mysql_fetch_array($r, MYSQL_ASSOC)) {
$tid=$row['id'];
$dt = ($row['timing']+36000)*1000;
$te = $row['temp'];
if($te>$maxtemp) $maxtemp=$te; // so the graph doesnt run along the top
if($te<$mintemp) $mintemp=$te; // or bottom of the axis
$return="[$dt, $te]";
echo $return; //here I get all values [1385435831000, 21][1385435862000, 23][1385435892000, 22][1385435923000, 25][1385435923000, 22]
$i++;
if($i<$count) $return= ","; echo $return; // if there is more data, add a ',' however, it return me ,,,[1385435923000, 22]
$latest = "$dt|$te"; // this will get filled up with each one
}
mysql_close();
// convert $latest to actual date - easier to do it here than in javascript (which I loathe)
$latest = explode('|',$latest);
$latest[0] = date('g:ia, j.m.Y',(($latest[0])/1000)-36000);
?>
You're just assigning $return to the values from the last row your while loop grabbed instead of concatenating it. Try this
$return = "[";
while($row=mysql_fetch_array($r, MYSQL_ASSOC)) {
$tid=$row['id'];
$dt = ($row['timing']+36000)*1000;
$te = $row['temp'];
if($te>$maxtemp) $maxtemp=$te; // so the graph doesnt run along the top
if($te<$mintemp) $mintemp=$te; // or bottom of the axis
$return.="[$dt, $te]";
$i++;
if($i<$count) $return .= ", ";// if there is more data, add a ','
$latest = "$dt|$te"; // this will get filled up with each one
}
$return .= "]";
Related
I try to loop trough a php script to calculate a Total Holding of a Persons Portfolio. But my code only puts out one calculated field instead of all from the Database.
My DB looks like this:
id email amount currency date_when_bought price_when_bought
33 test#test.com 100 BTC 2019-04-17 4000
34 test#test.com 50 ETH 2019-04-17 150
My Code (pretty messy)
<?php
include('databasecon.php');
//// GET API JSON DATA
$coinData = json_decode(file_get_contents('https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC,ETH,XRB,IOTA,XRP,XLM,TRX,LINK,USDT&tsyms=USD'), true);
//SELECT ALL MAIL
$result = mysqli_query($con, "SELECT DISTINCT email FROM user_data");
$email_array = array();
while($row = mysqli_fetch_array($result))
{
$email_array[] = $row['email'];
};
// PORTFOLIO ARRAYS
for ($i = 0; $i < sizeof($email_array); $i++) {
$sql = mysqli_query($con, "SELECT DISTINCT * FROM crypto_data WHERE email = '$email_array[$i]'");
while($row = mysqli_fetch_array($sql)){
$myCoins[$row['currency']] = array('balance' => $row['amount'],
'boughtprice' => $row['price_when_bought']);
};
// 0 VALUES FOR CALCULATION
$portfolioValue = 0;
$totalNET = 0;
$Value24H = 0;
// information in json path ['RAW'] so safeguard here to be sure it exists
if (isset($coinData['RAW'])) {
// then loop on all entries $cryptoSymbol will contain for example BTC and cryptoInfo the array USD => [...]
foreach($coinData['RAW'] as $cryptoSymbol => $cryptoInfo) {
// safeguard, check path [USD][FROMSYMBOL] exists
if (!isset($cryptoInfo['USD']) || !isset($cryptoInfo['USD']['FROMSYMBOL'])) {
// log or do whatever to handle error here
echo "no path [USD][FROMSYMBOL] found for crypto: " . $cryptoSymbol . PHP_EOL;
continue;
}
// Symbol in on your json path/array [USD][FROMSYMBOL]
$thisCoinSymbol = $cryptoInfo['USD']['FROMSYMBOL'];
$coinHeld = array_key_exists($thisCoinSymbol, $myCoins);
// Only retour held
if ( !$coinHeld ) { continue; }
// get price:
$thisCoinPrice = $cryptoInfo['USD']['PRICE'];
// get symbol holding:
if ($coinHeld) {
$myBalance_units = $myCoins[$thisCoinSymbol]['balance'];
};
// calculate total holdings:
if ($coinHeld) {
$myBalance_USD = $myBalance_units * $thisCoinPrice;
$portfolioValue += $myBalance_USD;
};
echo '<br>';
echo $email_array[$i];
echo $portfolioValue . PHP_EOL;
echo '<br>';
echo '<br>';
$myCoins = null;
}}};
?>
The Steps are:
1 API connection
2 Select Mail adresses from user_data and put them into an Array
3 start for-loop with size of the email_array
4 Query the crypto_data DB to get all results from that mail
5 Put all Data from crypto_data into Array
6 foreach loop the API
7 Calculations
8 Echo the results
9 null $myCoins
As a result, I get the right Mail Adress + the second row (id 33) calculated with the actual price. But my Result should also plus count id 33 and 34 to get the total result.
To clearify, I get "100 * Price of BTC" , but I need "100 * Price of BTC + 50 * Price of ETH"
Somehow my code only puts out 1 row, but does not calculate them like I want to do so here:
// calculate total holdings:
if ($coinHeld) {
$myBalance_USD = $myBalance_units * $thisCoinPrice;
$portfolioValue += $myBalance_USD;
};
Any help is appreciated, thank you very much.
There are few bugs in your code, such as:
You are setting $myCoins to null immediately after the first iteration of foreach loop, so array_key_exists() function will fail in the next iteration. Remove it entirely, there's no need of setting $myCoins to null.
Keep the below just inside the outer for loop. You should not print the portfolio value for each iteration of foreach loop, rather print the aggregated portfolio value for each email address.
echo '<br>';
echo $email_array[$i];
echo $portfolioValue . PHP_EOL;
echo '<br>';
echo '<br>';
Reset $portfolioValue value to 0 at the end of the for loop.
So your code should be like this:
<?php
include('databasecon.php');
// GET API JSON DATA
$coinData = json_decode(file_get_contents('https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC,ETH,XRB,IOTA,XRP,XLM,TRX,LINK,USDT&tsyms=USD'), true);
//SELECT ALL MAIL
$result = mysqli_query($con, "SELECT DISTINCT email FROM user_data");
$email_array = array();
while($row = mysqli_fetch_array($result)){
$email_array[] = $row['email'];
}
// PORTFOLIO ARRAYS
for ($i = 0; $i < sizeof($email_array); $i++) {
$sql = mysqli_query($con, "SELECT DISTINCT * FROM crypto_data WHERE email = '$email_array[$i]'");
while($row = mysqli_fetch_array($sql)){
$myCoins[$row['currency']] = array('balance' => $row['amount'], 'boughtprice' => $row['price_when_bought']);
}
// 0 VALUES FOR CALCULATION
$portfolioValue = 0;
$totalNET = 0;
$Value24H = 0;
// information in json path ['RAW'] so safeguard here to be sure it exists
if (isset($coinData['RAW'])) {
// then loop on all entries $cryptoSymbol will contain for example BTC and cryptoInfo the array USD => [...]
foreach($coinData['RAW'] as $cryptoSymbol => $cryptoInfo) {
// safeguard, check path [USD][FROMSYMBOL] exists
if (!isset($cryptoInfo['USD']) || !isset($cryptoInfo['USD']['FROMSYMBOL'])) {
// log or do whatever to handle error here
echo "no path [USD][FROMSYMBOL] found for crypto: " . $cryptoSymbol . PHP_EOL;
continue;
}
// Symbol in on your json path/array [USD][FROMSYMBOL]
$thisCoinSymbol = $cryptoInfo['USD']['FROMSYMBOL'];
$coinHeld = array_key_exists($thisCoinSymbol, $myCoins);
// Only retour held
if ( !$coinHeld ) { continue; }
// get price:
$thisCoinPrice = $cryptoInfo['USD']['PRICE'];
// get symbol holding:
if ($coinHeld) {
$myBalance_units = $myCoins[$thisCoinSymbol]['balance'];
}
// calculate total holdings:
if ($coinHeld) {
$myBalance_USD = $myBalance_units * $thisCoinPrice;
$portfolioValue += $myBalance_USD;
}
}
}
echo '<br>';
echo $email_array[$i];
echo $portfolioValue . PHP_EOL;
echo '<br>';
echo '<br>';
$portfolioValue = 0;
}
?>
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection attack. Also see how you can prevent SQL injection in PHP.
Here is the code after I uploaded the raw file then tried to validate the raw file with the uploaded file to see if they match:
while ($db_fetch_row = sqlsrv_fetch_array($database_query)){
$db_eid = $db_fetch_row['eid'];
$db_team_lead = $db_fetch_row['team_lead'];
$db_role = $db_fetch_row['role'];
$db_productivity = $db_fetch_row['productivity'];
$db_quality = $db_fetch_row['quality'];
$db_assessment = $db_fetch_row['assessment'];
$db_staffed_hours = $db_fetch_row['staffed_hours'];
$db_kpi_productivity = $db_fetch_row['kpi_productivity'];
$db_kpi_quality = $db_fetch_row['kpi_quality'];
$db_kpi_assessment = $db_fetch_row['kpi_assessment'];
$db_kpi_staffed_hours = $db_fetch_row['kpi_staffed_hours'];
for($row = 2; $row <= $lastRow; $row++) {
$eid = $worksheet->getCell('A'.$row)->getValue();
$team_lead = $worksheet->getCell('C'.$row)->getValue();
$role = $worksheet->getCell('B'.$row)->getValue();
$productivity = $worksheet->getCell('D'.$row)->getValue();
$productivity1 = chop($productivity,"%");
$quality = $worksheet->getCell('E'.$row)->getValue();
$quality1 = chop($quality,"%");
$assessment = $worksheet->getCell('F'.$row)->getValue();
$assessment1 = chop($assessment,"%");
$staffed_hours = $worksheet->getCell('G'.$row)->getValue();
$staffed_hours1 = chop($staffed_hours,"%");
$kpi_productivity = $worksheet->getCell('H'.$row)->getValue();
$kpi_quality = $worksheet->getCell('I'.$row)->getValue();
$kpi_assessment = $worksheet->getCell('J'.$row)->getValue();
$kpi_staffed_hours = $worksheet->getCell('K'.$row)->getValue();
if($db_eid == $eid) {
echo "Raw and Uploaded file Matched";
} else {
echo "Did not match";
}
}
}
The output always didn't match, as you can see below:
Of course it outputs that. Let's think it through:
For every row in the DB, you are checking EVERY row in the CSV. Presumably there is only ONE row in the CSV that has the same ID as the row in the DB, so that means if there are 100 records in the CSV, it will output "no match" 99 times (assuming there is 1 record in the CSV that does match).
One approach is to separate it into a function and attempt to find the matching row, as follows:
// Loop over all DB records
while ($db_fetch_row = sqlsrv_fetch_array($database_query)) {
// call our new function to attempt to find a match
$match = find_matching_row( $db_fetch_row, $worksheet );
// If there's no match, output "didn't find a match"
if ( ! $match ) {
echo '<br>DID NOT FIND A MATCH.';
// If there IS a match, $match represents the row number to use....
} else {
var_dump( $match );
// Do your work on the match data...
$team_lead = $worksheet->getCell('C'.$match)->getValue();
// ...etc
}
}
/**
* Attempt to find a row from the CSV with the same ID as the DB
* record passed in.
*
* #param array $db_fetch_row
* #param mixed $worksheet
*/
function find_matching_row( $db_fetch_row, $worksheet ) {
$db_eid = $db_fetch_row['eid'];
// Youll need to calculate $lastRow for this to work right..
$lastRow = .... ;
// Loop through the CSV records
for($row = 2; $row <= $lastRow; $row++) {
// If the IDs match, return the row number
if($db_eid == $worksheet->getCell('A'.$row)->getValue() ){
return $row;
}
}
// If no match, return FALSE
return FALSE;
}
This question already has answers here:
How to store values from foreach loop into an array?
(9 answers)
Closed 1 year ago.
Basically I want to make a download button for my project that will produce different csv files (one csv file per table) in memory and zip before download. It works fine but the problem is that I am only getting one row (the last result) on each mysql_fetch_array where it is supposed to return rows depending on how many are stored in the database. This code is depreciated, sorry for that.
Here is my code:
<?php
require("../includes/connection.php");
require("../includes/myLib.php");
//get the ID that is passed
$ID = $_REQUEST['q'];
$ID = xdec($ID);
//All queries to fetch data
$query = mysql_query("SELECT * FROM `ge2`.`projects` WHERE `projects`.`proj_id`='$ID'");
$query2 = mysql_query("SELECT * FROM `ge2`.`attributes` WHERE `attributes`.`proj_id`='$ID'");
$query3 = mysql_query("SELECT * FROM `ge2`.`category` WHERE `category`.`proj_id`='$ID'");
$query4 = mysql_query("SELECT * FROM `ge2`.`multipletarget` WHERE `multipletarget`.`proj_id`='$ID'");
$query5 = mysql_query("SELECT * FROM `ge2`.`data_cut` WHERE `data_cut`.`proj_id`='$ID'");
$query6 = mysql_query("SELECT * FROM `ge2`.`raw` WHERE `raw`.`proj_id`='$ID'");
//getting all array
while ($row = mysql_fetch_array($query)) {
$proj_alias = $row['proj_alias'];
$proj_id = $row['proj_id'];
$date_added = $row['date_added'];
}
while ($row1 = mysql_fetch_array($query2)) {
$attrib_param_id = $row1['param_id'];
$attrib_proj_id = $row1['proj_id'];
$attrib_cat_id = $row1['cat_id'];
$attrib_val_id = $row1['val_id'];
$attrib_name = $row1['name'];
$attrib_isCust = $row1['isCust'];
}
while ($row2 = mysql_fetch_array($query3)) {
$category_cat_id = $row2['cat_id'];
$category_name = $row2['name'];
$category_proj_id = $row2['proj_id'];
$category_desc = $row2['desc'];
}
while ($row3 = mysql_fetch_array($query4)) {
$multipletarget_id = $row3['id'];
$multipletarget_proj_id = $row3['proj_id'];
$multipletarget_mtarget1 = $row3['mtarget1'];
$multipletarget_mtarget2 = $row3['mtarget2'];
}
while ($row4 = mysql_fetch_array($query5)) {
$data_cut_id = $row4['id'];
$data_cut_proj_id = $row4['proj_id'];
$data_cut_name = $row4['name'];
$data_cut_param = $row4['param'];
$data_cut_lvl = $row4['lvl'];
$data_cut_val = $row4['val'];
}
while ($row5 = mysql_fetch_array($query6)) {
$raw_id = $row5['raw_id'];
$raw_proj_id = $row5['proj_id'];
$raw_p_id = $row5['p_id'];
$raw_url = $row5['url'];
$raw_ip = $row5['ip'];
$raw_pos = $row5['pos'];
$raw_datetaken = $row5['datetaken'];
$raw_used = $row5['used'];
$raw_fdc_id = $row5['fdc_id'];
$raw_dq = $row5['dq'];
}
// some data to be used in the csv files
$records = array(
$proj_alias, $proj_id, $date_added
);
$records2 = array(
$attrib_param_id, $attrib_proj_id, $attrib_cat_id, $attrib_val_id, $attrib_name, $attrib_isCust
);
$records3 = array(
$category_cat_id, $category_name, $category_proj_id, $category_desc
);
$records4 = array(
$multipletarget_id, $multipletarget_proj_id, $multipletarget_mtarget1, $multipletarget_mtarget2
);
$records5 = array(
$data_cut_id, $data_cut_proj_id, $data_cut_name, $data_cut_param,$data_cut_lvl,$data_cut_val
);
$records6 = array(
$raw_id, $raw_proj_id, $raw_p_id, $raw_url,$raw_ip,$raw_pos,$raw_datetaken,$raw_used,$raw_fdc_id,$raw_dq
);
//making an array to be used in loop
$set = array($records,$records2,$records3,$records4,$records5,$records6);
//names to be named for each csv file
$names = array('projects', 'attributes', 'category', 'multipletarget', 'data_cut', 'raw');
// create zip file
$zipname = $proj_alias;
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
// loop to create csv files
$n = 0;
foreach ($set as $setk => $sets) {
$n += 1;
$fd = fopen('php://temp/maxmemory:1048576', 'w');
if (false === $fd) {
die('Failed to create temporary file');
}
fputcsv($fd, $sets);
// return to the start of the stream
rewind($fd);
// add the in-memory file to the archive, giving a name
$zip->addFromString('BrainLink-' . $proj_alias . "-" . $names[$setk] . '.csv', stream_get_contents($fd));
//close the file
fclose($fd);
}
// close the archive
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname.'.zip');
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
// remove the zip archive
// you could also use the temp file method above for this.
unlink($zipname);
?>
Thanks in advance.
Well, it seems that you're independently iterating over all query results and overwriting the variables over and over again. So in the end, you have only last table results to work with.
You might try using JOIN OR UNION SELECT in MySQL to get all the items in one big query result row:
$query = mysql_query('SELECT proj.*, attrs.*
FROM `projects` AS proj
JOIN `attributes` AS attrs ON (attrs.project_id=proj.project_id)
<..more tables to join in the same manner..>
WHERE proj.`proj_id`= ' . $projectId);
And then, you'll just have to iterate only over a single query resource.
while ($row = mysql_fetch_array($query)) {
//your code here
}
Note, that if tables being JOIN'ed have the same column names, they will "overwrite" each other and you'll have to rename them yourself "on the fly".
Like so:
SELECT proj.field, proj.another_field, proj.conflicting_field_name AS unique_field_name
I did not read all of your code, but in each while loop, you only save last record. It should be something like this.
while($row = mysql_fetch_array($query)){
$proj_alias[] = $row['proj_alias'];
$proj_id[] = $row['proj_id'];
$date_added[] = $row['date_added'];
}
and the others like above.
I am using a script to generate cascading dropdowns using a MySQL database.
A course is selected, then a location and from that the start date.
It has three columns: Course, Location and Start Date.
How can I rename these so that they are Course2, Location2 and Start Date2?
I have tried look for a solution but aliasing doesn't seem to work.
This is the SELECT statement:
$sql = "SELECT DISTINCT `$col` FROM `$table`".$where."ORDER BY `$col` ASC";
This is the full script I am using:
http://coursesweb.net/ajax/multiple-select-dropdown-list-ajax_t
$table = 'options';
$ar_cols = array('Course', 'Location', 'Start Date', null);
$preid = 'slo_'; // a prefix used for element's ID, in which Ajax will add <select>
$col = $ar_cols[0]; // the variable used for the column that wil be selected
$re2_html = ''; // will store the returned html code
// if there is data sent via POST, with index 'col' and 'wval'
if (isset($_POST['col']) && isset($_POST['wval'])) {
// set the $col that will be selected and the value for WHERE (delete tags and external spaces in $_POST)
$col = trim(strip_tags($_POST['col']));
$wval = "'".trim(strip_tags($_POST['wval'])).
"'";
}
$key = array_search($col, $ar_cols); // get the key associated with the value of $col in $ar_cols
$wcol = $key === 0 ? $col : $ar_cols[$key - 1]; // gets the column for the WHERE clause
$_SESSION['ar_cols'][$wcol] = isset($wval) ? $wval : $wcol; // store in SESSION the column and its value for WHERE
// gets the next element in $ar_cols (needed in the onchange() function in <select> tag)
$last_key = count($ar_cols) - 1;
$next_col = $key < $last_key ? $ar_cols[$key + 1] : '';
$conn = new mysqli($server, $user, $pass, $dbase); // connect to the MySQL database
if (mysqli_connect_errno()) {
exit('Connect failed: '.mysqli_connect_error());
} // check connection
// sets an array with data of the WHERE condition (column=value) for SELECT query
for ($i = 1; $i <= $key; $i++) {
$ar_where[] = '`'.$ar_cols[$i - 1].
'`='.$_SESSION['ar_cols'][$ar_cols[$i - 1]];
}
// define a string with the WHERE condition, and then the SELECT query
$where = isset($ar_where) ? ' WHERE '.implode($ar_where, ' AND ') : '';
$sql = "SELECT DISTINCT `$col` FROM `$table`".$where.
"ORDER BY `$col` ASC";
$result = $conn - > query($sql); // perform the query and store the result
// if the $result contains at least one row
if ($result - > num_rows > 0) {
// sets the "onchange" event, which is added in <select> tag
$onchg = $next_col !== null ? " onchange=\"ajaxReq('$next_col', this.value);\"" : '';
// sets the select tag list (and the first <option>), if it's not the last column
if ($col != $ar_cols[$last_key]) $re2_html = '<label>'.$col.
':</label> <select name="'.$col.
'"'.$onchg.
' id="'.$col2.
'"><option>Select a '.$col.
'</option>';
while ($row = $result - > fetch_assoc()) {
// if its the last column, reurns its data, else, adds data in OPTION tags
if ($col == $ar_cols[$last_key]) $re2_html. = '<br/>'.$row[$col];
else $re2_html. = '<option value="'.$row[$col].
'">'.$row[$col].
'</option>';
}
if ($col != $ar_cols[$last_key]) $re2_html. = '</select> '; // ends the Select list
} else {
$re2_html = '0 results';
}
$conn - > close();
// if the selected column, $col, is the first column in $ar_cols
if ($col == $ar_cols[0]) {
// adds html code with SPAN (or DIV for last item) where Ajax will add the select dropdown lists
// with ID in each SPAN, according to the columns added in $ar_cols
for ($i = 1; $i < count($ar_cols); $i++) {
if ($ar_cols[$i] === null) continue;
if ($i == $last_key) $re2_html. = '<p id="'.$preid.$ar_cols[$i].
'"> </p>';
else $re2_html. = '<p id="'.$preid.$ar_cols[$i].
'"> </p>';
}
// adds the columns in JS (used in removeLists() to remove the next displayed lists when makes other selects)
$re2_html. = '<script type="text/javascript">var ar_cols = '.json_encode($ar_cols).
'; var preid = "'.$preid.
'";</script>';
} else echo $re2_html;
Any help would be appreciated. I am pulling my hair out at this point! Please let me know if you need more information.
You are doing something very very weird...
I can't read your code, and I can't get your logic...
But just in case, maybe it can help you somehow:
$col2 = ''.$col.'2';
$sql = "SELECT DISTINCT `$col` as `$col2` FROM `$table`".$where."ORDER BY `$col` ASC";
Using an addon of FPDF, I am printing labels using PHP/MySQL (http://www.fpdf.de/downloads/addons/29/). I'd like to be able to have the user select how many labels to print. For example, if the query puts out 10 records and the user wants to print 3 labels for each record, it prints them all in one set. 1,1,1,2,2,2,3,3,3...etc. Any ideas?
<?php
require_once('auth.php');
require_once('../config.php');
require_once('../connect.php');
require('pdf/PDF_Label.php');
$sql="SELECT $tbl_members.lastname, $tbl_members.firstname,
$tbl_members.username, $tbl_items.username, $tbl_items.itemname
FROM $tbl_members, $tbl_items
WHERE $tbl_members.username = $tbl_items.username";
$result=mysql_query($sql);
if(mysql_num_rows($result) == 0){
echo "Your search criteria does not return any results, please try again.";
exit();
}
$pdf = new PDF_Label("5160");
$pdf->AddPage();
// Print labels
while($rows=mysql_fetch_array($result)){
$name = $rows['lastname'].', '.$rows['firstname';
$item= $rows['itemname'];
$text = sprintf(" * %s *\n %s\n", $name, $item);
$pdf->Add_Label($text);
}
$pdf->Output('labels.pdf', 'D');
?>
Assuming that a variable like $copies is an integer of how many copies they want made, I would make the following modification:
// Print labels
while( $row = mysql_fetch_array( $result ) ){
// Run Once for Each Result
$name = $row['lastname'].', '.$row['firstname'];
$item = $row['itemname'];
$text = sprintf(" * %s *\n %s\n", $name, $item);
if( isset( $copies ) ) {
// The Copies Variable exists
for( $i=0 ; $i<$copies ; $i++ ) {
// Run X times - Once for each Copy
$pdf->Add_Label($text);
}
} else {
// The Copies Variable does not exist - Assume 1 Copy
$pdf->Add_Label($text);
}
}
This should provide the required functionality.