Insert data into mysql using OOP PHP and PDO - php

I am new to PHP and trying to learn OOP PHP.
I am creating a registration form (a simple one) to learn OOP PHP, when I submit data the success message shows up but data is not inserted in data base.
Below is my code:
connection.php
<?php
class DBConnection extends PDO
{
public function __construct()
{
$host='mysql:host=localhost;dbname=OOP';
$user='root';
$password='';
parent::__construct($host,$user,$password);
$this->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// always disable emulated prepared statement when using the MySQL driver
$this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
}
?>
Index.php
<?php
session_start();
/*include 'classes.php';
//$dbHandle = new DBConnection();
$ins=new basic_operation();
$ins->Insert_Data();*/
?>
<div class="col-lg-12">
<div class="col-lg-1"></div>
<div class="col-lg-7">
<form action="user_data.php" method="post" >
<input type="text" name="username" id="username" class="form-control"><br>
<input type="email" name="email" id="email" class="form-control"><br>
<input type="password" name="password" class="form-control" id="password"><br>
<input type="submit" name="submit" id="submit" value="submit">
</form>
</div>
</div>
<div>
<?php if (isset($_SESSION['insert']))
{
echo $_SESSION['insert'];
unset($_SESSION['insert']);
}
?></div>
</div>
</div>
User_data.php
<?php
session_start();
include 'classes.php';
$insert=new basic_operation();
$usr=$insert->Insert_Data();
//return $insert;
$_SESSION['insert']='data inserted successfuly';
header('location:index.php');
?>
Classes.php
<?php
include 'connection.php';
class basic_operation
{
public function Insert_Data()
{
if (isset($_POST['submit'])) {
$user = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['password'];
$smt = new DBConnection();
$qry = $smt->prepare("insert into student(User_Name,Email,Password) VALUES ('" . $user . "','" . $email . "','" . $pass . "')");
$qry->execute();
}
}
}
?>
If any one knows how to perform basic CRUD (insert, update, delete, select) operation in PHP using OOP PHP and PDO Then please provide the link, source, Example, so i can learn from it
I searched on the internet but bearly able to find the connection code... Looking for a descriptive answer, as I think this question will also help a lot of people who try/want to learn OOP PHP.
Any help will appreciated.

Use try-catch in your connection script to get errors.
try {
$pdo = new PDO(
'mysql:host=localhost;port=3306;dbname=your_db;charset=utf8mb4',
'user',
'password',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4")
);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Database connection has failed. Contact system administrator to resolve this issue!<br>';
$e->getMessage();
die();
}
Enable error reporting in php (add this on top of your php script).
error_reporting(E_ALL);
Since you want to use prepared statements then you will have to bind your parameters in order to get escaped properly.
$qry = $smt->prepare("INSERT INTO `student` (`User_Name`,`Email`,`Password`)
VALUES (:user,:email,:pass);");
$qry->bindParam(':user', $user, PDO::PARAM_STR, 255);
$qry->bindParam(':email', $email, PDO::PARAM_STR, 255);
$qry->bindParam(':pass', $pass, PDO::PARAM_STR, 255);
$qry->execute();
Prepared statements with bound parameters are not only more portable,
more convenient, immune to SQL injection, but are often much faster to
execute than interpolated queries, as both the server and client side
can cache a compiled form of the query.
source: Description of PDO::quote in php.net
And last but not least... Always use backticks “`” in your MySQL queries to properly quote MySQL Keywords and Reserved Words such as PASSWORD. You use it in your query as a field but you don't quote it.

Actually the code is working fine, when i try to run it directly using localhost without using phpstorm then it works.. mean the issue is in my IDE.
Thanks for your efforts.

`if (isset($_POST['submit'])) {
$user = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['password'];
$smt = new DBConnection();
$qry = $smt->prepare("insert into student(User_Name,Email,Password) VALUES ('" . $user . "','" . $email . "','" . $pass . "')");
$qry->execute();
}`
Try this
if (isset($_POST['submit'])) {
$user = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['password'];
$smt = new DBConnection();
$qry = $smt->prepare("INSERT INTO student(User_Name,Email,Password) VALUES (:user,:email,:pass)");
$qry->execute(array(':user'=>$user,':email'=>$email,':pass'=>$pass));
}

Related

PHP form doesn't insert into SQL database

I am trying to test a very simple PHP form that inserts input into an SQL database. The connection works fine, but the data does not appear in the database when I refresh it. I have only two files, an index.html and a process.php.
index.html:
<html>
<head>Testing</head>
<body>
<div id="frm">
<form action="process.php" method=POST>
<p>
<label>Username</label>
<input type="text" id="stuff" name="stuff">
</p>
<p>
<input type="submit" id="btn" value="Login">
</p>
</form>
</div>
</body>
</html>
Process.php:
<?php
$userinput = $_POST['stuff'];
$servername = "localhost";
$username = "root";
$password = "";
$database = "testing";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error)
{
die("connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully ";
echo $userinput;
$sql = "INSERT INTO `entries`(`input`) VALUES ('$userinput')";
}
?>
The problem is that you're not actually running the query. You just assigned the query string to a variable, so it's not being executed in MySQL.
Your code is vulnerable to SQL injection, so I'm proposing a solution:
<?php
$userinput = $_POST['stuff'];
$servername = "localhost";
$username = "root";
$password = "";
$database = "testing";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error)
{
die("connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully ";
echo $userinput;
$sql = "INSERT INTO `entries` (`input`) VALUES (?)";
if ($stmt = $conn->prepare($sql)) { // Prepare statement
$stmt->bind_param("s", $userinput); //Bind the string (s), with the content from $userinput to the statement marker (?)
$stmt->execute(); // Run (execute) the query
$stmt->close(); //clean up
}
This code should work and also keep you secure from SQL injections.
Haven't tested it fully but I fixed your query.
$sql = mysqli_query($conn, "INSERT INTO entries (input) VALUES ('$userinput')");
also change the post part to: <form action="process.php" method="POST">
That should fix the problem for you
Also make sure you use the function: mysqli_real_escape_string to escape malicious user input to prevent SQL injection.
Another thing: you could change localhost to 127.0.0.1. I think this is more reliable although it's the same in most cases.
Your code is not submitting the query to the database, it is opening the connection but not submitting the query, see below to the submit query request if you use mysqli in PHP
... else {
# this submits the query
$conn -> query ($sql);
}
you need to take function mysqli_query of mysqli that will take parameter as connection object like $conn and 2nd parameter will be sql query to execute.
like this
$sql = mysqli_query($conn, "INSERT INTO entries (input) VALUES ('$userinput')");
to prevent from sql injection you must use PDO because PDO use paramBind to protect injection .

PHP/MYSQL Insert is doing nothing

I have a simple form set up in HTML to pass values to PHP and put them in a MYSQL database. I just can't fathom why nothing is happening when I click the submit button. Previously it was saying 'failed' but now nothing. I have checked the values from the form - fine. I've checked the database connection - fine. I've checked the SQL statement - well, I can't see any errors.
This is my main HTML page
<p class="subtitle">Let me know what you think</p>
<form action="db_insert.php">
<input name="username" placeholder="Name">
<br>
<textarea name="comments" placeholder="Please type your comments here"
cols=120 rows=5></textarea>
<br>
<input type="button" name="submit" value="submit">
<br>
<p id="commTitle">Comments</p>
<br>
<p id="comment"></p>
This is the PHP
<?php
include 'db_connection.php';
//create database connection
$conn = OpenCon();
$username = htmlspecialchars($_POST['username']);
$comment = htmlspecialchars($_POST['comment']);
$sql = 'INSERT INTO sitecomments(username, comment) VALUES(:username,:comment)';
$stmt = $conn -> prepare($sql);
$stmt -> bindValue(':username', $username);
$stmt -> bindValue(':comment', $comment);
$q_result = $stmt -> execute();
if($q_result){
echo 'Comment Inserted Successfully';
}
else{
echo 'Failed';
}
db_connection.php looks like this (with credentials removed.
<?php
function OpenCon(){
//pass the database details to variables
$host = "localhost";
$dbuser = "*****";
$dbpass = "*****";
$dbname = "*****";
// combine host and db name in to single variable
$dbhost = "mysql:host=$host;dbname=$dbname";
//create PDO from database information
$dbconn = new PDO($dbhost, $dbuser, $dbpass);
return $dbconn;
}
?>
As I said, I've checked the database connection and all is fine so where on earth am I going wrong? My database has 3 fields but one is autoincremented so I haven't included it in the query. I tried the query in MyPHPAdmin and it passed ok.
The first thing I notice is that the input has name of "comments" rather than the $_POST variable you're accessing called comment:
<textarea name="comments" placeholder="Please type your comments here" cols=120 rows=5></textarea>
$comment = htmlspecialchars($_POST['comment']);
Try changing that and see if it fixes the issue.
It would be helpful to handle errors within your code. In your current example if something goes wrong you will have a hard time finding out where the problem is.
You can try all of the following examples from the PHP Docs on PDO error handling and PDO::errorInfo:
Assert your connection is valid:
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
Assert your SQL is valid
/* Provoke an error -- bogus SQL syntax */
$stmt = $dbh->prepare('bogus sql');
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
As usual the error is a pebcak error, and you need to utilize proper debugging tools to find out where your mistakes are. Good luck!

Empty database records after a form submit

I am trying to save a form data into my database but I get just empty records.
I tryied many solutions but I really don't know where's the bug. I am getting crazy!
This is my form:
<head>
<form action="uploadall.php" method="post">
Name: <input type="text" name="name"><br>
Autore: <input type="text" name="author"><br>
Descrizione: <textarea id="editordescription" name="description" cols="45" rows="15">
</textarea>
<script>
CKEDITOR.replace( 'editordescription' );
</script>
<br>Misure: <input type="text" name="misure"><br>
Data: <input type="text" name="date"><br>
<input type="hidden" name="status" value="Disattivo" size="20">
<input type="submit">
</form>
And this is my PHP script to save records:
<?php
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysqli_real_escape_string(htmlspecialchars($_POST['name']));
$author = mysqli_real_escape_string(htmlspecialchars($_POST['author']));
$description = mysqli_real_escape_string(htmlspecialchars($_POST['description']));
$misure = mysqli_real_escape_string(htmlspecialchars($_POST['misure']));
$date = mysqli_real_escape_string(htmlspecialchars($_POST['date']));
$status = mysqli_real_escape_string(htmlspecialchars($_POST['status']));
}
$servername = "xxxxxxx";
$username = "xxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxxxx";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO exposition (name, author, description, misure, date, status)
VALUES ('$name', '$author', '$description', '$misure', '$date', '$status')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
And this is what I get in my database at the moment:
First, you are mixing the mysql api's at somepoint you are using mysqli_* at some point u using mysql_* They don't mix. And mysql_* functions are depreciated they no longer supported by later versions of php. better use mysqli or pdo. this mysql_real_escape_string() or mysqlo_real_escape_string() is not safe enough to prevent you against sql injections. solution is simple better start using mysqli prepared statements or pdo prepared statements.
another error : <input type="text" name="name"> <input type="text" name="name"> these two inputs fields have the same name attribute php will only read one. and you will get an undefined index here $misure = $_POST['misure']; You need to activate error reporting while you are still developing so you can see your errors and notices:
add this at the top of every php page : ini_set('display_errors', 1);
error_reporting(E_ALL);
also date date is a reserved word for mysql so you better use something else for your column name or add backslashes date
Oh and your code never execute here :
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$author = mysql_real_escape_string(htmlspecialchars($_POST['author']));
$description = mysql_real_escape_string(htmlspecialchars($_POST['description']));
$misure = mysql_real_escape_string(htmlspecialchars($_POST['misure']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
$status = mysql_real_escape_string(htmlspecialchars($_POST['status']));
}
Why is that? because you do not have POST value with the submit attribute name. <input type="submit"> see? your submit does not have a name attribute. therefore. This means
all this :
VALUES ('$name', '$author', '$description', '$misure', '$date', '$status')"; These are all undefined variables. I'm surprised why doesn't your server tell you that, with that error reporting enable you will get all those.
This is what u need to do to solve that :
Your html side.
<form action="uploadall.php" method="post">
Name: <input type="text" name="name"><br>
Autore: <input type="text" name="author"><br>
Descrizione: <textarea id="editordescription" name="description" cols="45" rows="15">
</textarea>
<script>
CKEDITOR.replace( 'editordescription' );
</script>
<br>Misure: <input type="text" name="misure"><br>
Data: <input type="text" name="date"><br>
<input type="hidden" name="status" value="Disattivo" size="20">
<input type="submit" name="submit">
</form>
uploadall.php
<?php
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit'])) {
$servername = "xxxxxxx";
$username = "xxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//check your inputs are set and validate,filter and sanitize
$name = $_POST['name'];
$author = $_POST['author'];
$description = $_POST['description'];
$misure = $_POST['misure'];
$date = $_POST['date'];
$status = $_POST['status'];
//prepare and bind
$sql = $conn->prepare("INSERT INTO exposition (name, author, description, misure, date, status)
VALUES (?,?,?,?,?,?)");
$sql->bind_param("ssssss", $name, $author, $description, $misure, $date);
if ($sql->execute()) {
echo "New record created successfully";
} else {
//you have an error
}
$conn->close();
}
?>
That's all good luck.
Update :
I corrected errors you told me and I am using PDO now but it still
doesn't work
I read that from your comments above, but you not telling us what the errors are, but I believe they are the ones I highlighted above.
with PDO this is how u will achieve your goal :
<?php
//connection
$servername = 'XXXXXXXXXXXXX';
$dbname = 'XXXXXXXXXXXXX';
$username = 'XXXXXXXXXXXXXX';
$password = 'XXXXXXXXX';
$charset = 'utf8';
$dsn = "mysql:host=$servername;dbname=$dbname;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dbh = new PDO($dsn, $username, $password, $opt);
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit'])) {
//check your inputs are set and validate,filter and sanitize
$name = $_POST['name'];
$author = $_POST['author'];
$description = $_POST['description'];
$misure = $_POST['misure'];
$date = $_POST['date'];
$status = $_POST['status'];
//prepare and bind
$stmt = $dbh->prepare("INSERT INTO exposition (name, author, description, misure, date, status)VALUES (?,?,?,?,?,?)");
if ($stmt->execute(array($name,$author,$description,$misure,$date,$status))) {
echo "New Record inserted success";
}
}
?>
Variable name problem E.g
Name: <input name="name">
and :
Misure: <input name="name">.This must be different.
Again, <input type="submit"> should be <input type="submit" name="submit">.
Hope, it will be helpful.
The variables you are using inside your INSERT Query are out of scope from the first if block where you are getting the data from your form. If the variables are initialized before the first if block it might work. like below..
$name = ""; $author = "";$description = "";$misure = "";$date = "";$status=";
if (isset($_POST['submit'])){ // as is}

Form area textarea is not updating to the database because of special characters

I have a form field for an update - where I have given the administrators the ability to make changes to comments:
<form method="post" action="form_action.php?job_numb=<?=$job_numb;?>" enctype="multipart/form-data">
<textarea class="form-control"
rows="10"
name="comments"
maxlength="5000">
<!--This is grabbing the previous $comments from the database-->
<?php echo html_entity_decode($comments);?>
</textarea>
</form>
I was wondering why text seemed truncated or cut-off, thinking it had to do with character limit it did not. How do you make sure the special characters don't stop the SQL from breaking?
The SQL row is set to text.
I have since learned that I just needed prepared statements, and that "cleaning" the data was not necessary at all.
See code below
<?php
$servername = "localhost";
$username = "XXXXX";
$password = "XXXXX";
try {
$conn = new PDO("mysql:host=$servername;dbname=**YOURDATABASE**", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
if(isset($_POST['submit']) && !empty($_POST['submit'])) {
$job_name = htmlspecialchars($_POST['job_name'], ENT_QUOTES, 'UTF-8');
$comments = htmlspecialchars($_POST['comments'], ENT_QUOTES, 'UTF-8');
}
$conn->exec($sql);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
$sql = "UPDATE `jobs_canjobs` SET
`job_name`='$job_name',
`comments`='$comments'
WHERE job_numb = '$job_numb'";
?>
There is no need for a second variable, and although the previous method worked - it was just an extra step.

PHP adding information to database

I have a slight problem here with my PHP page. I have difficulties getting the filled in data in a database.
Let me show you the code of the index;
<form action="aanmelden.php" method="post">
Naam: <input type="text" name="naam"><br>
Achternaam: <input type="text" name="achternaam"><br>
<input type="submit">
</form>
<php
$nm = $_POST['naam;];
$anm = $_POST['achternaam'];
?>
Now I thought I had obtained the variabled and sent to the 'aanmelden.php' file.
The contents of the aanmelden.php file are:
<?php
$nm = $_GET['naam'];
$anm = $_GET['achternaam'];
$connect = mysql_connect('localhost', 'root', 'usbw');
mysql_select_db ('kantine');
$sql = "INSERT into kantine (naam, achternaam)
VALUES ('$nm', '$anm')";
$res = mysql_query($sql);
mysql_close ($connect); ?>
Looks all quite good to me, but when I press the submit button I get the following errors.
Notice: Undefined index: naam in I:\USBWebserver v8.6\root\aanmelden.php on line 2
Notice: Undefined index: achternaam in I:\USBWebserver
v8.6\root\aanmelden.php on line 3
Please help me out if you can.
Regards,
Demiën
Since your form is configured to use method="post", you should be using the $_POST array rather than $_GET.
$name = $_POST['name'];
$lname = $_POST['lastname'];
See The Method Attribute.
Also, to avoid potential undefined indexes, I'd advise setting these variables with the ternary operator. That way, you can check for the existence of particular indexes before trying to access them.
$name = isset($_POST['name']) ? $_POST['name'] : false;
$lname = isset($_POST['lastname']) ? $_POST['lastname'] : false;
Edit
Other potential issues (or typos) with your code are:
// invalid, should be <?php
<php
// semi-colon instead of a closing quote, should be $_POST['name']
$name = $_POST['name;];
Note the mismatch:
<form action="register.php" method="post">
^^^^
$name = $_GET['name'];
^^^^
You probably want $_POST instead.
And note that you are vulnerable to sql injection attacks
You are using method POST when you submit the form; however you are using the GET method to retrieve the information.
Change $_GET to $_POST on register.php and that should do the trick.
You probably don't want SQL Injection vulnerabilites, so I coded you a nice example of connecting to a DB and writing some values in it from POST.
<?php
$DB_SERVER = 'server_adress';
$DB_USER = 'mysql_server';
$DB_PASSWORD = 'myPassword';
$DB_NAME = 'myFancyDB';
try {
$db = new PDO("mysql:host=" . $DB_SERVER . ";dbname=" . $DB_NAME, $DB_USER, $DB_PASSWORD, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8mb4'));
} catch (PDOException $e) {
//Remove this Errormessage in Production as it leaks dbname + password
echo $e->getMessage();
}
//Now the DB has been initialized.
try {
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$sql = "INSERT INTO `registrierung` (Name, Lastname) VALUES (:name, :lastname);";
$query = $db->prepare($sql);
$query->execute(array(
':name' => $name,
':lastname' => $lastname));
if (!$query) {
echo 'Fail when executing query';
exit;
}
} catch (PDOException $e) {
//Remove this Errormessage in Production!! Leaks DB info. Replace with generic Errormessage
echo $e->getMessage();
exit;
}
echo "Success!";

Categories