2017-03-01 48 views
3

https://developers.google.com/maps/documentation/javascript/mysql-to-maps谷歌地圖文檔使用不推薦的PHP - 我如何更新它?

功能已棄用PHP連接到MySQL數據庫,即使用mysql而不是mysqli或pdo。

我試着按照教程顯示來自mySQL數據庫的集名/ lat/lng的標記,但發現PHP已被棄用,只是用'mysqli'替換'mysql'給了我一個幾乎空的XML文檔。

這是我的PHP:

<?php 

$servername = "localhost"; 
$username = "root"; 
$password = "root"; 
$dbname = "pins_db"; 
$database = "root-pins_db"; 

function parseToXML($htmlStr) 
{ 
$xmlStr=str_replace('<','&lt;',$htmlStr); 
$xmlStr=str_replace('>','&gt;',$xmlStr); 
$xmlStr=str_replace('"','&quot;',$xmlStr); 
$xmlStr=str_replace("'",'&#39;',$xmlStr); 
$xmlStr=str_replace("&",'&amp;',$xmlStr); 
return $xmlStr; 
} 

// Opens a connection to a MySQL server 
$connection=mysqli_connect ('localhost', $username, $password); 

// Set the active MySQL database 
$db_selected = mysqli_select_db($connection, $dbname); 

// Select all the rows in the markers table 
$query = "SELECT * FROM pins_table WHERE 1"; 
$result = mysqli_query($query); 

header("Content-type: text/xml"); 

// Start XML file, echo parent node 
echo '<markers>'; 

// Iterate through the rows, printing XML nodes for each 
while ($row = @mysqli_fetch_assoc($result)){ 
    // Add to XML document node 
    echo '<marker '; 
    echo 'name="' . $row['name'] . '" '; 
    echo 'lat="' . $row['lat'] . '" '; 
    echo 'lng="' . $row['lng'] . '" '; 
    echo '/>'; 
} 

// End XML file 
echo '</markers>'; 

?> 

生成的XML文件只包含:

<markers/> 

我在MAMP運行PHP 7.0.15和MySQL 35年6月5日。

數據庫信息:

user/pw: root/root 
database: pins_db 
table: pins_table 

表:

1 id int(11) 

2 datetime datetime 

3 lat float(10,6) 

4 lng float(10,6) 

5 name text 

我失去了一些東西在這裏?我對PHP相當陌生,對mySQL也很新穎;我無法在網上找到其他任何地方的答案。

回答

3

開啓PHP錯誤報告

error_reporting(E_ALL); 
ini_set('display_errors', 1); 

http://php.net/manual/en/function.error-reporting.php

http://php.net/manual/en/function.ini-set.php


測試查詢執行的成功執行。

$result = mysqli_query($connection,$query); 
if(!$result) { 
    // error returned 
    die('error#002: '.mysqli_error($connection)); 
} 

http://php.net/manual/en/mysqli.error.php


取出@(at符號)函數之前調用,因爲我們不想沉默PHP錯誤:

while ($row = @mysqli_fetch_assoc($result)) { 
       ^

同時檢查成功連接

$connection = mysqli_connect('localhost', $username, $password); 
if(!$connection) { 
    die('error connecting: ' . mysqli_connect_error()); 
} 

http://php.net/manual/en/mysqli.connect-error.php

這也有可能是mysqli_select_db不能正常工作。例如,如果數據庫名稱不正確或不存在。

http://php.net/manual/en/mysqli.select-db.php

注意,數據庫名稱可以作爲mysqli_connect第四個參數提供。

https://ericlippert.com/2014/03/05/how-to-debug-small-programs/

+0

非常感謝!打開錯誤報告後,我發現mysqli_query需要將連接作爲參數。輸入$ connection後,我會看到一個包含所有引腳的生成的XML文件。希望導入這些代碼將與Google提供的代碼一起工作。 以供將來參考固定碼: '$結果= mysqli_query($查詢);'應該是'$結果= mysqli_query($連接,$查詢);' – Anthony

+0

@Anthony:我沒有注意到缺少'$連接參數...我專注於檢查錯誤和通知。 (請注意,我並不是建議'die'是處理錯誤的最合適的方式,它只是一個佔位符,在我們開始實現對日誌記錄函數的調用並顯示更友好的頁面給最終用戶......「我們對給您造成的不便表示歉意,但有些事情已經發生了可怕的錯誤」)。 – spencer7593

+0

'$ connection'參數在調用mysqli_error和mysqli_query時是必需的。答案中的代碼已更正。 – spencer7593