JVE999
JVE999

Reputation: 3517

I'm new to PHP and MySQL. I cannot figure this simple system out

    <?php
        $db = new mysqli("localhost","root","password","eme");

        if($db->connect_errno){ echo "Not connected."; exit();}

        echo $db->query("SELECT * FROM users") . "<br>";
        echo $_POST[FirstName] . " " . $_POST[LastName];
        $db->query("INSERT INTO users (FirstName, LastName) VALUES ('$_POST[FirstName]','$_POST[LastName]')");
        echo $db->query("SELECT * FROM users") . "<br>";

    ?>

I cannot figure out why this code doesn't work. The only line that outputs anything is "echo $_POST[FirstName] . " " . $_POST[LastName];"

My database has a "users" table and the database is called eme. The database connects properly.

There is currently no data in the database. I figured I could add some with "INSERT," but it's failing.

Upvotes: 0

Views: 67

Answers (2)

cwurtz
cwurtz

Reputation: 3257

You have several problems:

The query() method of mysqli returns a mysqli_result object. you need to use one of it's methods to get the actual data back from the query. For instance fetch_assoc()

In your insert, you need to either assign $_POST['FirstName'] to a variable, or explicitly add it to the string.

ie.

"INSERT INTO users (FirstName, LastName) VALUES ('" . $_POST['FirstName'] . "','" . $_POST['LastName'] . "')"

or

$first = $_POST['FirstName'];
$last = $_POST['LastName'];
"INSERT INTO users (FirstName, LastName) VALUES ('" . $first . "', '" . $last . "')"

You should also sanitize the data before inserting it to prevent major security threats.

Lastly, it's not a bug per se, but you should always use a string or integer value for an array index.

ie. You have $_POST[FirstName], it should be either $_POST['FirstName'] or $_POST["FirstName"]

It will still work, but the interpreter thinks it's a constant, which isn't defined, so assumes the literal value, throwing a warning (maybe notice, can't remember offhand). It's unnecessary overhead.

Upvotes: 1

Ashwini Agarwal
Ashwini Agarwal

Reputation: 4858

Try this...

$db->query("INSERT INTO users (FirstName, LastName) VALUES('".$_POST['FirstName']."','".$_POST['LastName']."')");

For more info on Quotes, look over this link - What is the difference between single-quoted and double-quoted strings in PHP?

Upvotes: 1

Related Questions