2014-04-15 36 views
0
<?php 
$link = mysql_connect('localhost', 'user', 'password'); 
if (!$link) { 
die('Failed to connect to MySQL: ' . mysql_error()); 
} 
$db_selected = mysql_select_db('mysql', $link); 
if (!$db_selected) { 
    die ("Can\'t use db : " . mysql_error()); 
} 
$query = sprintf("SELECT church_id FROM hours 
     WHERE day_of_week = DATE_FORMAT(NOW(), '%w') AND 
     CURTIME() BETWEEN open_time AND close_time", 
    mysql_real_escape_string($day_of_week), 
    mysql_real_escape_string($open_time), 
    mysql_real_escape_string($close_time)); 
$result = mysql_query($query); 

if (!$result) { 
    $message = 'Invalid query: ' .mysql_error() . "\n"; 
    $message .= 'Whole query: ' .$query; 
    die($message); 
} 

while ($row = mysql_fetch_array($result)) { 
    echo $row['shop_id']; 
} 

mysql_free_result($result); 
echo "end"; 
?> 

我知道SQL查詢通過複製/粘貼到phpmyadmin中起作用。我希望腳本只輸出一個shop_id或一系列shop_ids。現在它輸出資源ID#3。我查找了如何修復它,並且mysql_fetch_array應該是答案。我究竟做錯了什麼?PHP語法錯誤?輸出資源ID#3

+2

你應該張貼,你所看到的,看起來錯誤 - 崩潰的結果,輸出等。還請注意** MySQL是過時,新的代碼應寫入的mysqli ** – RobP

+2

...或PDO。請參閱[爲什麼我不應該在PHP中使用mysql_ *函數](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – Phil

+0

1) $ day_of_week'從哪裏來? 2)你的'sprintf'字符串只有一個佔位符,但你傳遞了三個值? 3)你'選擇church_id',但試圖回顯'shop_id' 4)上述代碼無法輸出。在任何時候您都不會顯示任何可能成爲資源的信息 – Phil

回答

1

我期待在您的查詢,我只看到你選擇church_id並且要輸出shop_id,你應該包括在你的選擇,像這樣:

$query = sprintf("SELECT church_id, shop_id FROM hours WHERE day_of_week = DATE_FORMAT(NOW(), '%w') AND CURTIME() BETWEEN open_time AND close_time", 
    mysql_real_escape_string($day_of_week), 
    mysql_real_escape_string($open_time), 
    mysql_real_escape_string($close_time)); 
$result = mysql_query($query); 
+0

仍然有3個參數傳遞給sprintf,只有一個佔位符。這不會導致它失敗,但它仍然是你的答案中的代碼錯誤。 – Mike

0

您在這裏有幾個問題,第一其中就是您使用的是mysql擴展名,該擴展名未被維護且正式被棄用(由於被刪除)。我建議你嘗試的mysqli ...

$link = new mysqli('localhost', 'user', 'password', 'mysql'); 
if ($link->errno) { 
    throw new Exception($link->error, $link->errno); 
} 

雖然你做了保護您的查詢的值得稱道的工作,你真的應該使用提供的更好的工具在的mysqli,特別是prepared statements ...

的mysqli準備好的聲明
$stmt = $link->prepare('SELECT church_id FROM hours 
    WHERE day_of_week = DATE_FORMAT(NOW(), ?) AND 
    CURTIME() BETWEEN open_time AND close_time'); 
if (!$stmt) { 
    throw new Exception($link->error, $link->errno); 
} 
$stmt->bindParam('s', $day_of_week); // assuming $day_of_week is properly defined 
if (!$stmt->execute()) { 
    throw new Exception($stmt->error, $stmt->errno); 
} 

獲取數據是舊mysql_fetch_array有點不同,但這並不困難。一種方法是使用結果結合

$stmt->bind_result($church_id); 
while ($stmt->fetch()) { 
    echo $church_id; 
}