troubleshooting Question

PHP and MySQL page not displaying correct conditional result.

Avatar of centem
centemFlag for United States of America asked on
PHP
2 Comments1 Solution449 ViewsLast Modified:
Greetings,
I am testing a simple php page that performs an INSERT and should echo "Success". But, it print the error message "Database query failed" even though it is successfully inserting the data into the database. Why is it not displaying "Success". Below is the code. Thank you.

<?php
      // 1. Create a database connection
      $dbhost = "localhost";
      $dbuser = "widget_cms";
      $dbpass = "secretpassword";
      $dbname = "widget_corp";
      $connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
      // Test if connection occurred.
      if(mysqli_connect_errno()) {
            die("Database connection failed: " .
                  mysqli_connect_error() .
                   " (" . mysqli_connect_errno() . ")"
            );
      }
?>
<?php
      // Often these are form values in $_POST
      $menu_name = "Edit me";
      $position = (int) 4;
      $visible = (int) 1;
      
      // 2. Perform database query
      $query  = "INSERT INTO subjects (";
      $query .= "  menu_name, position, visible";
      $query .= ") VALUES (";
      $query .= "  '{$menu_name}', {$position}, {$visible}";
      $query .= ")";
      
      $result = mysqli_query($connection, $query);

      if(!$result) {
            // Success
            // redirect_to("somepage.php");
            echo "Success!";
      } else {
            // Failure
            // $message = "Subject creation failed"
            die("Database query failed. " . mysqli_error($connection));
      }
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html lang="en">
      <head>
            <title>Databases</title>
      </head>
      <body>
      

      </body>
</html>

<?php
      // 5. Close database connection
      mysqli_close($connection);
?>
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 2 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros