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 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥15 基于OPENCV的人脸识别
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题