使用php从mysql db获取信息

时间:2011-03-01 01:38:44

标签: 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

?>

4 个答案:

答案 0 :(得分: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>"

答案 1 :(得分: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

?>

答案 2 :(得分:0)

您需要运行查询并遍历结果。

你最好从第一天开始学习PDO

并且也不要直接从任何用户提交的变量(包括$_POST)进行插值。

答案 3 :(得分:0)

当在双引号中嵌入比标量更复杂的东西时,你肯定需要这样做

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

因此,无论何时你的var名称都比引号中的“test $ var”更复杂,请用{}换行 - 即使这样,最好将标量包装成“test {$ var}”