首页 > 解决方案 > 如何修复“警告:非法字符串偏移”

问题描述

以前我尝试将 php pdo 代码翻译成我的 php 版本,但我遇到了这样的问题。“警告:非法字符串偏移 'tagName' in...”。有人可以帮助我,我该怎么办?我不知道基本代码。

PDO 版本:

$stmt2 = $db->prepare('SELECT catTitle, catSlug FROM blog_cats, blog_post_cats WHERE blog_cats.catID = blog_post_cats.catID AND blog_post_cats.postID = :postID');
$stmt2->execute(array(':postID' => $row['postID']));
$catRow = $stmt2->fetchAll(PDO::FETCH_ASSOC);
$links = array();
foreach ($catRow as $cat)
{
$links[] = "<a href='c-".$cat['catSlug']."'>".$cat['catTitle']."</a>";
}
echo implode(", ", $links);

我的PHP:

  $check_tag = mysql_query("SELECT tagName, tagSlug FROM tb_tags, tb_tag_posts WHERE tb_tags.tagID = tb_tag_posts.tagID AND tb_tag_posts.postID = '".$post['postID']."'") or die(mysql_error());
  $tagRow = mysql_fetch_assoc($check_tag);
  $tag_links = array();
  foreach($tagRow as $tag){
    $tag_link[] = "<a href=''>".$tag['tagName']."</a>";
  }
  echo implode(", ", $tag_link);

我需要这样创建:tag-1, tag-2

标签: phpmysql

解决方案


$tagRow是具有 2 个键/值的单行。$tag是一个字符串值。您需要使用 while 循环来获取每一行,然后您可以获取值。

  $check_tag = mysql_query("SELECT tagName, tagSlug FROM tb_tags, tb_tag_posts WHERE tb_tags.tagID = tb_tag_posts.tagID AND tb_tag_posts.postID = '".$post['postID']."'") or die(mysql_error());
  $tag_links = array();
  while($tagRow = mysql_fetch_assoc($check_tag);){
    $tag_link[] = "<a href=''>".$tagRow['tagName']."</a>";
  }
  echo implode(", ", $tag_link);

推荐阅读