Curiosity List Curiosity List - 15 days ago 6
MySQL Question

Undefined Variable PHP + MySQL

I know stackoverflow disapproves of repeat questions, but bear with me as I have scanned many similar questions without finding specific resolutions that will help me. (Mostly they mention things about avoiding database insertions)

I encounter these error messages:

here db connection success
Notice: Undefined variable: firstname in C:\xampp\htdocs\practice_connection_app\submit.php on line 10

Notice: Undefined variable: lastname in C:\xampp\htdocs\practice_connection_app\submit.php on line 10

Notice: Undefined variable: conn in C:\xampp\htdocs\practice_connection_app\submit.php on line 11

Fatal error: Call to a member function exec() on null in C:\xampp\htdocs\practice_connection_app\submit.php on line 11


The first result simply shows that I have connected to my database which I made using phpMyadmin.

Here is my relevant code (my html submission page which calls on a php action):

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>student info</title>
</head>
<body>
<br>
Enter your first name and last name in the corresponding boxes.
<br>
<form action="submit.php" method="POST">
First: <input type="text" name="firstname"/>
<br>
Last: <input type="text" name="lastname"/>
<br>
<input type="submit">
</form>


</body>
</html>


the database connection (I think)

<?php
echo 'here';
$dsn = 'mysql:host=localhost;dbname=practice_students';
$username = 'test_usr';
$password = 'pa55word';

try {
$db = new PDO($dsn, $username, $password);
echo 'db connection success';
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}

?>


AND my php submit page

<?php
echo 'here ';
$dsn = 'mysql:host=localhost;dbname=practice_students';


try {
$db = new PDO($dsn);
echo 'db connection success';
$sql = "INSERT INTO people (firstname, lastname)
VALUES ('$firstname', '$lastname')";
$conn->exec($sql);
echo "Now we know your name! Hi," . " " . $firstname . " " . $lastname;
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}
?>


I understand that I may need to do some 'cleaning up' to avoid database insertions, but for now I would just like to know how I can ensure my submissions are going to the database and can be returned.

Thanks in advance!

Answer

Not sure which manual you ahve been reading to end up with that code....

You need to access your POST variables (using $_POST['firstname']) AFTER sanitizing them of course....

EDIT:

To access the POSTed variable, you can do the following:

$firstname = $_POST['firstname'];

But you really need some santization going on, you could use php's filter_var:

$firstname = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);

Though, you can do better than that, and be very strict in what you allow through your filters / sanitizers... Please go investigate this part after you get your code "working" :)

Comments