Problemi di calcolo tra due date

pinoshine

Utente Attivo
15 Set 2012
95
0
0
Ciao a tutti, ho un problema di calcolo prezzo tra diverse date, io ho la tabella camere composta cosi':
Codice:
`id` int(11) NOT NULL AUTO_INCREMENT,
  `idhotel` int(11) DEFAULT NULL,
  `room` int(11) DEFAULT NULL,
  `data_start` date DEFAULT NULL,
  `data_end` date DEFAULT NULL,
  `price` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)

all'interno della tabella ho inserito il prezzo per diverse date poi ho questo codice per calcolare il prezzo in base alla data scelta ad esempio dal 20/05/2014 al 30/05/2014 la camera Twin costa 50,00
la query di ricerca è questa:
PHP:
$result = mysql_query("SELECT idhotel, room, price, (DATEDIFF(data_end, data_start) * price) as total FROM rooms");

quando effettuo una ricerca ad esempio dal 21 maggio al 22 maggio (1 notte) invece di uscire 50,00 mi esce 500,00 euro che sarebbe l'addizione dei giorni dal 20 al 30 maggio. mi sapete dire dove sto sbagliando?
Grazie
 

pinoshine

Utente Attivo
15 Set 2012
95
0
0
Ho cambiato la query in modo da fare una ricerca piu' specifica ma niente da fare mi calcola sempre il prezzo di 500 euro
PHP:
SELECT 
    idhotel, room, SUM(total) as total_sum 
FROM 
(
    SELECT 
        idhotel, 
        room,
        price, 
        (DATEDIFF(data_end, data_start) * price) as total 
    FROM 
        rooms
) as t 
GROUP BY 
    idhotel, room
proprio non capisco :gun:
 

criric

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
21 Ago 2010
5.607
54
48
TN
Ciao, tu gli stai dicendo di calcolare in base al range di date presenti sul database
Codice:
DATEDIFF(data_end, data_start) * price
e se non ho capito male è di 10 giorni
dovresti fare il calcolo sulle date passate invece
tipo
PHP:
$giorni = 1; // differenza tra data di arrivo e partenza
$query = "SELECT idhotel, room, price, ($giorni * price) as total FROM rooms";
In più dovresti verificare che le date passate rientrino nel range che hai memorizzato
Codice:
... WHERE $dataarrivo BETWEEN(data_start AND data_end)
 

pinoshine

Utente Attivo
15 Set 2012
95
0
0
Ciao, tu gli stai dicendo di calcolare in base al range di date presenti sul database
Codice:
DATEDIFF(data_end, data_start) * price
e se non ho capito male è di 10 giorni
dovresti fare il calcolo sulle date passate invece
tipo
PHP:
$giorni = 1; // differenza tra data di arrivo e partenza
$query = "SELECT idhotel, room, price, ($giorni * price) as total FROM rooms";
In più dovresti verificare che le date passate rientrino nel range che hai memorizzato
Codice:
... WHERE $dataarrivo BETWEEN(data_start AND data_end)

Grazie per l'aiuto, ma in
PHP:
$datarrivo
io non ho niente che cosa ci devo scrivere? poi mi faresti la query completa?
grazie
 

criric

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
21 Ago 2010
5.607
54
48
TN
quando effettuo una ricerca ad esempio dal 21 maggio al 22 maggio
come la fai la ricerca ? hai un form con i campi dal al ? lo invii in POST ?
 

pinoshine

Utente Attivo
15 Set 2012
95
0
0
Si, questo è il form della ricerca:
HTML:
<form method="post" action="selectroom.php" name="index" onsubmit="return validateForm()">
  
      <label style="margin-left: 8px;">Start Date : </label>
     <input type="text" class="w8em format-d-m-y highlight-days-67 range-low-today" name="start" id="sd" value="" maxlength="10" readonly />
      <BR />
	 <label style="margin-left: 15px;">End Date : </label>
      <input type="text" class="w8em format-d-m-y highlight-days-67 range-low-today" name="end" id="ed" value="" maxlength="10" readonly />
	  <BR />
	  <label style="margin-left: 45px;">Adult : </label>
	  <select name="adult" class="ed" >
	    <option>1</option>
	    <option>2</option>
	    <option>3</option>
	  </select>
	  <BR />
	  <label style="margin-left: 44px;">Child : </label>
	  <select name="child" class="ed">
	    <option>0</option>
	    <option>1</option>
	    <option>2</option>
	  </select>
	  <BR />
	  <input name="" type="submit" value="Check Availability" id="button" />
  </form>
e questa e' la pagina del risultato:
PHP:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
<?php
//lotus.x10hosting.com:2083/frontend/x3/filemanager/editit.html?file=selectroom.php&fileop=&dir=%2Fhome%2Fargie%2Fpublic_html&dirop=&charset=&file_charset=windows-1252&baseurl=&basedir=
	
	$arival = $_POST['start'];
	$departure = $_POST['end'];
	$adults = $_POST['adult'];
	$child = $_POST['child'];	
	
?>

<!--sa pop up-->

 <link href="src/facebox.css" media="screen" rel="stylesheet" type="text/css" />
  
  <script src="lib/jquery.js" type="text/javascript"></script>
  <script src="src/facebox.js" type="text/javascript"></script>
  <script type="text/javascript">
    jQuery(document).ready(function($) {
      $('a[rel*=facebox]').facebox({
        loadingImage : 'src/loading.gif',
        closeImage   : 'src/closelabel.png'
      })
    })
  </script>


<!--sa error trapping-->
<script type="text/javascript">
function validateForm()
{

var y=document.forms["room"]["no_rooms"].value;
var a=document.forms["room"]["madult"].value;
var b=document.forms["room"]["adult"].value;

if ((y==null || y==""))
  {
  alert("all field are required!");
  return false;
  }


/*if (b>a)
  {
  alert("dfdfdfdfdfdfdf");
  return false;
  }*/

}
</script>
<!--sa minus date-->
<script type="text/javascript">
	// Error checking kept to a minimum for brevity
 
	function setDifference(frm) {
	var dtElem1 = frm.elements['start'];
	var dtElem2 = frm.elements['end'];
	var resultElem = frm.elements['result'];
	 
// Return if no such element exists
	if(!dtElem1 || !dtElem2 || !resultElem) {
return;
	}
	 
	//assuming that the delimiter for dt time picker is a '/'.
	var x = dtElem1.value;
	var y = dtElem2.value;
	var arr1 = x.split('/');
	var arr2 = y.split('/');
	 
// If any problem with input exists, return with an error msg
if(!arr1 || !arr2 || arr1.length != 3 || arr2.length != 3) {
resultElem.value = "Invalid Input";
return;
	}
	 
var dt1 = new Date();
dt1.setFullYear(arr1[2], arr1[1], arr1[0]);
var dt2 = new Date();
dt2.setFullYear(arr2[2], arr2[1], arr2[0]);

resultElem.value = (dt2.getTime() - dt1.getTime()) / (60 * 60 * 24 * 1000);
}
</script>



<!--sa input that accept number only-->
<SCRIPT language=Javascript>
      <!--
      function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

         return true;
      }
      //-->
   </SCRIPT>

</head>

<body>
<div class="mainwrapper">
  <div class="leftother">
    <div class="l"></div>
	<div class="r">
	
	
	
	
	<div class="right3">
  <form action="personnalinfo.php" method="post" onsubmit="return validateForm()" name="room">
  <input name="start" type="hidden" value="<?php echo $arival; ?>" />
  <input name="end" type="hidden" value="<?php echo $departure; ?>" />
  <input name="adult" type="hidden" value="<?php echo $adults; ?>" />
  <input name="child" type="hidden" value="<?php echo $child; ?>" />
  
  
  <label style="margin-left: 119px;">Number of rooms: </label><INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="no_rooms" class="ed">
 <span id="errmsg"></span>
  <br />
  <br />
<?php
	require 'conn.php';
	
$dataarrivo = $_GET['date_start'];
$date_end = $_GET['date_end'];
$hotel_id = $_GET['id'];

$giorni = 1; // differenza tra data di arrivo e partenza
$result = mysql_query("SELECT idhotel, room, price, ($giorni * price) as total FROM rooms WHERE $dataarrivo BETWEEN(data_start AND data_end) GRUOP by idhotel, room");

while($row = mysql_fetch_array($result))
  {
  $a=$row['room_id'];
  $query = mysql_query("SELECT sum(qty_reserve) FROM roominventory where arrival <= '$arival' and departure >= '$departure' and room_id='$a'");
while($rows = mysql_fetch_array($query))
  {
  $inogbuwin=$rows['sum(qty_reserve)'];
  }
  $angavil = $row['qty'] - $inogbuwin;
  echo '<div style="height: 117px;">';
	  echo '<div style="float: left; width: 100px; margin-left: 19px;">';
	  echo "<img width=92 height=72 alt='Unable to View' src='" . $row["image"] . "'>";
	  echo '</div>';
	  echo '<div style="float: right; width: 575px; margin-top: -10px;">';
	  echo '<span class="style5">'.'Avalable Rooms: '.$angavil.'</span>';
	  if ($angavil > 0){
					echo '<input name="roomid" type="checkbox" value="' .$row["room_id"]. '" />';
					echo '<input type="submit" name="Submit" value="reserve" onclick="setDifference(this.form);"/>';
					}
				if ($angavil <= 0){
				echo '<span class="style5">'.'wala chansa wala gid vacant'.'</span>';
				}	
	  echo '<br>';		
	  echo '<span class="style5">'.'Room Type: '.$row['room'].'</span><br>';
	  echo '<span class="style5">'.'Room Rate: '.$row['total_sum'].'</span><br>';
          echo '<span class="style5">'.'Max Child: '.$row['max_child'].'</span><br>';
          echo '<input name="mchild" type="hidden" value="' .$row["max_child"]. '" />';
echo '<input name="avail" type="hidden" value="' .$angavil. '" />';
	  echo '<span class="style5">'.'Max Adult: '.$row['max_adult'].'</span><br>';
          echo '<input name="madult" type="hidden" value="' .$row["max_adult"]. '" />';
	  echo '<span class="style5">'.'Room Description: '.$row['description'].'</span><br>';
	  echo '</div>';
  echo '</div>';
}

mysql_close($con);
?> 
<input type="hidden" name="result" id="result" />
</form>
  </div>
	
	
	
	
	
	
	
	
	
	</div>
  </div>
  
  
  
  
  
  
  <div class="rightother">
  
  <div class="reservation">
	  <div align="center" style="padding-top: 7px; font-size:24px;"><strong>RESERVATION  DETAILS</strong></div>
	<div style="margin-top: 14px;">
<label style="margin-left: 16px;">Check In Date : <?php echo $arival; ?></label><br />
<label style="margin-left: 3px;">Check Out Date : <?php echo $departure; ?></label><br />
<label style="margin-left: 71px;">Adults : <?php echo $adults; ?></label><br />
<label style="margin-left: 78px;">Child : <?php echo $child; ?></label><br />
      <BR />
  </div>
	
	
	</div>
  
  
  </div>
  
  
  
  
  
  
</div>
<div class="footer" style="text-align:center; font-family:Arial, Helvetica, sans-serif; font-size:12px;">copyright © tameraplazainn 2011 - 2012 All Rights reserved</div>
</body>
</html>
ho modificato la query come mi hai suggerito ma non da risultato
 

criric

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
21 Ago 2010
5.607
54
48
TN
per prima cosa se i dati arrivano in post non puoi usare il get
PHP:
$dataarrivo = $_POST['start'];
$date_end = $_POST['end'];
 $hotel_id = $_POST['id'];
e non ho capito come sono formattate le date metti un var_dump e posta
PHP:
var_dump($_POST);
 

pinoshine

Utente Attivo
15 Set 2012
95
0
0
Grazie x l'aiuto Criric!!! questo e' quello che esce:
Codice:
array (size=4)
  'start' => string '10/05/2014' (length=10)
  'end' => string '11/05/2014' (length=10)
  'adult' => string '1' (length=1)
  'child' => string '0' (length=1)
 

criric

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
21 Ago 2010
5.607
54
48
TN
E' necessario convertire le date in un formato leggibile per MSQL
lasciando perdere per il momento il conteggio dei giorni potresti provare cosi
PHP:
$dataarrivo = implode("-", array_reverse(explode("/", $_POST['start'])));
$date_end = implode("-", array_reverse(explode("/", $_POST['end'])));
$hotel_id = $_POST['id'];

$giorni = 1; // differenza tra data di arrivo e partenza
$query = "SELECT idhotel, room, price, ($giorni * price) as total
                          FROM rooms 
                          WHERE $dataarrivo BETWEEN(data_start AND data_end) GRUOP by idhotel, room";
$result = mysql_query($query);
if (!$result) {
      echo "Errore query : " . $query . "<br/>" . mysql_error();
}
Conviene sempre tenere la query separata dalla sua esecuzione per aver più ordine nella pagina e per poterla stampare insieme ad eventuali errori SQL
 

pinoshine

Utente Attivo
15 Set 2012
95
0
0
grazie!! la query restituisce questo errore:
Codice:
 Errore query : SELECT idhotel, room, price, (1 * price) as total FROM rooms WHERE 2014-05-10 BETWEEN(data_start AND data_end) GRUOP by idhotel, room
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GRUOP by idhotel, room' at line 3
 

criric

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
21 Ago 2010
5.607
54
48
TN
non sono sicuro della sintassi del between ma puoi provare aggiungendo gli apici alla dataarrivo
PHP:
$query = "SELECT idhotel, room, price, ($giorni * price) as total
                          FROM rooms 
                          WHERE '$dataarrivo' BETWEEN(data_start AND data_end) GRUOP by idhotel, room";
edit:
togli anche le parentesi tonde
PHP:
$query = "SELECT idhotel, room, price, ($giorni * price) as total
                          FROM rooms 
                          WHERE '$dataarrivo' BETWEEN data_start AND data_end  GRUOP by idhotel, room";
 
Ultima modifica:

criric

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
21 Ago 2010
5.607
54
48
TN
non va cosa vuol dire?
se dà ancora errore postalo
 

criric

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
21 Ago 2010
5.607
54
48
TN
Mi sono creato la tabella rooms e l'ho testata, prova questa
PHP:
$query = "SELECT idhotel, room, price, ($giorni * price) as total
                          FROM rooms 
                          WHERE '$dataarrivo' BETWEEN data_start AND data_end  &&
                                id = $hotel_id";
 

pinoshine

Utente Attivo
15 Set 2012
95
0
0
niente adesso ho questo errore:
Codice:
Number of rooms:

Errore query : SELECT idhotel, room, price, (1 * price) as total FROM rooms WHERE '2014-05-15' BETWEEN data_start AND data_end && id =
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 4

Edit: tu ha detto che l'hai testata, ti funziona?
 
Ultima modifica:

criric

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
21 Ago 2010
5.607
54
48
TN
nel POST manca l'id dell'hotel
edit
se l'id è sempre lo stesso togli la condizione su $hotel_id
PHP:
$query = "SELECT idhotel, room, price, ($giorni * price) as total
                          FROM rooms 
                          WHERE '$dataarrivo' BETWEEN data_start AND data_end
edit edit
si mi funziona
 
Ultima modifica:

criric

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
21 Ago 2010
5.607
54
48
TN
vuol dire che la $dataarrivo non rientra nel range di date che hai settato nel db
stampala e provala direttamente su phpmyadmin
PHP:
echo $query;
 

pinoshine

Utente Attivo
15 Set 2012
95
0
0
ho stampato la query:
Codice:
SELECT idhotel, room, price, (1 * price) as total FROM rooms WHERE '2014/05/13' BETWEEN (2014/05/13 AND 2014/05/15) GROUP by room
la data sembra scritta bene pero' non capisco perchè non mi da risultati, io nella tabella dal 10 al 20 maggio ho come prezzo 50,00 quindi come risultato doveva darmi: camera Twin 100,00 euro
 
Discussioni simili
Autore Titolo Forum Risposte Data
P problemi calcolo prezzo PHP 19
N php problemi a visualizzare video PHP 3
T problemi con dati menu a tendina HTML e CSS 2
T problemi di connessione MySQL 2
M Upload immagine con javascript problemi con FormData() Javascript 1
F Problemi visualizzazione mappa Android studio Sviluppo app per Android 0
S Problemi Javascript + Aruba Javascript 2
A Problemi con move_uploaded_file PHP 7
M Problemi con la stampa dei valori in php PHP 1
L Problemi con il login PHP 2
L Problemi form Pagina php HTML e CSS 3
R Tutto su utf-8 ma ancora problemi con i caratteri speciali in mysql MySQL 1
Z problemi con foreach insert into PHP 10
B javascript per problemi con pdf e Safari Javascript 0
N Problemi kit videosorveglianza IP Cam e Videosorveglianza 0
M Problemi con creazione maschere Presentati al Forum 1
M Problemi con query a più tabelle PHP 3
R Problemi anomalo insermento in db PHP 9
S Problemi delle funzioni eliminate con PHP e MySQL PHP 4
S Problemi di un principiante PHP 3
M Problemi con blog Grav CMS (Content Management System) 0
F Problemi di visualizzazione di un sito su più browser WordPress 0
S Problemi di visualizzazione form contatti sito web HTML e CSS 2
S incoerenza di stampa. problemi con il magenta Photoshop 3
A problemi con paypall Java 1
A Problemi di accesso da remoto a Ipcam IP Cam e Videosorveglianza 5
michele81 [WordPress] problemi plug meteo api key WordPress 4
E Problemi in registrazione telecamere Dahua IP Cam e Videosorveglianza 6
S Problemi con modulo upload video php (help!) PHP 0
felino [Windows 8.1] Problemi con connessione WiFi Windows e Software 0
M [PHP] Problemi su inserimento array nel db PHP 7
E [PHP] problemi nuova riga con fwrite su piattaforma android PHP 5
M [PHP] Problemi di salvataggio su campo calcolato PHP 0
O [HTML] problemi con la regola "background-attachment: fixed" in EDGE HTML e CSS 0
M [PHP] Problemi con query unione PHP 11
M [PHP] Problemi con select PHP 6
Spown [WordPress] Problemi visualizzazione su più browser + voci menu in movimento WordPress 1
ANDREA20 [HTML] problemi con il footer HTML e CSS 1
D [MS Access] problemi con inserimento campo in una maschera MS Access 6
M [PHP] Problemi con il riconoscimento login. PHP 21
A [WordPress] problemi con xampp WordPress 2
M Problemi con database Apache/2.4.37 (Win32) OpenSSL/1.1.1a PHP/7.3.1 PHP 6
P Problemi comunicazioni Comunicazioni dallo Staff 8
G I problemi non vengono solo per nuocere Presentati al Forum 0
A Problemi Wi-Fi Fastweb Reti LAN e Wireless 4
C [WordPress] Url vulnerability e problemi sito da mobile WordPress 0
S [PHP] problemi con le sessioni PHP 3
B Problemi accesso Instagram Smartphone e tablet 1
T [PHP] problemi con il browser PHP 0
M [Flash] Problemi conversione formato swf Flash 20

Discussioni simili