2017-10-09 30 views
0

我有這樣的SQL查詢如何在php中保存sql查詢的值?

$sql = "SELECT Trans_id ,**Source** ,Destination, Journey_type,Start_Date, 
      End_Date,Start_Time,End_Time, 
      min((TIMESTAMPDIFF(minute, Start_Date_time , End_Date_time))) as minimum_time 
     FROM transport_type 
     WHERE destination = '" . $selectedDestination . "' 
      AND Start_Date = '" . $selectedDate ."'" . $selectedRide ; 

,我只想要在PHP保存來源元素進一步使用。

我該如何得到這個?請幫忙。

+0

什麼ID問題了嗎?這已經被回答[這裏](https://stackoverflow.com/questions/37367992/php-inserting-values-from-the-form-into-mysql) – Sand

+0

@Sand他只是問如何選擇數據從一個數據庫。 Anny基本的MySQL/PHP教程或代碼從PHP文件將解釋它.... Topicstarter閱讀這個http://php.net/manual/en/mysqli-result.fetch-row.php或http://php.net /manual/en/mysqli-result.fetch-array.php這些是一些methodes關閉從數據庫中選擇和保存在php –

+0

@RaymondNijland我以爲他要求保存數據,我引用「如何保存一個值的SQL在PHP中查詢?「不選擇它們還是選擇數據保存到數據庫? – Sand

回答

0

首先,有一些重要的點,在此:

  • 直接在查詢中使用的變量是不是最好的做法,你會更好地(在很多方面)使用已準備好的規則(PDOMySQLI
  • 其次,爲了提高效率,您應該僅檢索要利用的查詢中的值 - 如果你不需要Trans_idDestination(等等),那麼就沒有必要將它們包含在您選擇

考慮到這一點,我將在以下假設提供了一個答案:

  • 你想用的Source輸出從您的查詢,它在你的PHP分配給$variable
  • 您正在使用mysqli連接到你的數據庫 即$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
  • 你只指望一個行
  • 原始查詢實際工作,因爲我不知道爲什麼你在最後concat'ed selectedRide

如果是這樣,你可以做到以下幾點:

$sql = "SELECT source 
     FROM transport_type 
     WHERE destination = '" . $selectedDestination . "' 
     AND Start_Date = '" . $selectedDate ."'" . $selectedRide 
     LIMIT 1; // added just to enforce the one row thing 

$result = mysqli_query($mysqli,$sql); 
$row = mysqli_fetch_assoc($result); 
$source = $row['source']; 

然而,一個更好的解決辦法是使用mysqli_prepare(或PDO),如上

0

正確的方法是使用PDO

看看例如PDO::query頁:

<?php 
function getFruit($conn) { 
    $sql = 'SELECT name, color, calories FROM fruit ORDER BY name'; 
    foreach ($conn->query($sql) as $row) { 
     print $row['name'] . "\t"; 
     print $row['color'] . "\t"; 
     print $row['calories'] . "\n"; 
    } 
} 
?> 
+0

至少給他一個例子,他自己的sql查詢 –

+0

是的,可能還有一杯咖啡 – Ryosaku