如何使用mysql只获取一列的值?

时间:2014-03-29 15:07:44

标签: php mysql sql database

我有一个信息表,只包含一行网页的设置。

INFO
id
np (number of posts in one page)
ngbp (number of guestbook posts in one page)
title (title (header h1) of the website)
footer (text of the footer(copyright))
lat (latitude for the google maps)
lng (longitude for the google maps)
mail (email of the contact page)

获得帖子数量的最佳方式是什么?我从来没有从数据库的一行中获取值。

我一直用这个:

$sql="SELECT np FROM info WHERE id=".$id;
$result=mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) 
$numberofposts=$row['np'];

我应该与WHERE id=1一起使用吗?或者获得该列值的最佳方法是什么?

3 个答案:

答案 0 :(得分:1)

当只返回一行时,您不需要循环:

$sql="SELECT np FROM info WHERE id=".$id;
$result=mysql_query($sql);
$row = mysql_fetch_assoc($result);
$numberofposts=$row['np'];

答案 1 :(得分:0)

你可以使用限制来获得一个结果但是。但是,您可能想重新考虑一下您的方法。将设置作为键值对进行存储,可以在不改变数据库的情况下添加其他配置设置。

答案 2 :(得分:0)

我长时间使用ADODB for php library。它有一些很好的功能来处理数据库。对于你的问题,有一个getOne函数,我相信你的需要。