Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    PHP




Data/math Functions With Php/mysql


Hey everybody, I have a tricky problem that i need to solve... I'm currently using apache/php/mysql , developing a custom ticket system... now i'm working on one of the final parts which are reports...

here is the scenario: I have a few rows of dates, such as when a ticket was opened and when that same ticket was closed...

ie: open_ticket, closed_ticket

I need to calculate the number of days it took me to complete each ticket, then i need to calculate the MEDIAN time it took me to complete tickets...

see, kind of tricky, I noticed that mysql can do averages, but can it do MEDIAN values?




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Basic Math Functions
What's the codes for basic math functions, like +,  - , / , * , %

MySQL Date Math
I have this query to sum timesheet entries in my application. The user can enter hours and/or minutes and then we calculate the value. My question is about whether I can change the value back to hours:minutes for printing. This is my query right now:

SELECT timesheet_entries.id, Sum(COALESCE(timesheet_entries.hours,0))  + Sum(COALESCE(timesheet_entries.minutes,0)/60) AS Rtotal FROM timesheet_entries  GROUP BY timesheet_entries.id

It takes the hours and the minutes and combines them to output a number like 3.5 for 3 hours 30 minutes. Is there a way to break that number back down and convert it to at least look like 3:30. Some users, in testing, are getting confused by the output of 3.5 after entering 3 hours and 30 minutes (which is annoying but I digress.)

Which Functions To Use For Data Loading
I need to make a script where users will upload a comma seperated values (CSV) text file which will be inserted in a table. The user must be able to review and approve the extracted data from the CSV file before it is inserted in the table. There could be up to 1000 rows of data. What PHP functions must I utilize to complete this script?

Forms Data Format (FDF Functions)
Anyone used FDF functions in PHP like to share ideas how to populate, say a HCFA1500.PDF file from a MySQL database? Where do I start :-O ? Do I need to install the PDFlib at all? Or is it included in the PHP libraries already?

What Functions Should I Use To Fetch Data From A Flat File ?
What functions should i use to fetch data from a flat file ?

PHP MySQL Functions
Does anyone have any php funcitons already written for querying the database etc..?

MySQL Functions Are Undefined
I have php4 and mySQL. When I call a mySQL function such as mqsql_connect() I get ERROR undefined function.
Please help, THe dll is in the folder but I have no idea how to resolve this, other people have also had this problem.

Php Mysql Api Functions - Speed
is there a difference in script overhead/speed when using mysql_fetch_array vs. mysql_fetch_object? Is there a reason to use one over the other in any given circumstance?

Fastest MySQL Functions
i was wondering if anyone knows what the fastest mysql functions/libraries there are. i was reading that mysqli is up to 40x faster than mysql, but wasn't sure if i should use the object vers or just the function based ones.. also, if there's anything faster?

PHP Is Not Recognizing MySQL Functions
Whenever I try to use a mysql function (such as mysql_connect("localhost","root","mypassword") with mypassword being my actual password), viewing the page in mozilla reveals this error message:

Fatal error: Call to undefined function: mysql_connect() in /var/www/html/index.php3 on line 14

I'm pretty sure that this means it has no definition for that function, and thus can't execute it. It does this for all mySQL stuff. I am doing this on a 9.1 Mandrake Linux installation with PHP v. 4.3.1 and mySQL 4.0.14. To install mySQL for PHP, I used
urpmi php-mysql as suggested by my phpinfo() page. Both PHP and mySQL work fine on their own, just not together.

Mysql Time Functions
This represents 2 fields in a mysql database
[login] => 2005-08-22 18:04:41
[logout] => 2005-08-22 18:05:08

I want to find out the difference between these 2 times.
I don't have access to mysql's DATEDIFF function.

How do I do this ? Its there perhaps, a web page that explains how ?
I have looked at the date and time functions of the mysql manual but i
don't understand it.

PHP Version 4.2.2 Mysql Functions
I have a collectionof PHP/MySQL scripts that used to work great when I was using PHP 4.0.x. However I recently 'upgraded' to version 4.2.2 and none of them work. I looked through php.net for info on this, but couldn't find what I was looking for.

The script below works great on my old version of PHP, but I am always getting a "mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /www/htdocs/xxx/xxx.php on line 24" The script looks like this: Code:

Arrays And While Mysql Functions
How can I get this array to work? I am trying to add data to an array for every row of data? This is a sellection of queries that I need to parse into an array so a function can use the arra to draw a graph. I am new to arrays how can I get this to work? Code:

Mail Functions And MySQL
Okay I have created a script that post user information to mysql database. Now I would like to be able to send a webpage to each user based on there place and state, but the code below sends to one user multiple pages.

What is wrong with this code or is there something better to use to do this? ....

MySQL: External SQL Functions Exported By DLLs
Sorry for being a little off-topic, but I guess PHP
users are often MySQL users too.

We have a few rather advanced calculation routines
developed in C++. Currently we are using a Sybase ASA
database for our app. and these routines are accessible
by so called external functions exported by a DLL
(dynamic link library) that we wrote in C++. Sybase
supports this quite nicely.

The client app can call such routines by:

"select get_roof_angle() as angle from dummy;"
or
":angle = call get_roof_angle();"

Now we are checking if other databases can provide us
with similar abilities. So I just wonder if MySQL
supports the ability to call a routine exported by a
DLL? If yes, does anyone know the SQL syntax to declare
it in MySQL.

PHP Needs To Clear Memory After Making Mysql Functions?
I use $result=mysql_fetch_array(...), I need to clear memory there or it happens automatically?

Comparing Form Data To Mysql Data
Im interested in building a script that would take form data, a variable like an address, and compare it with a known address in a mysql table (called addresses), then if there is a match log the address information in a separate table called (addresslog), and return the visitor to a certain page. If there is no match between the address entered in the form and known addresses then the information is still logged into the addresslog database but the visitor will be sent to a different page.

I'm still new to this, and am working through the logic and the syntax, but I believe I'm close. It's still not working, I have all of the proper tables, maybe I'm way off with the coding so I thought I would seek out some expert advice. Here's the entire script with as much explanation as I could give. PHP Code:

Session.save_path Appears To Affect Mysql Functions
I was installing a script did not want to place session variables in
the standard php directory.

After changing the session_save_path in the scripts .htaccess file, the
mysql_connect stopped functioning, function_exists('mysql_connect')
returned False. I suspect the whole mysql library stopped functioning.

Is this a known bug in PHP's mysql handling?

Math
I'm doing some php math and need to divide a floating point number
variable by only 4 decimal places - when I do the following:

$aspect_ratio = 942 / 760;
$new_height = $target_width * $aspect_ratio;

In PHP $aspect_ratio claculates to 1.2394736842105 but for my purposes
I need only 1.2394

How can I limit the decimals to just 4 places?

Need Some Serious Math Libaries
I'm in dire need of some php libraries / classes. Specifically:

- basic statistical/probability calculations
- prefferably more advanced ones that can deal with asymetric normal distributions
- a linear programing solver


I highly doubt the last two exist in php, but maybe somebody knows of a way of using some other GPL software to solve linear progaming problems or do some more advanced statistical calculations and then somehow access them through PHP (maybe WDDX?)

It seems there are a few open source LP solvers written in C. Any ideas on how i might interface with them?

Any Math Guru's Out There?
I am not good at math, if you can find a dumbed down tutorial on this
I'd appreciate it. I am trying to come up with a function that will
find the distance between two points within a cube.

The function eventually will be fed three co-ordinates, x y & z.

Point 1 could be 290 : 195 : 132
Point 2 could be 136 : 201 : 8

Has anybody done this before? If so can you throw this poor dog a bone,
I can code PHP and anything just fine, alas my poor math is letting me
down on this one. (I've checked out the math functions in PHP hoping
this had already been done to no avail).

PHP Math Calculation
I am trying to perform a simple calculation from variables passed from a form. The code is as follows:

<?php
echo "Bonus for the year: <b>";
$x = (($awage * $nibt) + ($awage * $ratio));
$x = number_format($x, 2);
print $x;
echo "</b><p>";
$xtmp = ($x + $qtr);
print $xtmp;?>

The calculation multiplies two different values (based on values from the previous page), and then sets it equal to $x. The first calculation prints fine, but when I try to add it to $qtr (also passed via radio button from previous page), it doesn't calculate correctly.

I found that if I hard-code the values for $x and $qtr after I print $x, then it will calculate correctly. I am thinking that I am using the variables incorrectly somewhere.

A Math Puzzler For You
I have a php code that generates numbers. sometimes is generates whole
numbers but most of the time decimals. How can I, when it generates a
whole number, convert the number to n.0
where n is the whole number?

For example 23 := 23.0

Math Logic
I'm writing a script to do some calculations on gambling odds. I don't have a direct PHP question, but a math question related to my script. There are some smart people around here so I thought I'd ask. If someone can answer my question and explain the logic that would be great.

The house edge is 1.41% and a winning bet pays 2:1. However, for every $1 lost on the game, the player only has to pay $.55. Given these circumstances, what is the modified house edge?

Date Math
I'm using PHP 4.4.4. If I have a date of the form

$curDate = date("Y-m-d");

How do I get the date 6 months from this date?

Check My Math!
Not sure about you, but when I run this, it tells me 59001.31 doesn't
equal 59001.31. Change each side of the equation by a hundreth or two
and it checks. Change it a bit more, and it won't.

_What_ is going on here?!

<?php
$subtotal=59001.31;
$principal=58605.33;
$interest=395.98;
$check=$principal+$interest;
echo("<pre>");
echo("Check: " . $check . "
");
echo("Subtotal: " . $subtotal . "
");
if($check!=$subtotal) {
echo("Check (" . $check . ") does not equal subtotal (" .
$subtotal . ")"); // Check doesn't equal subtotal
}
else {
echo("Check (" . $check . ") equals subtotal (" . $subtotal .
")"); // Check does equal subtotal
}
echo("</pre>");
?>

Math Formula
I am trying to put the following math formula in php, but I know to little
of math to do it I guess, maybe somebody can help me out.

This is the formula:

x = (-ln(1) - ln(y/100))*100*z

The values for y and z will be submitted via a form.

Basic Math
<?php
$variable = "random number here";
$percentage = $variable - 10%;
// $percentage allways will contain 90% of whatever the monetary value was in variable
?>
Is the above correct, and 100% accurate?

Math Problem
I cannot add say 1,000 and 1,000

$total = '1,000' + '1,000';
when you echo $total it comes out '2'

yet if I do $total = '1000' + '1000'; it echos out '2000' like it should, one problem. All my pricing values have commas in them. Almost all if not all will always contain a comma and NOT a period. Just wondering how in the check can I remove the comma, add the values, then replace it?

BTW, it's for a profit/loss chart. It scans a list a purchased and sold vehicles and does some math and spits out totals. Values are stored as a VARCHAR(20) in the database. Not sure what needs to be done, not sure if storing the numbers different would fix the problem or what.

Doing Math With Timestamp
got a DB with TimeIn and TimeOut Fields, they are set up as INT and am using strtotime when these fields are populated.

I can get the math to find out the amount of time allotted between the two times

<SNIPPET>
$doseconds = $row_getLastPunch['TimeOut'] - $row_getLastPunch['TimeIn']
</SNIPPET>

Now I know to take the number and divide by 60 to get the minutes, and then another 60 to get the hours.

here  is where my problem starts and my skill level stops.

Say I have a final answer that breaks down to 98 minutes (5880 seconds) when I go to get the hours (98 divide by 60) I get '1.6333~ hours' which is correct math, I would rather it display '1:38 hours'  or something close to that.

Multiplication Math Not Working ?
I had this in a function - so I've just moved this out of the function
for readabilty.

Can someone please tell me WHY does this not return the result of :
n1 times n2

As I said - I took it out of the function just for readability :
In my php file :

Strange Math Result... 1-1= -1 ???
See something weird on this result?

632.35 - 632.35 = -1.13686837722E-013

If anyone has seen something similar, please let me know!

this a part of the code:

$total_due = abs( $order_total ) - abs( $total_paid );
echo( $order_total . " - " . $total_paid . " = " . $total_due );

I've added the abs() in order to be sure that I'm dealing with
numbers, I've also used is_numeric() and confirmed it.
The echo() is showing the result I pasted up there.

Simple Math From Form
I'm trying to setup some simple math to happen after a form submission occurs.
Here a snippet of the current code MySQL submit code:

<?php
$con = mysql_connect("localhost", "xxx", "xxx");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("db", $con); $sql="INSERT INTO ATS2007 (value1, value2, value3) VALUES ('$_POST[value1]','$_POST[value2]','$_POST[value3]'" ;if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());  }

Essentially what I want it to do is this - > (Value2 - Value1) and then store it at Value4. Is this something that I do in the form action code (as show above) or in the form itself?

Which Is Fast, For Math Purposes
Lets say (hypothethically) I have an array of 2000 numbers and I need to perform 1000 actions on these numbers.

and my server allows me to upload c/c++ scripts.  Would it be faster to use php to do the 2 million math operations or allow C/C++ to run it and use the return of that as the done function.  I'm not asking is C/C++ faster than php i'm asking is the bonus from going to C/C++ enough to compensate for the function exec().

Issues Working With Complex Math
I'm having a little bit of trouble trying to implement some arithmetic
logic into an application that I'm working on, and I'm hoping that
somebody can possibly point me in the right direction. I am working
with a database with ZIP codes, latitudes, and longitudes, and am
working to implement the Haversine formula alongside with another
formula for creating a "box" that I can use to get locations from within
a square (or as close as you can get with the Earth, anyway).

While I was reading up on the math and working through the problem, I
wrote a function (well, two) in the bc calculator language to process
this information manually while initially working with the concepts.
Now that I have a semi-functional understanding of the problem, I
rewrote the logic in PHP, and am having a problem actually computing
longitude portions of coordinates for the "box" that I want to use to
pull data about a given region.

The problem as best as I can tell resides in the latlong_box($lat,
$long, $miles) function that I've written in PHP, but I'm not seeing
anything different, computationally, from what I've implemented in bc;
of course, I could just be suffering from staring at it too long, too.
:-) I'm not sure if I am expecting something that PHP won't provide, or
if I'm handling something not quite right in PHP's arithmetic eyes, or
what, really. The latitudes being computed are correct, it's just the
longitudes that are way off.

I will go ahead and give a link to the code and include a sample run of
the script. I appreciate any help/pointers!

The sample run:
./zip_test.php
Array
(
[zipcode] => 30034
[latitude] => +33.6907570
[longitude] => -084.2511710
[city] => DECATUR
[state] => GEORGIA
[abbr] => GA..

Resources For Simple Math Form?
I am very new to PHP, and I am wondering if anyone can point me towards an example of how to use a PHP form to have the user input some values, perform a mathematical operation, and then write out the answer on the same screen?

For example, the form would have 2 input fields, assigned to variable_a and variable_b respectively. I would like the user to input the integers, click a "calc" button, and have the script print out something to the effect of "the answer is" and then the sum of the values.

I am working this up towards a more complex mathematical equation, which I am sure I could get working if I could find a simple example of this somewhere.

Basic If Statement Involving Math.
I am running the following code:

$total = 0;
if ($total > 0); {
  $average = $sum/$total;
  echo "Sum: $sum / Total: $total"; }

When I try to tun the code I get the following error:
Warning: Division by zero in /home/superman/public_html/comics/comicvote.php on line 14

I understand that division by 0 is not allowed, but shouldn't the if statement prevent that division from running?

Math Between Table Columns And Updating Values
Basically what i want to do is simple math. I want to pull the value of one column add a percentage to it and update another column with that new value.

column a + 55% = column b updated.

I have 12k prices to update, other wise this would probably be easy.

Math: Calculating Latitude And Longitude Between Two Points..
I have a bit of a problem with a pretty complicated mathematical
expression. Basically, I'm trying to determine the initial heading
between two points on the globe using latitude and longitude of the
two points. I already know the distance between the two ($miles).

Here's the expression:

$Hdg=2*M_PI-acos((sin($lat2)-sin($lat1)*cos($miles))/(sin($miles)*cos($lat1)));

When I echo $Hdg, I see:

-1.#IND

If the expression was working, I should see something like 134.9 for
the following latitude/longitude combinations:

$lat1 = 33.9780761
$lon1 = -83.9623772
$lat2 = 32.1950556
$lon2 = -81.8695556
$miles = 172.7381359

I can't find any references to what #IND means, so if anyone out there
has any ideas, I'd be grateful.

Modifing Record Without Update (basic Math)
I have a table that has numeric data type float on which I perform a simple update on base  on a store ID What I would like to do is instead of doing an Update, is add or subtract a value to the existing value in the table. Example Code:

Math On Large Base 10 & 16 Unsigned Numbers
I'm trying to add the uniqid() base 16, to a large (15 - 18 bit) base 10 number, store both, later retrieving both numbers and subtracting. Is this possible to do without the results going into scientific notation?

DBM Functions:: Undefined Functions Error
I have been trying to use the DBM Functions (dbmopen etc) in php but always get an undefined funtion error. Do I need to load something or change something in the .ini file to get it to work?

thanks
MIke

Get Mysql Data
I have a database, and what I want is for people to be able to put in a number from the database and it pull up their info and put into a form, so then they can just add to what they already had.

Data And Mysql
I want column XY be unique so:

 xy | gg | zz | ee
 12 | df | df | fd
 13 | df | df | fd

I want to enter more data but it might enter 12 | df | df | fd again so i would get an error. How would i prevent that without having to loop threw the whole database checking for that entry?

Getting Data With MYSQL
IM interested in knowing of any better ways of retreiving data from mysql and if my current way is safe as i request it over all my scripts.

$information = mysql_fetch_row(mysql_query("SELECT `row` FROM `table` WHERE `username` = 'Memphis'"));

print("$information[0]");

Getting Data From Mysql To Put Into Form
i am trying to set up a page that will allow the user to select a name from a list. The details of this name(ie, last name,address, job etc) are then taken from a database and put into a form. If any changes are needed the user makes them then presses a submit to update the database.

I can get the information out of the database and into the form fields but i have one small problem...

In the address field i can only get the first part of the address...
ie

if the address is 123 Sample Street

only 123 gets put into the form field.

How do i get the rest of the address to appear?

i am sure it is quite simple but cant quite put my finger on the answer!

my code is:

Address: <input type="Text" name="address" value =<?php echo $myrow["address"] ?>><br>

where $myrow is the array holding the results from my database query.

Any help would be appreciated!

Importing Data Into Mysql
I'm starting working on a new project where I'll have to allow users to upload and import tab-formatted text files into the db. Should I use the LOAD DATA INFILE from PHP or write a custom procedure?

Problems Getting Data From Mysql
I've written a scipt for breaking articles into several pages and it seem to be working fine but I can't get them from the database. PHP Code:

Mysql Data Doubled
I'm facing a problem with mysql and don't know what is the problem as I still learn php/mysql. I use a simple script to upload some images and a file. Everything runs very well untill I choose a name for a file that is allready in the database, the new data just overwrite the old one which gives me allmost two identical results in the db, allmost because only the path to the uploaded images are changed, the comments, name, creation data stay different.

Here is my db:


Copyright © 2005-08 www.BigResource.com, All rights reserved