如果PDO INSERT查询中为空值,则可以避免错误?

时间:2013-10-11 00:04:58

标签: php mysql sql

以下是允许用户在其列表中添加<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();

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

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

$author_id = '';
foreach ($matches...

答案 1 :(得分:1)

您需要首先定义$ author_id

author_id = null;

而不是foreach循环