1

I am coding my first php app and I am basing it off a tutorial I was working on that worked. My code as of right now works fine until I get to the $var = $connection->query("INSERT INTO . . . etc.

At this point, the code immediately after the first $ just shows up as plaintext in firefox. (google shows the whole thing as text blah).

I will post my code here:

<?php 



$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "cowboyserver";

$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword);
mysqli_select_db($dbName, $conn);


$email = ($_POST['email']);

if(!$conn){
    echo 'error';
}else{
    $query = $conn->query("INSERT INTO email_list  (email) VALUES ('$email')");
}
mysqli_query($query);
header("Location: ../index.html?signup=success");
echo '<p>email entered !! ! ! ! ! ! !! !! ! ! ! ! !</p>'    ;

Additionally, here is the HTML : : : :

<form autocomplete="on" action="includes/signup.inc.php" method="POST">
    <input type="email" name="email" placeholder="put your email here" class="blah"/>
</form>

EDIT: After trying some solutions, I have found that my php code breaks at a seemingly random point in the code. In the second answer posted, for example, the php code runs until it gets to "$conn->connect_error" in the if statement and then prints out everything after the -> instead of executing it.

Quibble
  • 173
  • 1
  • 7
  • 3
    **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST`, `$_GET` or **any** user data directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman Sep 03 '17 at 18:19
  • 2
    Note: The object-oriented interface to `mysqli` is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete `mysql_query` interface. Before you get too invested in the procedural style it’s worth switching over. Example: `$db = new mysqli(…)` and `$db->prepare("…”)` The procedural interface is an artifact from the PHP 4 era when `mysqli` API was introduced and should not be used in new code. – tadman Sep 03 '17 at 18:19
  • 1
    A lot of problems can be detected and resolved by [enabling exceptions in `mysqli`](https://stackoverflow.com/questions/14578243/turning-query-errors-to-exceptions-in-mysqli) so mistakes aren't easily ignored. – tadman Sep 03 '17 at 18:19
  • 1
    It's also extremely concerning that you're directly referencing a `.inc.php` file. Those are typically named `.inc` to prevent direct execution, and furthermore, are never intended to be called directly. – tadman Sep 03 '17 at 18:20
  • This seems really helpful and quite scary, but I'm new to php and I don't know what a parameterized query is or how to fix any of these problems (nor the difference between mysql and mysqli) After looking at the exceptions article I understand the purpose but not the implementation. How do I avoid using $_POST and .inc.php files in the php if I need them to be able to get data? – Quibble Sep 03 '17 at 18:32
  • I'm not sure what reference material you're working from to organize your code, but `.inc` files are supposed to be "included", never executed. They're for libraries of code. `.php` files are intended to be run, they're endpoints for your application. I'd encourage you to have a look at a PHP survival guide like [PHP the Right Way](http://www.phptherightway.com) and find best practices to embrace. – tadman Sep 03 '17 at 18:33
  • I'd also strongly advise you to look at various [development frameworks](http://codegeekz.com/best-php-frameworks-for-developers/) to see if you can find one that fits your style and needs. They come in various flavors from lightweight like [Fat-Free Framework](https://fatfreeframework.com/) to far more comprehensive like [Laravel](http://laravel.com/). These give you concrete examples to work from and much stronger guidance on how to write your code and organize your files. – tadman Sep 03 '17 at 18:36
  • @tadman Here is the reference: https://www.youtube.com/watch?v=xb8aad4MRx8 Thank you for everything :) – Quibble Sep 03 '17 at 20:35
  • Sadly that tutorial, like 99.9% of the tutorials on YouTube, is a complete waste of time and not worth learning from. Virtually everything about it is at least a decade out of date, if not more. It starts with "A login system is really easy to create..." which is *flat out wrong* and goes downhill fast. In the summary: "PDO is used in Object Oriented PHP Programming, meaning that we CANNOT use it in this lesson." Why not? If you can't handle rudimentary object-oriented programming you are not ready to write a login system. Period. – tadman Sep 03 '17 at 20:48
  • @rickdenhaan I fixed the problem . I had to delete this code:AddType application/x-httpd-php .php AddType application/x-httpd-php-source .phps That was in the htaccess folder I made because I thought that I needed php stuff in the index.html. Hold on, I'm putting the .htaccess code back in ! – Quibble Sep 03 '17 at 21:27
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/153572/discussion-between-quibble-and-tadman). – Quibble Sep 03 '17 at 21:27

2 Answers2

3

Changes you needed:-

1.Need to change file name from signup.inc.php to signup.php and then use it in from like below:-

<form autocomplete="on" action="includes/signup.php" method="POST">
    <input type="email" name="email" placeholder="put your email here" class="blah"/>
</form>

2.change in signup.php(the file you renamed) code (changes are commented):-

<?php 
//comment these two lines when code executed successfully
error_reporting(E_ALL);
ini_set('display_errors',1);

if(!empty($_POST['email']){ // check posted data coming or not
    $dbServername = "localhost";
    $dbUsername = "root";
    $dbPassword = "";
    $dbName = "cowboyserver";

    $conn = mysqli_connect($dbServername, $dbUsername, $dbPassword,$dbName); //add dbname here itself
    //check conneced or not
    if(!$conn){ // $ missed
     die('connection problem'.mysqli_connect_error());//check for real connection problem
    }else{
        $email = $_POST['email'];// remove ()

        //don't mix oop way to procedural way and use prepared statements

        $stmt = mysqli_prepare($conn, "INSERT INTO email_list (email) VALUES (?)"));

        /* bind parameters for markers */
        mysqli_stmt_bind_param($stmt, "s", $email);

        /* execute query */

        if(mysqli_stmt_execute($stmt)){//check query executes or not
            header("Location: ../index.html?signup=success");
            echo '<p>email entered !! ! ! ! ! ! !! !! ! ! ! ! !</p>';
            exit();
        }else{
            echo "insersion failde because of".mysqli_error($conn); 
        }
    }

}else{
    echo "please fill the form";
}

Note:- always use prepared statements to prevent from SQL INJECTION.Thanks

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
  • I edited my code, and this seems right but honestly I have no idea what I'm looking at. I will run it and check back with you after the XAMPP panel stops having the pesky port 80 error again. – Quibble Sep 03 '17 at 20:53
  • When I run the code this is what happens in the browser: email entered !! ! ! ! ! ! !! !! ! ! ! ! ! '; }else{ echo "insertion faild bc of".mysqli_error($conn); } } }else{ echo "plz fill out form"; } – Quibble Sep 03 '17 at 20:56
  • I removed the htaccess file that had two lines in it but were messing things up, but now it is getitng me a parse error: "Syntax error, unexpected '{' in C:\xampp\htdocs\folder\includes\signup.php on line 6 – Quibble Sep 03 '17 at 21:14
  • It was just a typo. The last fix almost always is. Thank you, this is the right answer. If you happen to come back to this I would appreciate learning more about why this works but BLESS YOU for this and I hope you win the lottery today – Quibble Sep 03 '17 at 21:18
2

Try this. Change your form to include a submit button. Then only you can access values using $_POST.

<form autocomplete="on" action="includes/signup.php" method="POST">
    <input type="email" name="email" placeholder="put your email here" class="blah"/>
    <input type="submit" value="Form Submission" name="submitBtn">
</form>

Your signup.php page:

<?php

$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "cowboyserver";

// Create connection
$conn = new mysqli($conn = new mysqli($dbServername, $dbUsername, $dbPassword, $dbName));
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if(isset($_POST['submitBtn'])) { //form submission occured

    $email = $_POST['email'];
    $sql = "INSERT INTO email_list (email) VALUES ('$email')";

    if ($conn->query($sql)) {
        echo '<p>email entered !! ! ! ! ! ! !! !! ! ! ! ! !</p>';
        header("Location: ../index.html?signup=success");
        exit();

    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

} else {
    echo "Form Submission Error";
}

$conn->close();
?>

Hope it's helpful.

Sreejith BS
  • 1,183
  • 1
  • 9
  • 18