Search code examples
phphtmlsqlherokucleardb

PHP not submitting form data without echo statement?


During a test to see if my database would receive a username through a form field , the code would not work unless I echo'd out error messages. Why is this? My goal is to send the username through the form field , and retrieve the list of usernames on the same page below the form field.

My html for submitting usernames ,

    <section id="banner">
    <div class="content">
    <header>
        <h2>Add Usernames Here</h2>
        <form method="post">
        <br><input type="text" name="user_name"><br>
        <input type="submit" value="Submit"> 
        </form>
    </header>
    </div>

For displaying usernames:

<section id="five" class="wrapper style2 special fade">
<div class="container">
<header>
<h2>Added Usernames</h2>
<?php require 'post.php'; ?>                            
</header>
</div>
</section>

And my post.php code

<?php
//connection
$url = parse_url(getenv("CLEARDB_DATABASE_URL"));
$server = $url["host"];
$username = $url["user"];
$password = $url["pass"];
$db = substr($url["path"], 1);
$conn = new mysqli($server, $username, $password, $db);
//test connection
    if(!$conn)
    {
        echo 'not connected';
    }

    if(!mysqli_select_db($conn,'heroku_cd6b3866e127c21'))
    {
        echo 'database not selected';
    }
//insert username    
    $user_name = $_POST['user_name'];
    $sql = "INSERT INTO store (user_name) VALUES ('$user_name')";

//test query    
    if(!mysqli_query($conn,$sql))
    {
        echo 'not inserted';
    }
    else {
        echo 'inserted';
    }

//echo all usernames    
mysqli_select_db($db,$conn);
$sql2 = "SELECT * FROM  store";

$mydata = mysqli_query('$sql2,$conn');

while($record = mysqli_fetch_array($mydata)){
    echo "<br>";
    echo  $record['user_name'];
}
?>

This code works until I remove the if statements , checking for the connection.


Solution

  • This is simple example, only one page named index.php:

    <form action="index.php" method="post">
        <br><input type="text" name="user_name">
        <br><input type="submit" value="Submit"> 
    </form>
    
    <?php
    $username = $_POST["user_name"];
    $link = mysqli_connect("127.0.0.1", "root", "", "db12");
    mysqli_query($link, "INSERT INTO users (username) values ('$username')");
    
    
    echo $username; 
    
    $query = "SELECT username FROM users";
    
    $result = mysqli_query($link, $query);
        /* fetch associative array */
        while ($row = mysqli_fetch_array($result)) {
            echo $row['username'] . "<br>";
        }
    
    
    /* close connection */
    mysqli_close($link);
    ?>
    

    In production app always write separate page for insert, and always use prepare http://php.net/manual/en/mysqli.prepare.php