Crud insert method - php

I am creating a database for employees, and I am applying the crud operation to it
The problem with the code is that I cannot insert data into the database from the fields, I also get this error:
do not access superglobal $_post array directly.
<?php
session_start();
include("configa.php");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$FirstName = filter_input(INPUT_POST, $_POST["FirstName"]);
$LastName = filter_input(INPUT_POST, $_POST["LastName"]);
// attempt insert query execution
$sql = "INSERT INTO employeeinfo (FirstName, LastName) VALUES ('$FirstName', '$LastName')";
if(mysqli_query($mysqli, $sql)){
echo "Records added successfully.";}
else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($mysqli);
}
// close connection
$sql = 'INSERT INTO `employeeinfo`(`FirstName`, `LastName`) ';
$sql = $sql . "VALUES (\"$FirstName\", \"$LastName\") ";
if ($mysqli->query($sql) === TRUE) {
echo "New record created successfully";
$_SESSION['completed'] = "YES";
} else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
header('Location: Employee.php');
}else
{
echo 'BYE BYE !!!';
}
mysqli_close($mysqli);
?>

So the filter_input() method in php accepts a third parameter specifying what it should do as a filtering function. You could go with the filter FILTER_SANITIZE_STRING, judging by your case.
Refer the filter_array method in php manual : http://php.net/manual/en/function.filter-input.php
Refer what filters are available in php : http://php.net/manual/en/filter.filters.php
What Filter am I using for this demo : http://php.net/manual/en/filter.filters.sanitize.php
So your input assignment to variables will look like the following,
$FirstName = filter_input(INPUT_POST, $_POST["FirstName"], FILTER_SANITIZE_STRING);
$LastName = filter_input(INPUT_POST, $_POST["LastName"], FILTER_SANITIZE_STRING);
And i gather you might be using NetBeans for PHP development (https://blogs.oracle.com/netbeansphp/entry/improve_your_code_with_new). This has the same warning as you've mentioned. But I'm not quite sure you will see the warning around other IDE's.

Related

Duplicate insert into MySQL

Im using the following code and testing it using WAMP on my localhost.
It works fine and inserts the data however for some reason it creates duplicate row.
Is there are reason why it makes it appear twice?
<?php
require "conn.php";
$name =$_POST["name"];
$surname = $_POST["surname"];
$age = $_POST["age"];
$username = $_POST["username"];
$userpass = $_POST["password"];
$mysql_qry = "insert into employee_data(name, surname, age, username, password) values ('$name', '$surname', '$age', '$username', '$userpass')";
$result = mysqli_query($conn, $mysql_qry);
if ($conn->query($mysql_qry) === TRUE){
echo "insert success";
}
else{
echo "Error:" .$mysql_qry . "<br> " . $conn->error;
}
$conn->close();
?>
Thank you
YES, you run the query TWICE, see comments in the code
<?php
require "conn.php";
$name =$_POST["name"];
$surname = $_POST["surname"];
$age = $_POST["age"];
$username = $_POST["username"];
$userpass = $_POST["password"];
$mysql_qry = "insert into employee_data
(name, surname, age, username, password)
values ('$name', '$surname', '$age', '$username', '$userpass')";
//ONCE HERE
$result = mysqli_query($conn, $mysql_qry);
//AND AGAIN HERE
if ($conn->query($mysql_qry) === TRUE){
echo "insert success";
}
else{
echo "Error:" .$mysql_qry . "<br> " . $conn->error;
}
$conn->close();
?>
ALSO Your script is wide open to SQL Injection Attack
Even if you are escaping inputs, its not safe!
Use prepared parameterized statements in either the MYSQLI_ or PDO API's
Coded using prepared and bound queries
<?php
require "conn.php";
$sql = "insert into employee_data
(name, surname, age, username, password)
values (?,?,?,?,?)";
$stmt = $conn-prepare($sql);
$stmt->bind_param('sssss', $_POST["name"],
$_POST["surname"];
$_POST["username"];
$_POST["password"];
if ( $stmt->execute() ){
echo "insert success";
}else{
echo "Error:" .$mysql_qry . "<br> " . $conn->error;
}
$conn->close();
?>
Now I have to mention how bad it is to use Plain Text Password.
PHP provides password_hash()
and password_verify() please use them.
And here are some good ideas about passwords

Editing user profile: How to avoid user from entering duplicate values?

I'm a newbie in PHP. I wanted the display warning messages user to avoid entering duplicate values such as username, email and telephone number.
For example, user wants to change their username. When the user submit the form after editing their username, a warning message is display saying that username has already been taken or already exists.
<?php
error_reporting(E_ALL ^ E_NOTICE);
session_start();
include("../config.php");
include("../errors.php");
include("../success.php");
$errors = array();
$successes = array();
if ($_SESSION["uName"]){
if ($_SESSION["uType"] != "admin") {
header("location:../user/dashboard_user.php");
} else if ($_SESSION["uType"] == "admin"){
if(isset($_POST["update"])) {
$fname = $_POST["fname"];
$telno = $_POST["telno"];
$uname = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$password = md5($password);
$sql = "UPDATE users SET fullname = '$fname', telno = '$telno', username = '$uname', email = '$email', password = '$password' WHERE id = '".$_SESSION['uId']."'";
if (mysqli_query($con, $sql)) {
array_push($successes, "Update Success!");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
?>
What is the correct way to use the SELECT statement in the code to get the expected results?
You should really handle the issue in the database:
create unique index idx_username on users(username);
Then in your code do what you do and then simply:
define('MYSQL_UNIQUE_CONSTRAINT_VIOLATION', 1062);
if (mysqli_query($con, $sql)) {
array_push($successes, "Update Success!");
} elsif (mysql_errno() == MYSQL_UNIQUE_CONSTRAINT_VIOLATION ) {
echo "Error: username $username is already taken";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
This code is very crude of course, but it gives you the idea. If your code inside the class, then use const instead of define.
Also, your code is very much liable to SQL injection. Use parametrised query instead of using variable inside the sql string.

$_POST method showing undefine variable

How to solve this i don't add data using by $_Post Method, but without $_POST method showing undefine variable?
if (isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['age'])){
//Getting values
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$age = $_POST['age'];
//Creating an sql query
$sql = "INSERT INTO info (firstname,lastname,age) VALUES ('$firstname','$lastname','$age')";
//Importing our db connection script
require_once('connect.php');
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Employee Added Successfully';
}else{
echo 'Could Not Add Employee';
}
//Closing the database
mysqli_close($con);
}
You need to define your variables to something if $_POST is not set.
So code would look something like this:
$firstname = isset($_POST['firstname']) ? $_POST['firstname'] ? "";
$lastname = isset($_POST['lastname']) ? $_POST['lastname'] : "";
$age = isset($_POST['age']) ? $_POST['age'] : "";
//if isset $_POST['age'] then assign it to $_POST['age'] else assign it to ""
if (isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['age'])){
//Creating an sql query
$sql = "INSERT INTO info (firstname,lastname,age) VALUES ('$firstname','$lastname','$age')";
//Importing our db connection script
require_once('connect.php');
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Employee Added Successfully';
}else{
echo 'Could Not Add Employee';
}
//Closing the database
mysqli_close($con);
}
Bonus:
You code can be easily injected. Use prepared statements to avoid this.
$sql = "INSERT INTO info (firstname,lastname,age) VALUES (?,?,?)"; // question marks are placeholders to bind values to
$stmt = $con->prepare($sql); // prepare query
$stmt->bind_param("sss", $firstname, $lastname, $age); // bind values to your query
if($stmt->execute()){ // if success
echo 'Employee Added Successfully';
}else{
echo 'Could Not Add Employee';
}
You can learn more about it here
Try changing this one:
$sql = "INSERT INTO info (firstname,lastname,age) VALUES ('$firstname','$lastname','$age')";
To this one:
$sql = "INSERT INTO info (firstname,lastname,age) VALUES ('".$firstname."','".$lastname."','."$age."')";

PHP Form to SQL Error

I am trying to write from form to my SQL database. This is all local through WAMP, if that makes a difference.
The error I am receiving is as follows:
Error: INSERT INTO customers (yard, full_address, business_name, business_status, first_name, last_name, landline_number, mobile_number, email_address) VALUES ('Dominic', '123 Fake Street', 'Dom's Business Name', '', 'Dominic', 'Fichera', 0123456789', '0123456789', '')
Erreur de syntaxe pr�s de 's Business Name', '', 'Dominic', 'Fichera', 0123456789', '0123456789', '')' � la ligne 2
I've also uploaded an image here: http://s7.postimg.org/ecqci36nv/error_snippet.png
I am unsure if this error refers to an issue within my code, an issue with the way I've setup my SQL table or something completely different.
Here is the main chunk of my code where all of the action happens:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "login";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["yard"])) {
$yard_error = "Yard is required";
} else {
$yard = test_input($_POST["yard"]);
}
if (empty($_POST["full_address"])) {
$full_address_error = "Address is required";
} else {
$full_address = test_input($_POST["full_address"]);
}
if (empty($_POST["first_name"])) {
$first_name_error = "First name is required";
} else {
$first_name = test_input($_POST["first_name"]);
}
if (empty($_POST["last_name"])) {
$last_name_error = "Last name is required";
} else {
$last_name = test_input($_POST["last_name"]);
}
if ($_POST["business_status"] = "") {
$business_status_error = "Business status is required";
} else {
$business_status = test_input($_POST["business_status"]);
}
$business_name = $_POST["business_name"];
$landline_number = $_POST["landline_number"];
$mobile_number = $_POST["mobile_number"];
$email_address = $_POST["email_address"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customers (yard, full_address, business_name, business_status, first_name, last_name, landline_number, mobile_number, email_address)
VALUES ('$yard', '$full_address', '$business_name', '$business_status', '$first_name', '$last_name', $landline_number', '$mobile_number', '$business_status')";
if ($conn->query($sql) === TRUE) {
$yard_confirmation = $yard . "successfully saved.";
} else {
$yard_confirmation = "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I would recommend something like this:
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
And:
$errors = array();
($_POST["business_name"]) ? $business_name = test_input($_POST["business_name"]) : $errors[] = "Business name is required!";
(Doing the same line for each $_POST variable)
Basically it's an if/else statement in one line (reduces clutter). If there is data in $_POST["business_name"], then $business_name will have the value parsed through test_input - if it has no value, then the errors array gets a new value!
After checking all the values and parsing them, you can do:
if(empty($errors)) {
//If there are no errors, continue inserting
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customers (yard, full_address, business_name, business_status, first_name, last_name, landline_number, mobile_number, email_address) VALUES ('$yard', '$full_address', '$business_name', '$business_status', '$first_name', '$last_name', $landline_number', '$mobile_number', '$business_status')";
if ($conn->query($sql) === TRUE) {
$yard_confirmation = $yard . "successfully saved.";
} else {
$yard_confirmation = "Error: " . $sql . "<br>" . $conn->error;
}
} else {
foreach($errors as $error) {
echo $error."<br />";
}
}
I would definitely recommend using PDO though, it allows you to bind values to queries.
'Dom's Business Name' is invalid, you'll need to escape it:
'Dom\'s Business Name'
Please consider using prepared statements.
You SQL-injected your own database lol. Though you do have a function for adding slashes called test_input() you forgot to use it in some places. Change these:
$business_name = $_POST["business_name"];
$landline_number = $_POST["landline_number"];
$mobile_number = $_POST["mobile_number"];
$email_address = $_POST["email_address"];
To these:
$business_name = test_input($_POST["business_name"]);
$landline_number = test_input($_POST["landline_number"]);
$mobile_number = test_input($_POST["mobile_number"]);
$email_address = test_input($_POST["email_address"]);
I'd encourage reading this.
Consider this php function http://php.net/manual/en/mysqli.real-escape-string.php and prepare your string before saving into database.
As others said, the problem is with apostrophe in the business name, but it could be with other characters that need to be escaped. And worst, your code is a candidate to be a victim of SQL injection.
For a solution, line:
$business_name = $_POST["business_name"];
should be changed by :
if ($_POST["business_name"] = "") {
$business_name_error = "Business name is required";
} else {
$business_name = test_input($_POST["business_name"]);
}
And the following three lines should be change in the same way.
In your query, your listed values, you're missing a single quote before "$landline_number".
Also, since you're not using prepared statements, I HIGHLY recommend you use mysqli_real_escape_string() for all user submitted variables to prevent injection. For example:
$variable = mysqli_real_escape_string($conn, $_POST['variable']);

why is insert into not working

I made this code
<?php
mysql_connect ("localhost","root","root");
mysql_select_db ("new");
$newusername=$_POST ['newusername'];
$newpassword=$_POST ['newpassword'];
$submit=$_POST ['submit'];
if($submit) {
$newaccount= "INSERT INTO users (name,password) VALUES ("$newusername","$newpassword")";
$result=mysql_query($newaccount);
if ($result) {
print "account has been created"."<meta http-equiv="refresh" content="5;login.php">";
}
else {
echo " The account is already exist";
}
}
?>
but it says error on line 8 which is " insert into" line
There is a problem with double quotes. You can add concatenation:
$newaccount = "INSERT INTO users (name,password) VALUES ('" . $newusername . "','" . $newpassword . "')";
P.S. Don't use mysql_* functions (mysql extension is deprecated), use mysqli_* instead.
You used wrong quoting:
$newaccount= "INSERT INTO users (name,password) VALUES ('$newusername','$newpassword')";
Sorting out the quotes and using mysql_real_escape_string to sanitise the input (and prevent an easy SQL injection attack):-
<?php
mysql_connect("localhost","root","root");
mysql_select_db ("new");
$newusername = mysql_real_escape_string($_POST['newusername']);
$newpassword = mysql_real_escape_string($_POST['newpassword']);
$submit = $_POST['submit'];
if($submit)
{
$newaccount = "INSERT INTO users (name, password) VALUES ('$newusername', '$newpassword')";
$result = mysql_query($newaccount);
if ($result)
{
print "account has been created"."<meta http-equiv='refresh' content='5;login.php'>";
}
else
{
echo " The account is already exist";
}
}
?>
$newaccount= "INSERT INTO users (name,password) VALUES ("$newusername","$newpassword")";
TO
$newaccount= "INSERT INTO users (name,password) VALUES ('".$newusername."','".$newpassword."')";
OR TO
$newaccount= "INSERT INTO users (name,password) VALUES ('$newusername','$newpassword')";
<?php
mysql_connect ("localhost","root","root");
mysql_select_db ("new");
$newusername=$_POST ['newusername'];
$newpassword=$_POST ['newpassword'];
$submit=$_POST ['submit'];
if($submit) {
$newaccount= "INSERT INTO users (name,password) VALUES ('".$newusername."', '".$newpassword."')";
$result=mysql_query($newaccount);
if ($result) {
print "account has been created"."<meta http-equiv="refresh" content="5;login.php">";
}
else {
echo " The account is already exist";
}
}
?>

Categories