0

下面是允许用户将一个添加<a href> tag到他们的列表的简单脚本。

如果没有<a href> tag$author_id则为空。

第一个查询工作正常,如果 $author_id 为空,第二个则不会。

如果它是空的,我怎样才能避免出错?(我确定我想多了

$content = $_POST['book_title'];
preg_match_all('/@\w+/is', $content, $matches);
foreach ($matches[0] as $v) {
    $name = substr($v, 1, strlen($v));
    $sql = "SELECT id, author FROM users WHERE author like '%{$name}%' LIMIT 1";
    $result = query($sql);
      if($result[0]['author']) {
       $author = $result[0]['author'];
       $author_id = $result[0]['id'];
       $content = str_replace($v, "<a href='/$author'>$v</a>",$content);

--->
//if i put $sql query here, $bookid doesn't exist yet
      }
}

    // works fine
$insert=$sth->con->prepare("INSERT INTO booklist (userid, bookid, book) VALUES (?,'', ?)");
$insert->bindParam(1, $id, PDO::PARAM_STR, 12);
$insert->bindParam(2, $content, PDO::PARAM_STR, 12);
$insert->execute();

    // when $author_id is empty, it doesn't work
$sql=$sth->con->prepare("INSERT INTO notifications (notifid, user, author, type, bookid) VALUES ('',?, ?,'3',LAST_INSERT_ID())");
$sql->bindParam(1, $id, PDO::PARAM_STR, 12);
$sql->bindParam(2, $author_id, PDO::PARAM_STR, 12);
$sql->execute();

有任何想法吗?

4

2 回答 2

2

$author_id 在您的情况下不是空的,它是未定义的,在 foreach 语句之前定义 $author_id 为:

$author_id = '';
foreach ($matches...
于 2013-10-11T00:10:47.047 回答
1

你需要先定义你的 $author_id

author_id = null;

而不是做一个foreach循环

于 2013-10-11T00:21:36.407 回答