2011-03-01 141 views
1

使用正確的字段名稱更新了腳本。爲什麼不能正常工作?使用php從mysql數據庫獲取信息

<?php 
$con = mysql_connect("localhost","root","pass"); 
if (!$con) 
{ 
    die('Could not connect: ' . mysql_error()); 
} 

mysql_select_db("bookorama", $con); 

$sql="SELECT * FROM customers"; 
$result = mysql_query($sql);  // You actually have to execute the $sql with mysql_query(); 

echo "<table>"; //start the table 

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) //Loop through the results 
{ 
    //echo each row of the table 
    echo "<tr>        
      <td>$row['customerID']</td> 
      <td>$row['name']</td> 
      <td>$row['Aaddress']</td> 
      <td>$row['city']</td> 
      </tr>"; 
} 

echo '</table>'; //close out the table 

?> 
+0

您不會實際運行您的查詢$ sql,或從中檢索結果。看到手冊爲:mysql_query(),mysql_fetch_assoc() – 2011-03-01 01:44:07

回答

2
<?php 
$con = mysql_connect("localhost","root","pass"); 
if (!$con) 
{ 
    die('Could not connect: ' . mysql_error()); 
} 

mysql_select_db("bookorama", $con); 

$sql="SELECT * FROM customers"; 
$result = mysql_query($sql);  // You actually have to execute the $sql with mysql_query(); 

echo "<table>"; //start the table 

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) //Loop through the results 
{ 
    //echo each row of the table 
    echo "<tr>";        
    echo "<td>$row['CustomerID']</td>"; 
    echo "<td>$row['address']</td>"; 
    echo "<td>$row['city']</td>"; 
    echo "</tr>"; 
} 

echo '</table>'; //close out the table 

?> 
+0

這給我一個錯誤:解析錯誤:語法錯誤,意想不到的T_ENCAPSED_AND_WHITESPACE,期待T_STRING或T_VARIABLE或T_NUM_STRING在第19行 – Jshee 2011-03-01 02:47:50

+0

更新它,嘗試。 – jondavidjohn 2011-03-01 14:01:15

+0

這仍然給出了錯誤:解析錯誤:語法錯誤,意外的T_ENCAPSED_AND_WHITESPACE,預計T_STRING或T_VARIABLE或T_NUM_STRING第19行 – Jshee 2011-03-02 17:37:13

0

您需要運行查詢並遍歷結果。

你最好從第一天開始學習約PDO

也不要直接從任何用戶提交的變量(包括$_POST)插值。

2

您可以mysql_fetch_arraymysql_fetch_assoc來檢索您查詢中的行。

例如使用mysql_fetch_array:

$result = mysql_query($sql); 
echo "<table><tbody>"; 
while ($row = mysql_fetch_array($result, MYSQL_NUM)) { 
    echo "<tr><td>".$row[0] . "</td><td>" . $row[1] . "</td></tr>"; 
} 
echo "</tbody></table>" 
0

敢肯定你需要這樣做嵌入什麼比雙引號

echo "<tr>        
     <td>{$row['CustomerID']}</td> 
     <td>{$row['address']}</td> 
     <td>{$row['city']}</td> 
     </tr>"; 

內標量較複雜時,所以,只要你有一個更復雜VAR名稱比引用中的「test $ var」更好,用{}包裝 - 甚至可以這樣做,比如「test {$ var}」也是很好的練習方式