I'm encountering a problem with the generation of a number which increases everytime an operation is called.
When the value arrive to 10, i can't print 11 and so on...
$this->sql = "SELECT codice FROM accettazione ORDER BY id DESC LIMIT 1";
if ($result = $this->hookUp->query($this->sql)) {
if ($result->num_rows > 0) {
while ($rw = mysqli_fetch_array($result, MYSQLI_BOTH)) {
(int)$codice = substr($rw['codice'], -1);
if ($codice < 9) {
$rw['codice'] = date("Y") . ".0000";
} else /*if ($codice == 9 || $codice < 99)*/ {
$rw['codice'] = date("Y") . ".000";
}
echo $rw['codice'] . ++$codice;
}
} else {
echo date("Y") . ".00001";
}
} else if ($this->hookUp->query($this->sql) === false) {
echo "fail";
}
}
The goal is to print 00001 when the value is lower than 10, ++00010 when lower than 100, ++00100 when lower than 1000, and so on...
When the code is 00010, at 00011, the value goes back to 00001 (if ($result->num_rows > 0) isn't satisfied anymore).
In the mySQL table, $rw["codice"] is a VARCHAR.
Why?
I guess you want your values displayed with leading zeros. That is:
1 displayed as 00001
9 displayed as 00009
11 displayed as 00011
1234 displayed as 01234
This is a requirement as old as the IBM 029 keypunch machine. (If I guess incorrectly, please edit your question.)
It's easy in php using sprintf.
$string_codice = sprintf('%05d', $codice);
EDIT
I think you're doing this the hard way. It looks like you want a string that reads 2015.00001 or 2015.09876 or suchlike. But I'm not confident guessing your requirements from your code. For one thing, I don't know what the values in your codice column in your database table look like.
Maybe you could try something like this.
/* assume the counter starts at zero */
$codice = 0;
if ($result->num_rows > 0) {
/* fetch the counter value from the table if nay. */
while ($rw = mysqli_fetch_array($result, MYSQLI_BOTH)) {
(int)$codice = $rw['codice']; /* no substr */
}
}
/* add one to the value and format it YYYY.000nn */
$codice++;
$stringval = date("Y") . "." . sprintf('%05d', $codice);
echo $stringval;
Related
I have a set of numbers from MySQL within the range 1000 0000 (8 digits) to 9 999 999 999 (10 digits). It's supposed to be consecutive, but there are missing numbers. I need to know which numbers are missing.
The range is huge. At first I was going to use PHP to do this:
//MySqli Select Query
$results = $mysqli->query("SELECT `OCLC Number` FROM `MARC Records by Number`");
$n_array = array();
while($row = $results->fetch_assoc()) {
$n_array[] = $row["OCLC Number"];
}
d($n_array);
foreach($n_array as $k => $val) {
print $val . " ";
}
/* 8 digits */
$counter = 10000000;
$master_array = array();
/* 10 digits */
while ($counter <= 9999999999 ) {
$master_array[] = $counter;
$counter++;
d($master_array);
}
d($master_array);
$missing_numbers_ar = array_diff ($master_array, $n_array);
d($missing_numbers_ar);
d() is a custom function akin to var_dump().
However, I just realized it would take tons of time for this to be done. At the 15 minute mark, $master_array is being populated with only 4000 numbers.
How can I do this in a quicker way? MySQL-only or MySQL-and-PHP solutions both welcome. If the optimal solution depends on how many numbers are missing, please let me know how so. Tq.
Your d() probably is the cause of slowness, please remove it, and make small changes in your code
while($row = $results->fetch_assoc()) {
$n_array[$row["OCLC Number"]] = 1;
}
and
$missing_numbers_ar = [];
while ($counter++ <= 9999999999 ) {
if (empty($n_array[$counter])) {
$missing_numbers_ar[] = $counter;
}
}
If the following is still slow I would be surprised. I also just noticed it is similar to #Hieu Vo's answer.
// Make sure the data is returned in order by adding
// an `ORDER BY ...` clause.
$results = $mysqli->query("SELECT `OCLC Number`
FROM `MARC Records by Number`
ORDER BY `OCLC Number`");
$n_array = array();
while($row = $results->fetch_assoc()) {
// Add the "OCLC Number" as a key to the array.
$n_array[$row["OCLC Number"]] = $row["OCLC Number"];
}
// assume the first array key is in fact correct
$i = key($n_array);
// get the last key, also assume it is not missing.
end($n_array);
$max = key($n_array);
// reset the array (should not be needed)
reset($n_array);
do {
if (! $n_array[$i]) {
echo 'Missing key:['.$i.']<br />';
// flush the data to the page as you go.
flush();
}
} while(++$i <= $max);
We have 2 while loops , we are displaying 2 different results with both.
we need to combine or without combining we need to merge 2 results.
in below image ,
1st while loop result = > 1st, 2nd, 6th rows.
2nd while loop result = > 3rd, 4th, 5th rows.
we need 3rd , 4th & 5th rows results in 1st, 2nd 6th rows in last 2 columns [ Paid status & commission ].
1st while results coming from Database 1 & 2nd while results are coming from Database 2 with table [order_details]
$stmt = $user_home->runQuery("SELECT * FROM order_details");
$stmt->execute(array(":uid" => $_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->execute();
$i = 0;
foreach($order as $orderData)
{
$k = 0;
$orderitems = $orderData['dproduct_id'];
$orderitemsarray = explode(",", $orderitems);
/* 1st while */
while ($k < count($orderitemsarray))
{
if ($orderitemsarray[$k] != '0')
{
$stmtorders = $user_home->runQuery("SELECT * FROM order_details");
$stmtorders->execute(array(":dorder_id" => $orderData['entity_id']));
$roworders = $stmtorders->fetch(PDO::FETCH_ASSOC);
$dorderStatus = $roworders['dpaid_status'];
$productdetail = Mage::getModel('catalog/product')->load($orderitemsarray[$k]);
$designer_id = $productdetail->getDesignerID() ;
if($accountType == "admin")
{
$designerName = getDesignerName($productdetail->getDesignerID()) . " -(" . $productdetail->getDesignerID() . ")";
$responce[] = array(
$orderData->getIncrementId() ,
$orderitemsarray[$k],
$productdetail->getName() ,
$designerName,
$orderData['status'],
$data['dpaid_status'],
$data['commission'],
$sDate
);
}
}
$k++;
$i++;
}
/* 2nd while */
while($data = $stmt->fetch())
{
$responce[] = array(
$data['dorder_id'],
$data['dpaid_status'],
$data['commission']
);
$k++;
}
}
I tried below code , but it results as below image - means only 2 rows displayed instead of 23 rows....
while (($k < count($orderitemsarray)) && ($data = $stmt->fetch()))
Full page looks as below :
I am new to php world & tried lot before posting here....
The thing is whenever you use empty brackets [] an index is automatically assigned which is equal to the next available numeric value and your data ends up in a next position so correct index is equired to solve this issue .
In while (($k < count($orderitemsarray)) && ($data = $stmt->fetch()))
If either of condition fails then loop ends and your $data probably has only three entries it's showing only that many even though $orderitemsarray has many more , i am not sure but you can prolly replace while with if statement and change index like this to make those stuff append on same row
$indx=0;
foreach($order as $orderData)
{
$k = 0;
//.. Stufff
/* 2nd while */
if($indx == 0 || $indx == 1 || $indx == 5)
{
if($data = $stmt->fetch())
{
$size = count($responce); // get size from that get its last index
$responce[$size-1] = array(
$data['dorder_id'],
$data['dpaid_status'],
$data['commission']
);
$k++; //<-- not sure why it's here but doesn't matter may be some magento stuff?
}
}
$indx++
}
EDIT:sry my bad , ignore my last comment try this instead
$responce[$size-1] = array_merge($responce[$size-1] , array(
$data['dorder_id'],
$data['dpaid_status'],
$data['commission']
) );
I currently have:
// connect for other mins
$sql = "SELECT sum(mins) FROM completed_activity WHERE member_id = '$_SESSION[SESS_MEMBER_ID]' AND exercise != 'Personal Training' AND date >= '$mon'";
But, when the date is not within the where clause, nothing is shown. I'm not even getting my 'else' statement.
Any ideas?
MAYBE SOLVED
I may have got the correct way of doing it with:
$sql = "SELECT sum(CASE WHEN member_id = '$_SESSION[SESS_MEMBER_ID]' AND exercise != 'Personal Training' AND date >= '$mon' THEN mins ELSE 0 END) AS mins FROM completed_activity";
Can anyone confirm if this looks right?
When using SUM, there are at least one result returned. The result of SUM may be 0 or more.
That's why your code is not working correctly.
Try the following code:
// connect for other mins
$sql = "SELECT sum(mins) AS mins_sum FROM completed_activity WHERE member_id = '$_SESSION[SESS_MEMBER_ID]' AND exercise != 'Personal Training' AND date >= '$mon'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$mins = $row["mins_sum"];
if ($mins > 0) {
echo "yes";
} else {
echo "no";
}
}
I dont know php code, But When No condition matched sql query will return 0.
Means There will be atleast 1 record. So your if condition will always true.
Improve condition to check for value like
if ($result['sum'] > 0) { //Check for syntax
while($row = $result->fetch_assoc()) {
$mins = $row["mins"];
echo "yes";
}
} else {
$mins = 0;
echo "no";
}
I implemented code in PHP for linear regression, the idea was to take delivery date for each customer (however many delivery dates per customer there were in the DB) and then to use these delivery dates (converted to days) as a linear regression equation as the y parameter, to eventually prediction a future delivery date/order date, and based on this prediction and comparison to the current date, the system would take some action like send push notification reminders. My code for the implementation is as follows:
$conn = mysql_connect($dbhost,$dbuser,$dbpass) or die (mysql_error());
mysql_select_db($db, $conn) or die(mysql_error());
//Outer Loop to save all eligable customer ID's
$idarray=array();
$firstloop=mysql_query("Select id FROM ordering GROUP BY id",$conn);
$number_of_rows_initial=mysql_num_rows($firstloop);
while (($row = mysql_fetch_array($firstloop, MYSQL_ASSOC)) !== false){
$idarray[] = $row; // add the row in to the results (data) array
// print_r($idarray);
}
for($counter=0; $counter<$number_of_rows_initial; $counter++)
{
$id=$idarray[$counter]['id'];
//First confirm if user is already registered via website
$result = mysql_query("SELECT TO_DAYS(date) FROM ordering WHERE id=$id",$conn);
$num_rows = mysql_num_rows($result);
// mysql_query($result,$conn) or die(mysql_error();
//echo $num_rows;
$data = array();
$days=array();
$xAxis=array();
$ldate=array();
while (($row = mysql_fetch_array($result, MYSQL_ASSOC)) !== false){
$data[] = $row; // add the row in to the results (data) array
}
// print_r($data); // print result
//This part is working now!!!!
for ($x = $num_rows-1 ; $x > 0; $x--) {
$days[$x] = $data[$x]['TO_DAYS(date)'] -$data[$x-1]['TO_DAYS(date)'];
$xAxis[$x]=$x;
}
$days[0]=30;
print_r("<br />",$days);
//print_r($xAxis);
//my implementation of regression calculation
// calculate sums
$x_sum = (array_sum($xAxis));
$y_sum = array_sum($days);
echo "<br />","Customer ID is: ",$id,"<br />";
echo "Sum of X Axis: ",$x_sum, "<br />";
echo "Sum of Y Axis: ",$y_sum,"<br />" ;
$xx_sum = 0;
$xy_sum = 0;
for($i = 0; $i < $num_rows; $i++) {
$xy_sum+=($xAxis[$i]*$days[$i]);
$xx_sum+=($xAxis[$i]*$xAxis[$i]);
}
// calculate slope
$m = (($num_rows * $xy_sum) - ($x_sum * $y_sum)) / (($num_rows * $xx_sum) - ($x_sum * $x_sum));
// calculate intercept
$b = ($y_sum - ($m * $x_sum)) / $num_rows;
$predict=($m*($num_rows+1))+$b;
echo "The Slope of the Representative line is: ",$m,"<br />";
echo "The Y intercept is ",$b,"<br />";
echo "Predicted next date of delivery in days (from last delivery date) is: ", $predict,"<br />";
//Final Date Calculation
$lastdate=mysql_query("SELECT TO_DAYS(date) FROM ordering WHERE id=$id",$conn);
$num_rows_date = mysql_num_rows($lastdate);
while (($row_date = mysql_fetch_array($lastdate, MYSQL_ASSOC)) !== false){
$ldate[] = $row_date; // add the row in to the results (data) array
}
echo "Total number of records for the given id are: ",$num_rows_date, "<br />";
$ldatefinal=$ldate[$num_rows_date-1]['TO_DAYS(date)'];
echo "Last date in the records for the given ID is ",$ldatefinal,"<br />";
echo "Last date + Prediction days = ",$ldatefinal+$predict,"<br />";
$currentdate=mysql_query("SELECT TO_DAYS(CURDATE())",$conn);
$dcrow = mysql_fetch_assoc($currentdate);
//$dhold=$dcrow['TO_DAYS(CURDATE())'];
//echo "Current Date is: ",$dcrow['TO_DAYS(CURDATE())'],"<br /" ;
//UPON EXECUTION NOTHING BELOW GETS ExEcuted ??
//echo "Last date + Predicted days = ";
if (( (($ldatefinal+$predict) - $dcrow['TO_DAYS(CURDATE())']) <3 )&& $predict>0){
echo "Time to Order<br />","</br />";
}else if((( (($ldatefinal+$predict) - $dcrow['TO_DAYS(CURDATE())']) >3 && $predict>0) )){
echo "You Got Gas!!<br />","</br />";
}else{
echo "Linear Regression not Suitable for this Record ID","<br />";
}
}
mysql_close($conn);
Every thing seems to work perfect except for the times when the prediction comes up with negative numbers, I have for now chosen to ignore these by using the " echo "Linear Regression not Suitable for this Record ID","";" but I am sure there must be a better way to accommodate this type of scenarios, I am just not sure how to in my case, especially using the date format. Any help would be greatly appreciated. I must say this forum and of course its users have been extremely kind and generous with their time and knowledge in the past for me, and hope you guys can point me in the right direction this time as well. Hamood
A small background of myself is that I'm fairly new to php. I work as an IT assistant and have been asked to edit one of the pages our designers use for samples. I cannot point you to the page as it is an internally hosted page.
I'm honestly not even sure if the question is asked correctly but please bear with me.
The page has a 'request completion date' field within a table that outputs 6 dates in a list, the designers only want it to output the latest date from that list instead of all 6, usually these will be empty so it's no use having them printed.
The code to put them is as follows;
if ($database_data['request_confirmed_comp_date'] > "0")
{ $request_confirmed_completion_date = date("d/m/Y", $database_data['request_confirmed_comp_date']); }
else
{ $request_confirmed_completion_date = " -"; }
if $database_data['request_confirmed_comp_date2'] > "0")
{
$request_confirmed_completion_date2 = date("d/m/Y", $database_data['request_confirmed_comp_date2']);
}
else
{
$request_confirmed_completion_date2 = " -";
}
if ($database_data['request_confirmed_comp_date3'] > "0")
{
$request_confirmed_completion_date3 = date("d/m/Y", $database_data['request_confirmed_comp_date3']);
}
else
{
$request_confirmed_completion_date3 = " -";
}
if ($database_data['request_confirmed_comp_date4'] > "0")
{
$request_confirmed_completion_date4 = date("d/m/Y", $database_data['request_confirmed_comp_date4']);
}
else
{
$request_confirmed_completion_date4 = " -";
}
if ($database_data['request_confirmed_comp_date5'] > "0")
{
$request_confirmed_completion_date5 = date("d/m/Y", $database_data['request_confirmed_comp_date5']);
}
else
{
$request_confirmed_completion_date5 = " -";
}
if ($database_data['request_confirmed_comp_date6'] > "0")
{
$request_confirmed_completion_date6 = date("d/m/Y", $database_data['request_confirmed_comp_date6']);
}
else
{
$request_confirmed_completion_date6 = " -";
}
if ($database_data['request_date_required'] > "0")
{
$request_date_required = date("d/m/Y", $database_data['request_date_required']);
}
else
{
$request_date_required = "-";
}
if ($database_data['request_date'] > "0")
{
$request_date = date("d/m/Y", $database_data['request_date']);
}
else
{
$request_date = "-";
}
It is then called into play using;
echo '<td><b>1.</b>'.$request_confirmed_completion_date.'<br /><b>2.</b>'.$request_confirmed_completion_date2.'<br /><b>3.</b>'.$request_confirmed_completion_date3.'<br /><b>4.</b>'.$request_confirmed_completion_date4.'<br /><b>5.</b>'.$request_confirmed_completion_date5.'<br /><b>6.</b>'.$request_confirmed_completion_date6.'</td>';
Now I may not have much php knowledge, but I know that's a horribly long way of doing that. Is there anyway that I could pull the latest date out of an array, created by the the first block of code, and then output them into the table.
Thanks for any help or advice, even if you could just point me in the right direction as to what loop to use would be helpful.
Edit: I've uploaded the full file online here, hopefully that will clear up some confusion.
You want to use the php function asort. Since all of your values look to be numeric, you should be able to do a standard sort and pull off the last item with array_pop.
It might look something like this:
asort($database_data);
$latest = array_pop($database_data);
echo date('m/d/Y', $latest);
Create an array with the variable names, like if the variables are $A, $B and $C, then
$vars = array("A","B","C");
foreach($vars as $var_name){
if($database_data[$var_name] > "0")
$$var_name = $database_data[$var_name];
else
$$var_name = "-";
}
Note: A, B and C are dummy variable names, as the variable names are too long in your code :-)
Firstly there is a problem with your if conditions, you can't say $x > "0" because with using double-quotes you are using 0 as a string. You should use integer $x > 0.
Now here my answer :
I couldn't understand your system very well, so i'm assuming always there will be 6 dates.
for($q = 0;$q < 6; $q++)
{
if($database_data[...][$q] > 0)
$dates[] = date("d/m/Y", $database_data['...'][$q]);
else
$dates[] = " - ";
}
As you see, you have to fetch your database datas as an array $database_data['...'][].
If you can tweak the original SQL statement, which probably looks something like this:
select request_confirmed_comp_date, request_confirmed_comp_date2, request_confirmed_comp_date3, request_confirmed_comp_date4, request_confirmed_comp_date5, request_confirmed_comp_date6
from sometablename
where somefield='something'
You can tweak it to use shorter (and consistent) field names
select request_confirmed_comp_date as date1, request_confirmed_comp_date2 as date2, request_confirmed_comp_date3 as date3, request_confirmed_comp_date4 as date4, request_confirmed_comp_date5 as date5, request_confirmed_comp_date6 as date6
from sometablename
where somefield='something'
And then in PHP use an array to iterate over the field names like so:
<?php
$lastCompletionDate=""; //start by assuming there was no completion date
for($i=1;$i<=6;$i++) { //check to see if any field is after the last known completion date
if ($database_data['date'.$i] && (date("d/m/Y", $database_data['date'.$i]) > $lastCompletionDate)) {
//if so, store the new date
$lastCompletionDate=date("d/m/Y", $database_data['date'.$i]);
}
}
if($lastCompletionDate) {
echo "The last completion date was $lastCompletionDate\n";
}else {
echo "There was no completion date.\n";
}
?>
An alternative solution would be to use the SQL engine's own internal functions to find the highest date like so:
select greatest(request_confirmed_comp_date,
request_confirmed_comp_date2,
request_confirmed_comp_date3,
request_confirmed_comp_date4,
request_confirmed_comp_date5,
request_confirmed_comp_date6) as greatestcompdate
from sometablename etc...
and then refer to that in PHP like
<?php
if($database_data['greatestcompdate']) {
echo "There was a greatest completion date and it was $database_data[greatestcompdate]";
}
?>