在PHP+SQL循环中,用图像替换字符串的出现


Replace occurrence of string with image in PHP+SQL loop?

此PHP代码从我的数据库中获取记录并显示它们。基本上,我希望每次出现字符串"cross"(仅小写)都能更改为web服务器上的图像

记录当前看起来像:crossJohn Doe。因此,当它出现在页面上时,它应该用img替换cross并保留其余部分。

代码:

$sql = "SELECT DisplayName, LastName, FirstName FROM donor WHERE DonationAmount = 1000 ORDER BY LastName ASC LIMIT 154";
 $result = mysqli_query($conn, $sql); // query
 if (mysqli_num_rows($result) > 0) { // as long as the query returns something, do the calcs.
  $array = array(); // create a variable to hold the information
  while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ // whule there are results, put them in the array
     $array[] = $row; // add the row in to the results (data) array
  }
  $counter = (count($array)); // find the amount of items in the array
  $divisorCount = ceil($counter/2); // column count
  $forEachCount = 1;
  //loop while there are items in the array
  foreach ($array as $row){
     $forEachCount++; //increment counter
     // naming logic
     if (empty($row['DisplayName'])) { // if there is no DisplayName
         if (empty($row['FirstName'])) { // show lastname
             $block[] = "<div class='block'>".$row['LastName']."</div>'n";
         }
         else { //show first + last if no display name
             $block[] = "<div class='block'>".$row['FirstName']." ".$row['LastName']."</div>'n";
         }
     } else { // show display name
         $block[] = "<div class='block'>".$row['DisplayName']."</div>'n";
     }

     if($forEachCount > $divisorCount){ //insert each record into a "block"
         $forEachCount = 0;
         end($block);
         $key = key($block);
         $block[$key] .= "</div><div class='column'>"; // insert all "blocks" into a css div
     }
  }
  unset($row,$key,$forEachCount,$divisorCount); //cleanup
  //insert the div and populate it with the blocks
  $output = "<div class='tableContainer'>
    <div class='column'>".implode($block)."</div>
    </div>";
    print_r($output); // display all of it!
    unset($array,$block);
 }else{echo "<p>There are no donors in this category.</p>";}

使用REPLACE-mysql字符串函数可能就足够了

$sql = "SELECT REPLACE(DisplayName,'cross','<img src='"path/to/image'" />') AS `DisplayName`, REPLACE(LastName,'cross','<img src='"path/to/image'" />') AS `LastName`, REPLACE(FirstName,'cross','<img src='"path/to/image'" />') AS `FirstName` FROM donor WHERE DonationAmount = 1000 ORDER BY LastName ASC LIMIT 154";

--http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace

您可以使用mysqli_fetch_assoc,而不是使用mysqli_fetch_array并添加另一个参数以仅获得关联的一个

while ($row = mysqli_fetch_assoc($result)) { 
if (stripos('cross',$row['keyname']) !== false)
$row['keyname'] = str_replace('cross','<img src="path/to/image"/>',$row['keyname']);
$array[] = $row; // add the row in to the results (data) array
}