doupi6737 2013-10-11 00:04
浏览 55
已采纳

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

Below is the simple script to allow users to add an <a href> tag to their list.

If there's no <a href> tag, then $author_id is empty.

The first query works fine, the 2nd doesn't if $author_id is empty.

How can i avoid getting an error if it's empty? (i'm sure I'm overthinking

$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();

Any ideas?

  • 写回答

2条回答 默认 最新

  • duanjue2560 2013-10-11 00:10
    关注

    $author_id is not empty in your case, it is undefined, define $author_id before foreach statement as:

    $author_id = '';
    foreach ($matches...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?