可能重复:
如何在PhP中检查mysql条目是否为空?
我试图运行一个看似简单的if语句,然而,我的PHP技能并没有那么好。
我从一个MySQL表中查询数据,我想运行一个语句来检测字段是否为空,如果不是,我希望它显示一些内容,如果是,不显示任何内容。
此外,我不确定是否有可能将其放在回声中?
编辑:************************以下是让事情变得更容易的代码:
我可能做错了什么。这是我的代码,可以更容易地解释
'
if (!$result) {
exit('<p>Error performing query: ' . mysql_error() . '</p>');
}
//creating the table w/ headers
echo '
<table>
<thead>
<tr>
...
<th style="width:90px"><strong><a href="other-items.php?order=oc_retailer">Retailer</a></strong></th>
<th style="width:90px"><strong>Files</strong></th>
</tr>
</thead>';
// Display each item
while ($row = mysql_fetch_array($result)) {
echo '
<tr>
...
<td style="width:90px">' . $row['oc_retailer'] .'</td>
<td style="width:90px"> this is where I want to if statement to go</td>
';
}
echo '</table>';
?>'
您可以使用empty()
函数,该函数将检查是否有任何内容。
isset()
检查字段上的null(boolean==false),您也可以使用它。
if(empty($row['yourColumn']))
{
// it's empty!
echo "Nada in the field!.'n";
}
else
{
// Do stuff with the field
}
编辑:我想这就是你的意思:
while ($row = mysql_fetch_array($result))
{
if(!empty($row['oc_retailer']))
{
echo '
<tr>
...
<td style="width:90px"> this is where I want to if statement to go</td>
';
}
else
{
echo '
<tr>
...
<td style="width:90px">Ruh ohes! The Row was Empty!</td>
';
}
}
我从一个MySQL表中查询数据,我想运行一个语句来检测字段是否为空,如果不是,我希望它显示一些内容,如果是,不显示任何内容。
所以,你有一个结果集,我认为它是一个数组?在这种情况下,您需要检查该值是否不等于空字符串:
if($resultset['fieldname']===' '){
echo 'fieldname was empty';
}
请注意,isset的答案实际上是无效的:值将始终被设置,因为字段存在于结果集中,默认情况下它只是一个空字符串。
EDIT:我弄错了empty( )
调用,它似乎是在检查isset($var) && !$var
。尽管如此,因为您可以控制查询的列,所以不需要isset部分,我建议在这种情况下不要使用empty( )
。
从MySQL获取数据后,尝试
if (!isset($data[0]))
echo 'Input some data';
或
if (strlen($data[0])<1)
echo 'Input some data';
如果使用mysql_query
,则可以使用
if (mysql_num_rows($result) > 0) {
echo "There's Data";
}
检查mysql_num_rows()
但最好只是使用事先准备好的语句。
PDO使用PDO::rowCount()
Mysqli使用num_rows