简体   繁体   English

从php / MySql中的特定列检索数据

[英]retrieving data from a specific column in php/MySql

I'm using WordPress with XAMPP. 我正在使用WordPress和XAMPP。 I'm trying to fetch the post title from a column called post_title from a table called ltport_posts by using mysqli_fetch_row() function. 我正在尝试使用mysqli_fetch_row()函数从名为ltport_posts的表中从名为post_title的列中获取帖子标题。 The connection with the database is working just fine. 与数据库的连接工作得很好。 However, post titles don't seem to be written in the news ticker. 但是,帖子标题似乎没有写在新闻自动收报机中。 Now I know that $row variable is an enumerated array, so we should write the offset number to access the column. 现在我知道$row变量是一个枚举数组,所以我们应该写入偏移数来访问该列。 It should be noted that the while loop is working since I have four rows in the ltport_posts and four <div> 's are generated (browser's inspect element is showing me that). 应该注意的是while循环正在工作,因为我在ltport_posts中有四行,并且生成了四个<div> (浏览器的inspect元素向我显示)。 But the whole tag is empty: 但是整个标签都是空的:

<div class="ticker-wrap">
<div class="ticker">
<div class="ticker__item"> </div>
<div class="ticker__item"> </div>
<div class="ticker__item"> </div>
<div class="ticker__item"> </div>
</div>
</div>

Here's the php/HTML code: 这是php / HTML代码:

 <div class="ticker">
        <?php $query="SELECT post_title from ltport_posts";
        if($result=mysqli_query($conn,$query))
        {
            while($row=mysqli_fetch_row($result))
            {?>
            <div class="ticker__item"><?php printf("%s", $row[5]); ?> </div>
        <?php }
        mysqli_free_result($result);
    }
    mysqli_close($conn);?>
</div>

mysqli_fetch_row mysqli_fetch_row

mysqli_result::fetch_row -- mysqli_fetch_row — Get a result row as an enumerated array mysqli_result :: fetch_row - mysqli_fetch_row - 获取结果行作为枚举数组

Your query is 你的查询是

$query="SELECT post_title from ltport_posts";

You just fetch one column from your query. 您只需从查询中获取one column So you will get only $row[0] .It's indexing start from 0 所以你只得到$row[0]它的索引从0开始

 while($row=mysqli_fetch_row($result))
            {?>
            <div class="ticker__item"><?php printf("%s", $row[0]); ?> </div>
        <?php }

For fetching multiple column 用于获取多列

$query = "SELECT column1, column2,column3,column4 FROM City ORDER by ID DESC";

if ($result = mysqli_query($link, $query)) {

    while ($row = mysqli_fetch_row($result)) {
        printf ("%s (%s)\n", $row[0], $row[1],$row[3], $row[4]);
    }
}

You can do the following: 您可以执行以下操作:

// Prepare the query
$stmt = "select column FROM table";

// Execute it...
$result = mysqli_query($stmt);

// Fetch Results
$row = mysqli_fetch_assoc($result);

// Output single column
echo $row['column'];

And of course you can loop it through as well with multiple results. 当然,您也可以循环使用多个结果。 mysqli_fetch_assoc will return an array where the keys are the column names. mysqli_fetch_assoc将返回一个数组,其中键是列名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM