dsh1956 2013-12-04 16:17
浏览 195
已采纳

将数据库文本值输出到div中

I am trying to output values saved in my database into a div field, however the data does not seem to come out, could anyone explain to me why?

<div>
<?php
        $host="localhost"; // Host name 
        $username="root"; // Mysql username 
        $password="root"; // Mysql password 
        $db_name="Database"; // Database name 

        mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
        mysql_select_db("$db_name")or die("cannot select DB");

        $result=mysql_query("SELECT from `posts`");
        $num=mysql_numrows($result);
        $i=0;
        while ($i < $num) {
            echo $result[$i];
            $i++;
        }
        ?>
</div>

Above is the code I have inside the div tag. So my question why does my echo not work?

  • 写回答

4条回答 默认 最新

  • dpub33855 2013-12-04 16:19
    关注

    This is not the way to do that, you may use like this:

    //$result=mysql_query("SELECT from `posts`"); <- this query is wrong. 
    if ($result = mysql_query("SELECT * FROM posts"))
    {
        $num=mysql_num_rows($result);
    
       while ($row = mysql_fetch_assoc($result)) {
           echo $row['key']; // <- you must set the field name of your query here
       } 
    }
    else // This if will show you when any query error is thrown.
    {
        echo mysql_error();
    }
    

    Your original query is wrong. You may get an error because SELECT FROM is not valid. You have to specify a list of fields, a function or * to get all fields of the table.

    The you may use mysql_fetch_assoc(), mysql_fetch_row() or mysql_fetch_array() in order to fetch the received data from the query.

    Plus, I have added an if in your query command in order to get any mysql error thrown in your query execution. Using that you'll never be confuse about what happened here.

    Hope it helps.

    UPDATE: As @SpiderLinked said(Thank you dude), mysql_numrows() does not exists. You have to use mysql_num_rows() to get query result count.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程