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

时间:2016-08-01 17:17:36

标签: php sql

此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>";}

2 个答案:

答案 0 :(得分:1)

使用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

答案 1 :(得分:0)

您可以使用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
}