Reputation: 439
Hi I was developing my first db connection with php. But for some reason data is not inserting to the table. I have a page that takes the first name and last name. And I created a table called user info. here is the whole code except(error and result page which is all fine).
index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="wrapper">
<div id="main">
<div id="inbox">
<form action="function.php" method="post">
<span id="first">First Name: </span>
<input type="text" name="fname" id="textField">
<span id="second">Last name: </span>
<input type="text" name="lname" id="textField"><br><br>
<input type="submit" value="Submit" id="submitBtn">
</form>
</div>
</div>
</div>
</body>
</html>
database.php
<?php
$dsn = 'mysql:host=localhost;dbname=practice';
$username = 'user';
$password = 'user123';
try {
$db = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}
?>
function.php
<?php
require_once('database.php');
$firstName = filter_input(INPUT_POST, 'fname');
$lastName = filter_input(INPUT_POST, 'lname');
$firstName_q = $db->quote($firstName);
$lastName_q = $db->quote($lastName);
$query = 'INSERT INTO PRACTICE.USERINFO
(USERID, FIRSTNAME, LASTNAME)
VALUES(DEFAULT, $firstName_q, $lastName_q)';
$insert_count = $db->exec($query);
include('result.php');
?>
I am not sure where I am doing the mistake. It seems like its connecting successfully. And shows result page(which is just a text saying successful). But the table is empty.I saw some post similar to this but they are either too long or complicated for me at this time. A help would be highly appreciated. thanks in advance!
Upvotes: 0
Views: 87
Reputation: 36
include
. Incluse does not exist in php.PRACTICE_USERINFO
. Personally I always prefer lower-case for table names.$error_message
var directly, to see what the error might be.$
are not 'read'.Upvotes: 2
Reputation: 13971
There are several issues in your code ,most of them are mentioned by @HarryK in answer , i would like to focus particularly on the specific issue of "Why insert not getting triggered ?" Your query :
$query = 'INSERT INTO PRACTICE.USERINFO
(USERID, FIRSTNAME, LASTNAME)
VALUES(DEFAULT, $firstName_q, $lastName_q);
Replace with double quotes as below :
$query = "INSERT INTO PRACTICE.USERINFO
(USERID, FIRSTNAME, LASTNAME)
VALUES(DEFAULT, $firstName_q, $lastName_q)";
Good Reference :
When to use single quotes, double quotes, and backticks in MySQL
PHP - Single quotes or double quotes around SQL query?
Upvotes: 0