Jump to content

Not sure why I connect to db but cannot create row.


exceedinglife

Recommended Posts

I have a simple form and I run my script without any errors. I click my btn and I would like to see my echo errors but no errors show up when I have no value in textboxes. I have tried if(isset($_Post["submit"])) and if($_SERVER["REQUEST_METHOD"] == "post") What I think is nether of there ifs are becoming valid on my btn click.

<?php
$nameerror = $twoerror = $errormsg = "";
// PHP Procedural MYSQLi
// connect to mysql database with phpmyadmin
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "test";

$connection = new mysqli($servername, $username, $password, $dbname);
//if(isset($_Post["submit"]))
if($_SERVER["REQUEST_METHOD"] == "post")
{
    if(empty(trim($_Post["name"]))) {
        $nameerror = "Name is required";
    }
    else {
        $namesafe = mysqli_real_escape_string($connection, $_Post["name"]);
    }
    if(empty(trim($_Post["two"]))) {
        $twoerror = "Two is required";
    }
    else {
        $twosafe = mysqli_real_escape_string($connection, $_Post["two"]);
    }

    if($namesafe != "" && $twosafe != "") {
        $sqlInsert = "INSERT INTO tester(name, two) " .
          "VALUES('". $namesafe ."','". $twosafe ."')";

          if(mysqli_query($connection, $sqlInsert)) {
              echo "Successfully entered.";
          } else {
              echo "NOT successful error: " . $sqlInsert . "<br>" . mysqli_error($connection);
          }
    } 
}
mysqli_close($connection);
?>
<?php

      if(!$connection) {
        die("Connection Failed! " . mysqli_connect_error());
      }
      echo "Connected Successfully@!";



   ?>
    <section class="text-align" id="section-content">
        <div id="alertMessages" class="container rounded"></div>
        <div id="contentdiv" class="container rounded">
            <form id="formtest" class="rounded" method="post" >
              <!-- action="" -->
                <h3>PHP Create</h3>
                <?php
                    if(isset($errormsg)) {
                    //  echo "<div><span>";
                      echo $errormsg;
                    //  echo "</span></div>";
                    }
                 ?>
                <div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="txtName" name="name" />
                        <label for="txtName">Name </label>
                        <?php if(isset($nameerror)) { echo '<span class="error">' . $nameerror . '</span>'; } ?>
                        <!-- ? php//if(isset($_Post["name"])) echo htmlspecialchars($_Post["name"]); ? >" /> --->
                        <!-- <span class="error"><?php //echo $nameerror; ?></span> -->
                    </div>
                    <div>
                        <input type="text" class="form-control" id="txttwo" name="two" />
                        <label for="txttwo">Text Two </label>
                        <?php if(isset($twoerror)) { echo '<span class="error">' . $twoerror . '</span>'; } ?>
                    </div>
                </div>
                <button type="submit" class="btn btn-lg btn-primary btn-block" name="submit">Click</button>
            </form>
        </div>
    </section>

 

Link to comment
Share on other sites

It still does not insert data from my 2 text boxes into the mysql database. 

I tried it with this. "INSERT INTO tester (name, two) VALUES('Andrew', 'moredata')";

That works.. So I dont understand why I cant $_POST["name"] values from a textbox and insert into mysql

Here is my exact code.

<?php
$nameerror = $twoerror = $errormsg = "";
// PHP Procedural MYSQLi
// connect to mysql database with phpmyadmin
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "test";

$connection = new mysqli($servername, $username, $password, $dbname);
//if(isset($_POST["submit"]))
if($_SERVER["REQUEST_METHOD"] == "post")
{
    if(empty(trim(["name"]))) {
        $nameerror = "Name is required";
    }
    else {
        $namesafe = mysqli_real_escape_string($connection, $_POST["name"]);
    }
    if(empty(trim($_POST["two"]))) {
        $twoerror = "Two is required";
    }
    else {
        $twosafe = mysqli_real_escape_string($connection, $_POST["two"]);
    }

    if($namesafe != "" && $twosafe != "") {
        $sqlInsert = "INSERT INTO tester(name, two) " .
          "VALUES('". $namesafe ."','". $twosafe ."')";

          if(mysqli_query($connection, $sqlInsert)) {
              echo "Successfully entered.";
          } else {
              echo "NOT successful error: " . $sqlInsert . "<br>" . mysqli_error($connection);
          }
    } else {
        $errormsg = '<div class="alert alert-danger alert-dismissible fade show" role="alert"><button type="button" ' .
            'class="close" data-dismiss="alert" aria-label="Close" aria-hidden="true">&times;</button>' .
            'All fields are required to continue</div>';
    }
}
//else { echo "ELSE on btn click "; }

mysqli_close($connection);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>PHP BootStrap</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- BootStrap 4 CDN link -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">

</head>
<body>
  <?php

      if(!$connection) {
        die("Connection Failed! " . mysqli_connect_error());
      }
      echo "Connected Successfully@!";

   ?>
    <section class="text-align" id="section-content">
        <div id="alertMessages" class="container rounded"></div>
        <div id="contentdiv" class="container rounded">
            <form id="formtest" class="rounded" method="post" >
              <!-- action="" -->
                <h3>PHP Create</h3>
                <?php
                    if(isset($errormsg)) {
                    //  echo "<div><span>";
                      echo $errormsg;
                    //  echo "</span></div>";
                    }
                 ?>
                <div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="txtName" name="name" />
                        <label for="txtName">Name </label>
                        <?php if(isset($nameerror)) { echo '<span class="error">' . $nameerror . '</span>'; } ?>
                        <!-- ? php//if(isset($_POST["name"])) echo htmlspecialchars($_POST["name"]); ? >" /> --->
                        <!-- <span class="error"><?php //echo $nameerror; ?></span> -->
                    </div>
                    <div>
                        <input type="text" class="form-control" id="txttwo" name="two" />
                        <label for="txttwo">Text Two </label>
                        <?php if(isset($twoerror)) { echo '<span class="error">' . $twoerror . '</span>'; } ?>
                    </div>
                </div>
                <button type="submit" class="btn btn-lg btn-primary btn-block" name="submit">Click</button>
            </form>
        </div>
    </section>

    <!-- BootStrap 4 CDN JavaScript -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
    <!--<script></script>-->
</body>
</html>

 

Link to comment
Share on other sites

its commented out I havent retried the request_method but ok i will change it to "POST"
and i found in a trim() I had trim['name'} and needed trim($_POST['name']) I made a new file and copyed some of the php over and trying it step by step because i cant get xdebug to work with my atom ide for some reason my error showed on action="myphp.php" it showed on the new php file but in the network tab b4 when i ran it it didnt show a error

Link to comment
Share on other sites

action="" means the form should submit its data to the current URL.

If you want the browser to not submit the form under certain conditions then you would need Javascript.

However, if what you want is simply to require the two inputs to have values then you can set the "required" attribute on them. As in

<input type="text" class="form-control" id="txtName" name="name" required />

The browser will not let the user submit unless both have been filled. But you still need to validate in your PHP.

Link to comment
Share on other sites

lol THANKS i forgot about required. 

Here is another question I have.

I have a mysql db and I am running a check to see if a name is in the table.

Can I stop the query if the name is in the able without having the database being unique.

Here is the code in which i mean,

if($namesafe != "" && $twosafe != "") {
      // Check and see if EXISTS
          $sqlCheck = "SELECT * FROM tester WHERE name ='". $namesafe ."'";
        $check = mysqli_query($connection, $sqlCheck);
        $numRows = mysqli_num_rows($check);
        if($numRows != 0) {
            $errormsg = '<div>Name has <b>ALREADY</b> been <u>used</u>!<br>'. $namesafe .'</div>';
            die();
        }

 

Link to comment
Share on other sites

<?php
$nameerror = $twoerror = $errormsg = "";
$namesafe = $twosafe = "";
// PHP Procedural MYSQLi
// connect to mysql database with phpmyadmin
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "test";

$connection = new mysqli($servername, $username, $password, $dbname);

//if(isset($_POST["submit"]))
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    if(empty(trim($_POST["name"]))) {
        $nameerror = "Name is required";
    }
    else {
        $namesafe = mysqli_real_escape_string($connection, $_POST["name"]);
    }
    if(empty(trim($_POST["two"]))) {
        $twoerror = "Two is required";
    }
    else {
        $twosafe = mysqli_real_escape_string($connection, $_POST["two"]);
    }

    if($namesafe != "" && $twosafe != "") {
      // Check and see if EXISTS
          $sqlCheck = "SELECT name FROM tester WHERE name ='". $namesafe ."'";
        $check = mysqli_query($connection, $sqlCheck);
        $numRows = mysqli_num_rows($check);
        if($numRows != 0) {
            $errormsg = '<div class="alert alert-danger alert-dismissible fade show" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close" aria-hidden="true">
            &times;</button>Name has <b>ALREADY</b> been <u>used</u>!<br>'. $namesafe .'</div>';
            die("die");

        } else {
          $errormsg = "HERE is the other stopping try";
          die();
        }

        $sqlInsert = "INSERT INTO tester(name, two) " .
            "VALUES('". $namesafe ."','". $twosafe ."')";
          if(mysqli_query($connection, $sqlInsert)) {
              echo "Successfully entered.";
          } else {
              echo "NOT successful error: " . $sqlInsert . "<br>" . mysqli_error($connection);
          }
    } else {
        $errormsg = '<div class="alert alert-danger alert-dismissible fade show" role="alert"><button type="button" ' .
            'class="close" data-dismiss="alert" aria-label="Close" aria-hidden="true">&times;</button>' .
            'All fields are required to continue</div>';
    }
}
//else { echo "ELSE on btn click "; }

mysqli_close($connection);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>PHP BootStrap mysql Create</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- BootStrap 4 CDN CSS external link -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
    <!-- Custom CSS Link -->
    <link rel="stylesheet" href="css/main.css" />
</head>
<body>

  <?php
      if(!$connection) {
        die("Connection Failed! " . mysqli_connect_error());
      }
      echo "Connected Successfully@!";
   ?>
    <section class="text-align" id="section-content">
        <div id="alertMessages" class="container rounded"></div>
        <div id="contentdiv" class="container rounded">
            <form id="formtest" class="rounded" method="post" action="">
              <!-- action="" -->
                <h3>PHP Create</h3>
                <?php
                    if(isset($errormsg)) {
                      echo $errormsg;
                    }
                 ?>
                <div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="txtName" name="name" required/>
                        <label for="txtName">Name </label>
                        <?php if(isset($nameerror)) { echo '<span class="error"><b>' . $nameerror . '</b></span>'; } ?>
                    </div>
                    <div>
                        <input type="text" class="form-control" id="txttwo" name="two" required/>
                        <label for="txttwo">Text Two </label>
                        <?php if(isset($twoerror)) { echo '<span class="error"><b>' . $twoerror . '</b></span>'; } ?>
                    </div>
                </div>
                <button type="submit" class="btn btn-lg btn-primary btn-block" name="submit">Click</button>
            </form>
        </div>
    </section>
    <!-- BootStrap 4 CDN JavaScript -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
    <!--<script></script>-->
</body>
</html>

This is my whole project 100% 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.