Im trying to make a little calculator with input given by a person, multiplying and adding these answers with some variables declared in php. But I can't get it to work properly.
What is wrong with this script? The writing to database part from the form works correctly. But when it directs to the output screen, the calculations don't really work.
mysql_connect("localhost" , "root" , "DM3") or die (MySQL_error());
mysql_select_db("calculator");
$order = "INSERT INTO calculator (nineholes , eightteenholes , hcp , club , academy , locker , rainflex ) VALUES ('$_POST[nineholes]','$_POST[eightteenholes]','$_POST[hcp]','$_POST[club]','$_POST[academy]','$_POST[locker]','$_POST[rainflex]') " ;
$result = mysql_query($order);
//*Deze waarden kun je vrij veranderen
$brons = 44.00 ;
$zilver = 129.00 ;
$goud = 265.00 ;
$platinum = 599.00 ;
$greenfeebrons = 25.00 ;
$greenfeezilver = 17.50 ;
$greenfeegoud = 12.50 ;
greenfeeplatinum = 5.00 ;
$hcpx = 25.00 ;
$clubx = 65.00 ;
$academyx = 65.00 ;
$lockerx = 85.00 ;
$rainflexx = 45.00 ;
$allinx = 0.00 ;
$allinplatinumx = 0.00 ;
//*Deze waarden kun je niet veranderen
$nineholes = mysql_query('SELECT nineholes FROM calculator') ;
$eightteenholes = mysql_query('SELECT eightteenholes FROM calculator') ;
$hcp = mysql_query('SELECT hcp FROM calculator') ;
$club = mysql_query('SELECT club FROM calculator') ;
$academy = mysql_query('SELECT academy FROM calculator') ;
$locker = mysql_query('SELECT locker FROM calculator') ;
$rainflex = mysql_query('SELECT rainflex FROM calculator') ;
$allin = '0' ;
$allinplatinum = '0' ;
// Total
$bronstotaal = $brons + (($nineholes / 4) * $greenfeebrons ) + (($eightteenholes / 5) * $greenfeebrons ) + (( $hcp / 6 ) * $hcpx ) + (( $club / 7 ) * $clubx ) + (( $academy / 8 ) * $academyx) + (( $locker / 9 ) * $lockerx) + (( $rainflex / 10 ) * $rainflexx) + $allin + $allinplatinum;
$zilvertotaal = $zilver + (($nineholes / 4) * $greenfeezilver ) + (($eightteenholes / 5) * $greenfeezilver ) + (( $hcp / 6 ) * $hcpx ) + (( $club / 7 ) * $clubx ) + (( $academy / 8 ) * $academyx) + (( $locker / 9 ) * $lockerx) + (( $rainflex / 10 ) * $rainflexx) + $allin + $allinplatinum;
$goudtotaal = $goud + (($nineholes / 4) * $greenfeegoud ) + (($eightteenholes / 5) * $greenfeegoud ) + (( $hcp / 6 ) * $hcpx ) + (( $club / 7 ) * $clubx ) + (( $academy / 8 ) * $academyx) + (( $locker / 9 ) * $lockerx) + (( $rainflex / 10 ) * $rainflexx) + $allin + $allinplatinum;
$platinumtotaal = $platinum + (($nineholes / 4) * $greenfeeplatinum ) + (($eightteenholes / 5) * $greenfeeplatinum ) + (( $hcp / 6 ) * $hcpx ) + (( $club / 7 ) * $clubx ) + (( $academy / 8 ) * $academyx) + (( $locker / 9 ) * $lockerx) + (( $rainflex / 10 ) * $rainflexx) + $allin + $allinplatinum;
if($result)
{
echo ("<br> <u><b>Totaal:</b></u> <br>") ;
echo ($bronstotaal) . "<br>" ;
echo ($zilvertotaal) . "<br>" ;
echo ($goudtotaal) . "<br>" ;
echo ($platinumtotaal) . "<br>" ;
}
else
{
echo("<br>U heeft niet alles goed ingevuld");
}
i recommended you to use mysqli btw:
$result = mysql_query('SELECT * FROM calculator') ;
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while ($row = mysql_fetch_assoc($result)) {
$nineholes = $row['nineholes'];
$eightteenholes = $row['eightteenholes'];
$hcp = $row['hcp'];
$club = $row['club'];
//.
//.
//.
//and so on
}
so you only need one Select and not so many ;)
Errors in your script:
Missing a $ at greenfeeplatinum
After running query as mysql_query, you have to fetch the values as
while($row = mysql_fetch_array($nineholes))
{
$nine_hole = $row['nineholes'];
}
You can fetch all columns in a single query like
SELECT * FROM calculator
mysql_query returns a resource after succesful execution of the query not a value,u need to fetch it.Read here
so replace all like the below:
$nineholes = mysql_query('SELECT nineholes FROM calculator') ;
with
$nineholes = mysql_result(mysql_query('SELECT nineholes FROM calculator'),0) ;
OR
better use the method which Igoel mentioned,that is more optimized way.
also as mentioned in the above comments you are missing a $ at greenfeeplatinum
*Dont use mysql_ as they are deprecated.
Related
I'm getting issue when I try to use < symbol with AND condition in sql query.
WHERE (latitude - 0.009 < AND latitude + 0.00 >)
AND (longitude - 0.009 <
AND longitude + 0.009 > )
Here is my code in CorePHP:
<?php
ini_set("display_errors", 0);
$lat = $_REQUEST['latit'];
$long = $_REQUEST['longit'];
include ("commanvar.php");
include ("class.db.php");
$coordinates_ = '';
// function to calculate distance between two latitudes and longitudes
function distance($lat1, $lng1, $lat2, $lng2, $miles = true)
{
$pi80 = M_PI / 180;
$lat1 *= $pi80;
$lng1 *= $pi80;
$lat2 *= $pi80;
$lng2 *= $pi80;
$r = 6372.797; // mean radius of Earth in km
$dlat = $lat2 - $lat1;
$dlng = $lng2 - $lng1;
$a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
$km = $r * $c;
return ($miles ? $km * 0.621371192 : $km);
}
$obj = new db_connect();
// added by pramod
$sql = "SELECT name,
latitude,
longitude,
TYPE
FROM (SELECT name,
TO_BINARY_FLOAT(latitude) latitude,
TO_BINARY_FLOAT(longitude) longitude,
TYPE
FROM (SELECT name,
latitude,
longitude,
TYPE,
is_number (latitude) latisnum,
is_number (longitude) longisnum
FROM (SELECT name,
REGEXP_SUBSTR (latlon,
'[^,]+',
1,
1)
latitude,
REGEXP_SUBSTR (latlon,
'[^,]+',
1,
2)
longitude,
TYPE
FROM (SELECT olt.name,
olt_details.latlon,
'olt' AS TYPE
FROM ftth.olt, ftth.olt_details
WHERE olt_id = id
UNION
SELECT name, latlon, TYPE FROM ftth.splitters
))
WHERE latitude IS NOT NULL AND longitude IS NOT NULL)
WHERE latisnum = 1 AND longisnum = 1)
WHERE (latitude - 0.009 < $lat
AND latitude + 0.00 > $lat)
AND (longitude - 0.009 < $long
AND longitude + 0.009 > $long)";
//die();
$obj->db_query($sql);
// echo $sql;
// echo $lat . ',' . $long;
// define json array coordinates and prepare it's elements for returning via AJAX
$coordinates = '{
"coordinates": [';
while ($result = $obj->db_fetch_array(1)) {
$latitude = $result['LATITUDE'];
$longitude = $result['LONGITUDE'];
$name = $result['NAME'];
$type = $result['TYPE'];
$latlon_fiber = $result['LATITUDE'] . ", " . $result['LONGITUDE'];
$distance_fromswitch = distance($lat, $long, $latitude, $longitude, FALSE);
$distance_fromswitch = floor($distance_fromswitch * 1000);
$coordinates_ .= '{ "distance":"' . $distance_fromswitch . '" ,"site_name":"' . $name . '" , "latitude":"' . $latitude . '" , "longitude":"' . $longitude . '" , "device_type":"' . $type . '" },';
}
$coordinates .= rtrim($coordinates_, ',');
$coordinates .= "]}";
echo $coordinates;
$obj->free();
?>
I'm getting the following error due to this part < AND on line WHERE (latitude - 0.009 < AND latitude + 0.00 >)
ORA-00936: missing expression
00936. 00000 - "missing expression"
I think I've used some improper syntax while using < with AND on line WHERE (latitude - 0.009 < AND latitude + 0.00 >)
What can be the correction that need to be done here?
Think of it! The error message is self-explanatory.
You're trying to compare the result of subtraction to nothing. To correct this, you have to change it to:
WHERE (latitude - 0.009 < SomeValueHere AND latitude + 0.00 > SomeValueHere)
For further details, please see: ORA-00936 missing expression
[EDIT]
As to changes made in the question...
You're asking for help in debugging (inspect) your code. Let me quote the comment to your comment:
probably the variables do not have any values and passing empty
strings into your query.. – skybunk
Thank you, #skybunk!
I am trying to find the average of a set of results that come from a select:
I have already found the average of a row of results but I need to then find the average of averages but im struggling to count the rows and do tha math.
here is my PHP:
<?php
$dansql2 = "SELECT team_members.team_id, team_members.member_id, members.member_id,
members.firstName, members.lastName, members.score_1, members.score_2,
members.score_3, members.score_4, members.score_5, members.score_6,
members.score_7, members.score_8
FROM team_members
JOIN members
ON team_members.member_id = members.member_id
WHERE members.dashboard_id = $dashboard_id
AND team_members.team_id = $teamSelect
ORDER BY members.firstName ASC";
$danresult = $conn->query($dansql2);?>
<?php
if ($danresult->num_rows > 0) {
while($row = $danresult->fetch_assoc()) {
$score1 = $row["score_1"];
$score2 = $row["score_2"];
$score3 = $row["score_3"];
$score4 = $row["score_4"];
$score5 = $row["score_5"];
$score6 = $row["score_6"];
$score7 = $row["score_7"];
$score8 = $row["score_8"];
$sum = $score1 + $score2 + $score3 + $score4 + $score5 + $score6 + $score7 + $score8;
$totalAverage = $sum / 8;
echo $totalAverage;
}
}
?>
so what I need to find the total average of is from the $totalAverage variable. That prints out the average of each of the rows scores but I need to tall up the $totalAverage
Do you means something like this
<?php
$dansql2 = "SELECT team_members.team_id, team_members.member_id, members.member_id,
members.firstName, members.lastName,
members.score_1, members.score_2,
members.score_3, members.score_4,
members.score_5, members.score_6,
members.score_7, members.score_8,
(members.score_1 + members.score_2 +
members.score_3 + members.score_4 +
members.score_5 + members.score_6 +
members.score_7 + members.score_8 ) / 8 as membersAvg
FROM team_members
JOIN members
ON team_members.member_id = members.member_id
WHERE members.dashboard_id = $dashboard_id
AND team_members.team_id = $teamSelect
ORDER BY members.firstName ASC";
$danresult = $conn->query($dansql2);
$allAvg = 0;
while($row = $danresult->fetch_assoc()) {
$allAvg += $row['membersAvg'];
echo $row['firstName'] . ' ' .$row['lastName'] . ' Avg = ' . $row['membersAvg'];
}
echo 'Avg of Avgs = ' . $allAvg / $danresult->num_rows;
?>
I have MySQL table with some libraries. I need to make SQL query in PHP, which will select library by ID, and count distance. This is invalid query. Where I'm doing mistake in this query ?
$query = "SELECT *,
( 6371 *
acos(
cos(radians(" . $center_lat . ")) *
cos(radians(lat)) *
cos(radians(lng) - radians(" . $center_lng . ")) +
sin(radians(" . $center_lat . ") ) *
sin(radians( lat ) )
)
) AS distance
FROM `libraries`
WHERE id = ". $id ."
LIMIT 0 , 1";
I'm trying to return results by latitude and longitude in me BD.
I have this script. It works fine when I do the phpmyadmin
SELECT `loc` . * , (
(
(
ACOS( SIN( ( 4.6665578 * PI( ) /180 ) ) * SIN( (
`latitude_advertiser` * PI( ) /180 ) ) + COS( ( 4.6665578 * PI( ) /180 ) ) * COS( (
`latitude_advertiser` * PI( ) /180 )
) * COS( (
(
- 74.0524521 - `longitude_advertiser`
) * PI( ) /180 )
)
)
) *180 / PI( )
) *60 * 1.1515
) AS `distance`
FROM `user_profile_` `loc`
HAVING `distance` <1
LIMIT 0 , 30
However, when I try to do the similar procedure using php my query Returns How Empty.
$connect = mysqli_connect('localhost','root','');
$db = mysqli_select_db($connect, 's2_001') or die ('Erro #1010');
$distance = 10;
$latitude = 4.6665578;
$longitude = -74.0524521;
$sql = "SELECT `loc`.*, (((acos(sin(($latitude*pi()/180)) * sin((`latitude_advertiser`*pi()/180))+cos(($latitude*pi()/180)) * cos((`latitude_advertiser`*pi()/180)) * cos((($longitude - `longitude_advertiser`)*pi()/180))))*180/pi())*60*1.1515) AS `distance` FROM `user_profile_` `loc` HAVING `distance` < 1";
$query = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($query)){
echo $row['id'] . '-' . $row['distance'] . '<br>';
}
echo mysqli_num_rows($query); // no line here
echo $sql; // test query, working in phpmyadmin
I have 2 tables. Tables are having same colums and I need to compare them. Simple Join query cannot resolve my problem 'cause table2 can contain many rows appropriate to table 1, but I need to choose the best appropriate row. For example :
Table 1
duration; price; number;
1; 3; 5;
Table 2
duration; price; number;
1; 3.1; 5;
1; 3.01; 5;
I need to compare row1 from table1 to row1 and row2 from table 2 and choose the best appropriate(e.g row2 is the best appropriate) and mark the row2 as compared and do not to compare it next time. I'm using FIREBIRD database and ADODB php library. I wrote some code but it works very long time when I have many records in tables. How can I optimize my code to do this task more faster?
CODE:
$this->connect->BeginTrans();
$sourceResult = $this->connect->Execute( "SELECT SC_PHONE_NUMBER, SC_CALL_START, SC_DURATION, SC_RATE, SC_ID FROM ". $this->sourceTableName . " WHERE sc_comparing_id = " . $this->insertedId );
if ( $sourceResult ) {
while ( !$sourceResult->EOF ) {
$result = array();
$comparationResult = $this->connect->Execute(
"SELECT CC_PHONE_NUMBER, CC_CALL_START, CC_DURATION, CC_RATE, CC_ID FROM " . $this->comparableTableName . " WHERE cc_comparing_id = " . $this->insertedId
. " AND cc_is_compared = 0"
. " AND cc_phone_number = " . $sourceResult->fields['SC_PHONE_NUMBER']
. " AND " . $sourceResult->fields['SC_CALL_START'] . " BETWEEN cc_call_start - " . TIME_RANGE . " AND " . " cc_call_start + " . TIME_RANGE
);
if ( $comparationResult ) {
while ( !$comparationResult->EOF ) {
$callStartRating = TIME_RANGE / ( TIME_RANGE + abs( $sourceResult->fields['SC_CALL_START'] - $comparationResult->fields['CC_CALL_START'] ) );
$durationRating = 0;
$rateRating = 0;
if ( $sourceResult->fields['SC_DURATION'] > $comparationResult->fields['CC_DURATION'] ) {
$durationRating = $comparationResult->fields['CC_DURATION'] / $sourceResult->fields['SC_DURATION'];
} else {
$durationRating = $sourceResult->fields['SC_DURATION'] / $comparationResult->fields['CC_DURATION'];
}
if ( $sourceResult->fields['SC_RATE'] > $comparationResult->fields['CC_RATE'] ) {
$rateRating = $comparationResult->fields['CC_RATE'] / $sourceResult->fields['SC_RATE'];
} else {
$rateRating = $sourceResult->fields['SC_RATE'] / $comparationResult->fields['CC_RATE'];
}
$totalRating = $rateRating + $durationRating + $callStartRating;
$result[] = array(
'sc_id' => $sourceResult->fields['SC_ID'],
'cc_id' => $comparationResult->fields['CC_ID'],
'rating' => $totalRating
);
$comparationResult->MoveNext();
}
$resArray = null;
if ( count( $result ) >= 1 ) {
$resArray = $result[0];
foreach ( $result as $row ) {
if ( $resArray['rating'] < $row['rating'] ) {
$resArray = $row;
}
}
$query = "UPDATE source_cdr SET sc_cc_key = " . $row['cc_id'] . " WHERE sc_id = " . $row['sc_id'];
$this->connect->_Execute( $query );
$this->connect->_Execute( "UPDATE comparable_cdr SET cc_is_compared = 1 WHERE cc_id = " . $resArray['cc_id'] );
}
}
$this->connect->CommitTrans();
$sourceResult->MoveNext();
}
Not the answer you want, but to make it faster, you should try to answer this in SQL. In your top example, you would do something like
Select FIRST 1 duration, price, number
from tablea a
join tableb b on a.duration=b.duration and a.number = b.number
where b.price>=a.price
Now I am sure your table structure and comparison is more complicated, maybe you could share more of the data structure and rules on comparison and people here can help.
Another approach that would help but not be ideal, make sure you are ordering the data and if the minimum comparison happens, get out of your loop.
You can get the "best" entry from comparableTable with only one query.
SELECT *
FROM `comparable_table`
ORDER BY ABS(CAST("3.00" AS DECIMAL) - `price`)
LIMIT 1
The Value "3.00" is from one row in the source table.
This query is slow with large tables.
If you have a large table try this:
SELECT *
FROM
(
(
SELECT *
FROM `comparable_table`
WHERE `price` >= CAST("3.00" AS DECIMAL)
ORDER BY `price`
LIMIT 1
)
UNION DISTINCT
(
SELECT *
FROM `comparable_table`
WHERE `price` <= CAST("3.00" AS DECIMAL)
ORDER BY `price` DESC
LIMIT 1
)
) AS `min_max`
ORDER BY ABS(CAST("3.00" AS DECIMAL) - `price`)
LIMIT 1
If you add an index on price this query use it and it should be faster on large tables.