我正从数据库中检索3个字段,默认情况下,只有用户名字段会包含内容。其他信息将从用户应用程序中添加。如果字段中没有条目,我想将该字段显示为“无信息”。我试图使用empty()和is_null()无济于事。在两种情况下,$ row ['firstname']和$ row ['lastname']的var_dump都返回NULL。
<?php
if (isset($_GET["subcat"]))
$subcat = $_GET["subcat"];
if (isset($_GET["searchstring"])) {
$searchstring = $_GET["searchstring"];
}
$con = mysqli_connect("localhost","user","password", "database");
if (!$con) {
echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error();
exit;
}
$table = 'USERS';
$brand = '%' . $searchstring . '%';
$rows = getRowsByArticleSearch($brand, $table);
echo "<table border='0' width='100%'><tr>" . "\n";
echo "<td width='15%'>Username</td>" . "\n";
echo "<td width='15%'>Firstname</td>" . "\n";
echo "<td width='15%'>Surname</td>" . "\n";
echo "</tr>\n";
foreach ($rows as $row) {
if (is_null($row['firstname']) || $row['firstname'] == "") {
$row['firstname'] == "No Info";
}
if ($row['lastname'] == null || $row['lastname'] == "") {
$row['firstname'] == "No Info";
}
var_dump($row['firstname']);
var_dump($row['lastname']);
echo '<tr>' . "\n";
echo '<td><a href="#" onclick="updateByUser(\''. $row['username'] .'\',\''.$subcat.'\')">'.$row['username'].'</a></td>' . "\n";
echo '<td><a href="#" onclick="updateByUser(\''. $row['username'] .'\', \''.$subcat.'\')">'.$row['firstname'].'</a></td>' . "\n";
echo '<td><a href="#" onclick="updateByUser(\''. $row['username'] .'\', \''.$subcat.'\')">'.$row['lastname'].'</a></td>' . "\n";
echo '</tr>' . "\n";
}
echo "</table>\n";
function getRowsByArticleSearch($searchString, $table) {
$con = mysqli_connect("localhost","user","password", "database");
$recordsQuery = "SELECT username, firstname, lastname FROM $table WHERE lower(username) LIKE ? ";
if ($getRecords = $con->prepare($recordsQuery)) {
$getRecords->bind_param("s", $searchString);
$getRecords->execute();
$getRecords->bind_result($username, $firstname, $lastname);
$rows = array();
while ($getRecords->fetch()) {
$row = array(
'username' => $username,
'firstname' => $firstname,
'lastname' => $lastname,
);
$rows[] = $row;
}
return $rows;
} else {
print_r($con->error);
}
}
答案 0 :(得分:4)
启用display_errors并将error_reporting设置为E_ALL(在php.ini或htaccess中)。这应该揭示任何非明显的错误。
请尝试以下方法检查某些内容是否为空:
<?php
if(!isset($row['...']) || empty($row['...']))
{
$row['firstname'] = 'No Info';
}
?>
此外,请注意您使用'=='将$ row内容设置为'No Info'。这样做会返回'true'(或1)。使用单个'='设置变量。
答案 1 :(得分:3)
首先和你的主要问题:
您在$ row ['firstname'] ==“No Info”中使用比较运算符;而不是分配运营商$ row ['firstname'] = “没有信息”;
其他问题:
答案 2 :(得分:1)
要尝试的两件事......
if($row['field'] === NULL) { }
if(isset($row['field'])) { }
答案 3 :(得分:0)
您可以使用 is_null 属性检查空数据。有关详细信息,请参阅此链接 http://php.net/manual/en/function.is-null.php
is_null($row['field'])
使用
if(is_null($rows['field'])){
// Code Here
}else{
//code here
}