0
$query = "INSERT INTO api_fails (file, code, url, date) VALUES (?, ?, ?, ".time().")";

$stmt = $mysqli->stmt_init();
if(!$stmt->prepare($query)) {
    echo("Failed to prepare statement.<br />\n");
} else {
    $file = $_GET['f'];
    $code = $_GET['c'];
    $url = $_GET['u'];
    $stmt->bind_param("sis", $file, $code, $url);
    if($stmt->execute()) {
        echo("Inserted.<br />\n");
    }else {
        echo("Didn't insert.<br />\n");
    }
}

I have found if any of the following variables are not set, the insert fails...

    $file = $_GET['f'];
    $code = $_GET['c'];
    $url = $_GET['u'];

How do I setup my insert so that if the variable isn't set it just inserts nothing into that field?

1 Answer 1

2

Just assign empty values to those variables if they are not set:

$file = (isset($_GET['f'])) ? $_GET['f'] : '' ;
$code = (isset($_GET['c'])) ? $_GET['c'] : '' ;
$url  = (isset($_GET['u'])) ? $_GET['u'] : '' ;
Sign up to request clarification or add additional context in comments.

3 Comments

lol, wow that worked. I thought '' would be the same as null, guess not. Thanks. I'll accept as soon as the 8 minutes are up and it lets me :) PS is there a better way to do this? Seems kind of limited if one of your variables is null the whole insert fails.
Yea actually I'm going to hold out a bit and see if someone has a more elegant solution. I have some big queries with 85 fields that need to be filled with data. I'd rather not make 85 more lines to set the variables to ''.
Worst case I'll put all these insert statements into a function and set the default value of each parameter, which is still a huge hassle cause I can't pass an array of 85 values and instead I have to have a function with 85 parameters.

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.