0

I've been trying to figure out why I get this error in my prepared statement but I can't solve the problem. I get the error:

Notice: Undefined index: tipimage in C:\xampp\htdocs\Matt\addtip.php on line 68
ERROR: Could not execute query: INSERT INTO tips (tiptitle, tiptext, tiplink, tipimage) VALUES (?, ?, ?, ?). Column 'tipimage' cannot be null

All the values in my database are set to type text, except Id.

....
else {
        /* Attempt MySQL server connection. Assuming you are running MySQL
        server with default setting (user 'root' with no password) */
        $mysqli = new mysqli("localhost", "paul", "pass", "yourcomp");

        // Check connection
        if($mysqli === false){
            die("ERROR: Could not connect. " . $mysqli->connect_error);
        }

        // Prepare an insert statement
        $sql = "INSERT INTO tips (tiptitle, tiptext, tiplink, tipimage) VALUES (?, ?, ?, ?)";

        if($stmt = $mysqli->prepare($sql)){
            // Bind variables to the prepared statement as parameters
            $stmt->bind_param("ssss", $tiptitle, $tiptext, $tiplink, $tipimage);

            // Set parameters
            $tiptitle = $_REQUEST['tiptitle'];
            $tiptext = $_REQUEST['tiptext'];
            $tiplink = $_REQUEST['tiplink'];
            $tipimage = $_REQUEST['tipimage'];

            // Attempt to execute the prepared statement
            if($stmt->execute()){
                $successmsg = "<div class='alert alert-success'>Tip Added Successfully!</div>";
            } else{
                echo "ERROR: Could not execute query: $sql. " . $mysqli->error;
            }
        } else{
            echo "ERROR: Could not prepare query: $sql. " . $mysqli->error;
        }
miken32
  • 42,008
  • 16
  • 111
  • 154
oversoon
  • 350
  • 2
  • 7
  • 21

1 Answers1

2

You're looking for a POST variable that wasn't sent with the request. This is what the undefined index notice is trying to tell you. You don't check to see if it exists before passing it to the database, so it ends up getting passed as null. Just give a default value of an empty string (here using the null coalesce operator) and it will work fine.

$tipimage = $_REQUEST['tipimage'] ?? "";
miken32
  • 42,008
  • 16
  • 111
  • 154