开发者

Fetch information from mysql db using php

Updated script with proper field names. Why isnt this working?

<?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

?&开发者_高级运维gt;


<?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

?>


You can mysql_fetch_array or mysql_fetch_assoc to retriever the rows from you query.

For example using 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>"


You need to run the query and loop through the results.

You are better off learning from day one about PDO.

And also don't interpolate directly from any user submitted variables (that includes $_POST).


Pretty sure you need to do this when embedding anything more complex than scalars inside double quotes

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

So whenever you have a more complex var name than "test $var" in quotes, wrap with {} - and even then, it's good practice to wrap scalars too like "test {$var}"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜