Is this code vulnerable to sql injection? - php

Is this code prone to SQL Injection? Can you suggest something to improve the security? Is it right to use mysqli_real_escape_string? And do you think it's alright to use this for project?
<?php
require 'db.php';
if(isset($_POST['pawnshopName'])&&isset($_POST['street'])&&isset($_POST['barangay'])&&isset($_POST['city'])&&isset($_POST['dtiPermitNo'])&&isset($_POST['mayorPermitNo'])&&isset($_POST['firstName'])&&isset($_POST['lastName'])&&isset($_POST['middleName'])&&isset($_POST['contactNumber'])&&isset($_POST['email'])&&isset($_POST['password'])&&isset($_POST['confirmPassword']))
{
$options = ['cost' => 11, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),];
$pawnshopName = mysqli_real_escape_string($connection, $_POST['pawnshopName']);
$street = mysqli_real_escape_string($connection, $_POST['street']);
$barangay = mysqli_real_escape_string($connection, $_POST['barangay']);
$city = mysqli_real_escape_string($connection, $_POST['city']);
$dtiPermitNo = mysqli_real_escape_string($connection, $_POST['dtiPermitNo']);
$mayorPermitNo = mysqli_real_escape_string($connection, $_POST['mayorPermitNo']);
$firstName = mysqli_real_escape_string($connection, $_POST['firstName']);
$lastName = mysqli_real_escape_string($connection, $_POST['lastName']);
$middleName = mysqli_real_escape_string($connection, $_POST['middleName']);
$contactNumber = mysqli_real_escape_string($connection, $_POST['contactNumber']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password = mysqli_real_escape_string($connection, password_hash($_POST['password'], PASSWORD_BCRYPT, $options));
$confirmPassword = mysqli_real_escape_string($connection, $_POST['confirmPassword']);
if(password_verify($confirmPassword,$password))
{
echo 'Password Match';
}else
{
echo 'Password mismatch';
}
$sql = "INSERT INTO pawnshop ".
"(Pawnshop_ID, Pawnshop_Name, Street, Barangay, City, DTI_Permit_No, Mayor_Permit_No, Firstname, Middlename, Lastname, Contact_Number, Email_Address, Password) ".
"VALUES ".
"('','".$pawnshopName."', '".$street."', '".$barangay."', '".$city."', '".$dtiPermitNo."', '".$mayorPermitNo."', '".$firstName."', '".$lastName."', '".$middleName."', '".$contactNumber."', '".$email."', '".$password."' )";
mysqli_query($connection, $sql);
mysqli_close($connection);
}
?>

No, you must use prepare method. Then on every place where you want to add a value place a ?. Than you must use the bind_param method. Finally, you can execute it and get the results whit get_results. An example:
$stmt = $connection->prepare("INSERT INTO Customers (CustomerName, Address, CityID) VALUES (?, ?, ?)");
$stmt->bindParam('ssi', $name, $address, $cityId);
$stmt->execute();
$results = $stmt->get_results();
The 'ssi' are corresponding variable the types of the attributes.
i are integers
d are doubles
s are strings
b is a blob and will be sent in packets
My resources are: w3schools and php.net

Related

Brand new to coding: Fatal error: Call to a member function execute() on boolean

I am assuming by "Boolean" that it is coming out as "false"...
Can anyone explain what could be wrong here?
My code may be flawed altogether, but I would like some constructive criticism.
<?php
if ($_SERVER['REQUEST_METHOD'] = "POST") {
include("mytableconn.php");
$firstName = mysqli_real_escape_string($conn, trim($_POST['firstn']));
$lastName = mysqli_real_escape_string($conn, trim($_POST['lastn']));
$email = mysqli_real_escape_string($conn, trim($_POST['uemail']));
$password = mysqli_real_escape_string($conn, trim($_POST ['userpasscode']));
$cryption = "$2y$10$";
$chars = "thisisseriouslyfucked1";
$crypchar = $cryption . $chars;
$crypass = crypt($password, $crypchar);
$user = $conn->prepare("
INSERT INTO mytable(first_name, last_name, e_mail, pass_word)
VALUES(?, ?, ?, ?)
");
$user = $user->bind_param("ssss", $firstName, $lastName, $email, $crypass);
$user->execute();
$user->close();
$conn->close();
}else {
echo("Sorry, an unexpected error occurred");
}
?>
When you prepare the sql you assign it as a variable - you should then test that variable before proceeding to check that the sql is valid.
mysqli_prepare() returns a statement object or FALSE if an error
occurred
<?php
if ( $_SERVER['REQUEST_METHOD'] = "POST" ) {
include("mytableconn.php");
$firstName = mysqli_real_escape_string($conn, trim($_POST['firstn']));
$lastName = mysqli_real_escape_string($conn, trim($_POST['lastn']));
$email = mysqli_real_escape_string($conn, trim($_POST['uemail']));
$password = mysqli_real_escape_string($conn, trim($_POST['userpasscode']));
$cryption = "$2y$10$";
$chars = "thisisseriouslyfucked1";
$crypchar = $cryption . $chars;
$crypass = crypt( $password, $crypchar );
$stmt = $conn->prepare("insert into `mytable` ( `first_name`, `last_name`, `e_mail`, `pass_word` ) values (?, ?, ?, ?)");
if( $stmt ){
$stmt->bind_param("ssss", $firstName, $lastName, $email, $crypass);
$stmt->execute();
$stmt->close();
}
$conn->close();
}else {
echo("Sorry, an unexpected error occurred");
}
?>

ERROR WHILE INSERTING USING MYSQLI

i'm new to this PHP please help me here i'm unable to insert values into table.
But if i gave values directly to insert command in place of variables it works.
<?php
include ("db.php");
$msg = "";
if(isset($_POST["submit"]))
{
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$name = mysqli_real_escape_string($db, $name);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$sql="SELECT email FROM users2 WHERE email='$email'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
$msg = "Sorry...This email already exist...";
}
else
{
$query = mysqli_query($db, "INSERT INTO users2 (name, email, password)VALUES ('$name', '$email', '$password')");
if($query)
{
$msg = "Thank You! you are now registered.";
}
}
}
?>
$sql = "INSERT INTO users2 (name, email, password) VALUES (?,?,?)";
if (!$stmt = $db->prepare($sql)) {
die($db->error);
}
$stmt->bind_param("sss", $name, $email, $password);
if (!$stmt->execute()) {
die($stmt->error);
}
I don't know what is the problem in my above question but
i used the above query instead of the one i used the in question and Boom it is a success.
if any one of you know whats the problem in the question please let me know.
You have to concat the variable in string of insert not just put as variable
$query = mysqli_query($db,"INSERT INTO users2 (name, email, password)VALUES ('".$name."', '".$email."', '".$password."')")
or
$query = mysqli_query($db,"INSERT INTO users2 (name, email, password)VALUES ('{$name}', '{$email}', '{$password}')")
You should use prepare statement for this mysql_real_escape_string-versus-Prepared-Statements
Never use md5() is-md5-considered-insecure
Prefer password_hash() or password_verify() Manuel
``

"No data supplied for parameters in prepared statement"

So I am reworking a script to include prepared statements. It was working fine before, but now I am getting "No data supplied for parameters in prepared statement" when the script runs. What is the issue here?
<?php
require_once("models/config.php");
$firstname = htmlspecialchars(trim($_POST['firstname']));
$firstname = mysqli_real_escape_string($mysqli, $firstname);
$surname = htmlspecialchars(trim($_POST['surname']));
$surname = mysqli_real_escape_string($mysqli, $surname);
$address = htmlspecialchars(trim($_POST['address']));
$address = mysqli_real_escape_string($mysqli, $address);
$gender = htmlspecialchars(trim($_POST['gender']));
$gender = mysqli_real_escape_string($mysqli, $gender);
$city = htmlspecialchars(trim($_POST['city']));
$city = mysqli_real_escape_string($mysqli, $city);
$province = htmlspecialchars(trim($_POST['province']));
$province = mysqli_real_escape_string($mysqli, $province);
$phone = htmlspecialchars(trim($_POST['phone']));
$phone = mysqli_real_escape_string($mysqli, $phone);
$secondphone = htmlspecialchars(trim($_POST['secondphone']));
$secondphone = mysqli_real_escape_string($mysqli, $secondphone);
$postalcode = htmlspecialchars(trim($_POST['postalcode']));
$postalcode = mysqli_real_escape_string($mysqli, $postalcode);
$email = htmlspecialchars(trim($_POST['email']));
$email = mysqli_real_escape_string($mysqli, $email);
$organization = htmlspecialchars(trim($_POST['organization']));
$organization = mysqli_real_escape_string($mysqli, $organization);
$inriding = htmlspecialchars(trim($_POST['inriding']));
$inriding = mysqli_real_escape_string($mysqli, $inriding);
$ethnicity = htmlspecialchars(trim($_POST['ethnicity']));
$ethnicity = mysqli_real_escape_string($mysqli, $ethnicity);
$senior = htmlspecialchars(trim($_POST['senior']));
$senior = mysqli_real_escape_string($mysqli, $senior);
$student = htmlspecialchars(trim($_POST['student']));
$student = mysqli_real_escape_string($mysqli, $student);
$order= "INSERT INTO persons (firstname, surname, address, gender, city, province, postalcode, phone, secondphone, email, organization, inriding, ethnicity, senior, student_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($mysqli, $order);
mysqli_stmt_bind_param($stmt, "sssd", $firstname, $surname, $address, $gender, $city, $province, $postalcode, $phone, $secondphone, $email, $organization, $inriding, $ethnicity, $senior, $student);
mysqli_stmt_execute($stmt);
echo $stmt->error;
$result = mysqli_query($mysqli,$stmt);
if ($result === false) {
echo "Error entering data! <BR>";
echo mysqli_error($mysqli);
} else {
echo "User $firstname added <BR>";
}
?>
Thanks in advance.
You have only bound four arguments, by the control string "sssd", but you have many parameters. When binding variables with mysqli, you need one character for each parameter, for example:
mysqli_stmt_bind_param($stmt, "sssdsssssssssdd", $firstname, $surname, $address,
$gender, $city, $province, $postalcode, $phone, $secondphone, $email,
$organization, $inriding, $ethnicity, $senior, $student);
(I'm assuming senior and student are integers, and need the "d" code.)
You don't need to treat any of your variables with mysqli_real_escape_string() -- that's the point of using parameters. If you do escaping as well, you'll get literal backslash characters in your data in the database.
And you never need to use htmlspecialchars() in any case - you would use that when outputting to HTML, not when inserting to the database. You're going to get literal sequences like & in your data in the database.
Re your next error:
"Catchable fatal error: Object of class mysqli_stmt could not be converted to string in..."
This is caused by the following:
$result = mysqli_query($mysqli,$stmt);
That function expects the second argument to be a string, a new SQL query. But you've already prepared that query, so you need the following:
$result = mysqli_stmt_execute($stmt);

How can I place the SELECTED elements from database into a variable

How can I place these elements into a variable?
$user_information = $connect->prepare("SELECT email, gender, firstname, middlename, FROM members");
like
$firstname = 'firstname';
$gender = 'gender';
$email = 'email';
how can I do this
Thanks in advance
If you are using PDO
$user_information ->execute();
$result = $user_information->fetch(PDO::FETCH_ASSOC);
$firstname = $result['firstname'];
$gender = $result['gender'];
$email = $result['email'];
if you are using mysqli
$user_information->execute();
$user_information->bind_result($firstname, $gender, $email);
$user_information->fetch();
printf("%s, %s, %s\n", $firstname, $gender, $email);
$user_information ->close();
If you are using PHP and PDO, you can use the in the fetch method to get an object using PDO::FETCH_OBJ. http://de3.php.net/manual/en/pdostatement.fetch.php
$result = $sth->fetch(PDO::FETCH_OBJ);
print $result->NAME;
list($email, $gender, $firstname, $middlename) = $user_information;
For more info check LIST function # PHP docs.
if it returns an object you can get it like;
$firstname = $user_information->firstname;
$gender = $user_information->gender;
$email = $user_information->email;
or if it returns an array;
$firstname = $user_information["firstname"];
$gender = $user_information["gender"];
$email = $user_information["email"];

PHP is inserting two duplicate rows in MYSQL database

I am having trouble with PHP and MYSQL. I have an HTML form which when submitted runs the following PHP script.The problem is that the following PHP code is inserting the data into the database twice. I think it is something to do with the following PHP and not the database:
<?php
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$display_name = $_POST['displayname'];
$email = $_POST['email'];
$password = $_POST['password'];
$add_line1 = $_POST['addline1'];
$add_line2 = $_POST['addline2'];
$city = $_POST['city'];
$county = $_POST['county'];
$postcode = $_POST['postcode'];
$sql = "INSERT INTO members (memberID,
memberPassword,
memberFirstName,
memberLastName,
memberAddressLine1,
memberAddressLine2,
memberCity,
memberCounty,
memberPostcode,
memberDisplayName)
VALUES ('$email',
'$password', '$first_name', '$last_name',
'$add_line1', '$add_line2','$city',
'$county', '$postcode', '$display_name')";
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
mysqli_query($conn,$sql);
echo 'Guest Added';
mysqli_close($conn);
?>
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
mysqli_query($conn,$sql);
You have mysqli_query($conn,$sql); in your code twice. Once in the if(), and once outside. Each of these will insert into your database.
The point to note here is that the mysqli_query inside the if is evaluated - that is, it is run and the if statement executes on the result of the function call. Thus, you do not need to call it again.
Tushar pointed out the twin mysqli queries and he is right, besides that, the code as is now will cause you security troubles since it allows sql injection...
Please modify your code as follows:
$first_name = mysqli_escape_string($conn, $_POST['firstname']);
$last_name = mysqli_escape_string($conn, $_POST['lastname']);
$display_name = mysqli_escape_string($conn, $_POST['displayname']);
$email = mysqli_escape_string($conn, $_POST['email']);
$password = mysqli_escape_string($conn, $_POST['password']);
$add_line1 = mysqli_escape_string($conn, $_POST['addline1']);
$add_line2 = mysqli_escape_string($conn, $_POST['addline2']);
$city = mysqli_escape_string($conn, $_POST['city']);
$county = mysqli_escape_string($conn, $_POST['county']);
$postcode = mysqli_escape_string($conn, $_POST['postcode']);

Categories