0

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?

4
  • Is $author_id an empty string, or is it undefined? Commented Oct 11, 2013 at 0:08
  • Your variables will only contain the values from the last successful query in the foreach loop. Is that what you want? Commented Oct 11, 2013 at 0:12
  • @barmar, yes, that's what I want. And if ($result[0]['author']) doesn't return any results, then $author_id should be saved as 0 in the DB. Commented Oct 11, 2013 at 0:19
  • 1
    The problem is that if you try to store an undefined variable, it's trying to set the database column to NULL. My guess is that your schema has NOT NULL for the author_id column Commented Oct 11, 2013 at 0:25

2 Answers 2

2

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

$author_id = '';
foreach ($matches...
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer, i'm not sure to understand. To define $author_id I need to query the DB based on $name . And If $name comes before foreach ($matches[0] as $v), I get an undefined variable error.
@ChHr define variable in this case mean - store "default" value if you didn't find proper one, $name variable depends on $v - which is defined only inside loop, you cannot define it outside
1

you need to define your $author_id first

author_id = null;

and than do a foreach loop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.