mysqli real escape string issues - php

How can I use mysqli_real_escape_string in my script to prevent SQL injection. I was working on some code and asking some questions here and I was advised to use mysqli_real_escape_string instead of mysql_real_escape_string, the problem is my code does not make a connection until after the variables I want to secure. It was suggested that I should used prepared statements instead but after some searching http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php I feel more confused. Right now the code if doing exactly what it is not supposed to do, it is inserting empty values/rows into my table, which from my reading is probably because of the use of mysqli_real_escaape_string
Any thoughts or help is appreciated, I am so frustrated and confused but still trying to learn. Here is the code:
<?php
//Form fields passed to variables
$manu = mysqli_real_escape_string($_POST['inputManu']);
$model = mysqli_real_escape_string($_POST['inputModel']);
$desc = mysqli_real_escape_string($_POST['inputDesc']);
//Connect to database using $conn
include ('connection.php');
//Insert record into table
$sql = "INSERT INTO gear (`id`,`manu`,`model`,`desc`)
VALUES (NULL,'$manu','$model','$desc')";
//Check for empty fields
if (isset($_POST['submit']))
{
foreach($_POST as $val)
{
if(trim($val) == '' || empty($val))
{
die('Error: ' . mysqli_error());
echo "Please complete all form fields!";
echo "<meta http-equiv='Refresh' content='3; URL=../add.php'>";
}
}
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
else
{
//echo "1 record added";
echo "Success, You added the ".$manu." ".$model."";
echo "<meta http-equiv='Refresh' content='3; URL=../index.php'>";
}
}
else
{
echo "some error";
}
mysqli_close($conn);
?>

<?php
//Connect to database using $conn
include ('connection.php');
//Form fields passed to variables
$manu = mysqli_real_escape_string($conn, $_POST['inputManu']);
$model = mysqli_real_escape_string($conn, $_POST['inputModel']);
$desc = mysqli_real_escape_string($conn, $_POST['inputDesc']);

Hope Below code will help you.
<?php
//Connect to database using $conn
/*in connection.php
$link = mysqli_connect("localhost", "root", "", "test");
*/
include ('connection.php');
//Check for empty fields
if (isset($_POST['submit']))
{
//Form fields passed to variables
$manu = mysqli_real_escape_string($link,$_POST['inputManu']);
$model = mysqli_real_escape_string($link,$_POST['inputModel']);
$desc = mysqli_real_escape_string($link,$_POST['inputDesc']);
if($manu!='' && $model!="" && $desc!="")
{
//Insert record into table
$sql = "INSERT INTO gear (`id`,`manu`,`model`,`desc`)
VALUES (NULL,'$manu','$model','$desc')";
$r=mysqli_query($link,$sql) ;
//echo "1 record added";
if($r)
{
echo "Success, You added the ".$manu." ".$model."";
// echo "<meta http-equiv='Refresh' content='3; URL=../index.php'>";
}
}
else
{
echo "Please complete all form fields!";
}
}
?>

Related

PHP loop back through an if statement after SQL update

I'm trying to figure out a way to loop back through an if statement if the user fills in the the missing fields that updates the database? I was thinking of setting the header location back on it's self but I don't think that will work. Any suggestions please?
<?php
if(!isset($_SESSION)) { session_start(); }
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: ../login.php");
exit;
}
require_once "../config.php";
$key = $_SESSION["key"];
if (empty($key)) {
$example = $website = "";
$example_err = $website_err = "";
$conn = $link;
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty(trim($_POST["example"]))){
$example_err = "Please enter a valid key.";
} else{
$example = trim($_POST["example"]);
}
if(empty(trim($_POST["website"]))){
$website_err = "Please enter website URL.";
} else{
$website = trim($_POST["website"]);
}
if(empty($website_err) && empty($example_err)){
$stmt = $conn->prepare("UPDATE users SET website=?, example=? WHERE id=?");
$stmt->bind_param("sss", $param_website, $param_example, $param_id);
$param_website = $website;
$param_example = $example;
$param_id = $_SESSION["id"];
$stmt->execute();
$stmt->close();
$conn->close();
if($stmt){
*DO SOMETHING HERE*
} else{
echo "Something went wrong. Please try again later.";
}
}
}
} else{
echo "Success!";
}?>
If the form is on the same page, please set the form action as
<form action="" method="post">
and if not in the same page, please replace the following:
*DO SOMETHING HERE*
with
header("Location:".$_SERVER['HTTP_REFERER']);

Can't enter data in to the database using mysql

This is the php file that going to enter data into the mysql database. When I run it, browser shows "connected successfully selected successfully Executing inside fileNot Inserted". but it's not going to show any errors. And data is not insert in to the database. What's wrong with this code.
*dbConnection.php
<?php
$dbhost="localhost";
$dbuser="root";
$dbPassword="123";
$database="medicalcenter";
$connection = mysqli_connect($dbhost,$dbuser,$dbPassword) or die("unable to connect");
if($connection){
echo 'connected successfully ';
}else{
echo 'not connected';
}
$dbSelect=mysqli_select_db($connection,$database);
if($dbSelect){
echo 'selected successfully';
}else{
echo 'not selected';
}
?>
*insert.php
<?php
include 'dbConnection.php';
echo "Executing inside file";
$firstName = filter_input(INPUT_POST,'firstname');
$secondName = filter_input(INPUT_POST,'lastname');
$address1 =filter_input(INPUT_POST,'address1');
$address2 =filter_input(INPUT_POST,'address2');
$city =filter_input(INPUT_POST,'city');
$email =filter_input(INPUT_POST,'email');
$age =filter_input(INPUT_POST,'age');
$gender =filter_input(INPUT_POST,'gender');
$sql= "INSERT INTO patient(FirstName,LastName,AddressLine1,AddressLine2,City,Email,Age,Gender) VALUES ('$firstName','$secondName','$address1','$address2','$city',$email','$age','$gender')";
if(mysqli_query($connection,$sql)){
echo 'Inserted successfully';
}else{
echo 'Not Inserted';
}
mysqli_close($connection);
?>
$sql= "INSERT INTO patient(FirstName,LastName,AddressLine1,AddressLine2,City,Email,Age,Gender) VALUES ('$firstName','$secondName','$address1','$address2','$city',$email','$age','$gender')";
check your above line you have forgot ' before email please check with below line. may it helps you.
$sql= "INSERT INTO patient(FirstName,LastName,AddressLine1,AddressLine2,City,Email,Age,Gender) VALUES ('$firstName','$secondName','$address1','$address2','$city','$email','$age','$gender')";

Empty fields can get inserted into my database

I have the following code. I try to use my Submit button to insert the code into the database, but every time I use it and refresh the browser, empty fields get inserted into the database.
<?php
$servername = "localhost";
$username = "root";
$password = "";
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!". $cn->connect_error;
}
// once the button is clicked
if (isset($_POST['submitForm'])) {
//the values in the boxes
$name = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$confpass = $_POST['confpass'];
$interest = $_POST['interest'];
$info = $_POST['info'];
//echo "connection successfully";
//Insert into table
$sql = "INSERT INTO miltb(name, email, password, interest, info, productorder) VALUES('$name', '$email', '$password', '$interest', '$info', 'none' )";
}
if ($cn->query($sql) == true) {
?><script>alert ("INSERTED SUCCESSFULLY!");</script><?php
} else {
echo "error: " . $sql . "\n" . $cn->error;
}
$cn->close();
?>
How would I fix it?
The reason empty fields get inserted in the database it's because you are not checking for empty fields, you need to check those empty fields first then if empty fields exists do not insert.
Well man there's a lot that you need to learn, you need to learn about
1.SQL Injections
2.mysqli prepared or pdo prepared statements.
3.Password hashing
Filter ,sanitize and validate user inputs
Never trust an input from the user, you must always treat a user input as if it comes from a dangerous hacker.
Then you code with prepared statements should look like this :
<?php
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!" . $cn->connect_error;
}
$error = "";
// once the button is clicked
if (isset($_POST['submitForm'])) {
// check for empty fiels
if (empty($_POST['fname'])) {
echo "Enter your name";
$error++;
} else {
$name = userInput($_POST['fname']);
}
if (isset($_POST['email'])) {
echo "enter email";
$error++;
} else {
$email = userInput($_POST['email']);
// validate email
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
echo "enter a valid email";
$error++;
}
}
if (empty($_POST['password'])) {
echo "enter password";
$error++;
} else {
$password = userInput($_POST['password']);
$hash = password_hash($password, PASSWORS_DEFAULT); //hash the password
}
if (!empty($_POST['confpass']) && $_POST['confpass'] !== $_POST['password']) { //password confirmation
echo "passwords does not match";
$error++;
}
if (empty($_POST['interest'])) {
echo "enter interests";
$error++;
} else {
$interest = userInput($_POST['interest']);
}
if (empty($_POST['info'])) {
echo "enter info";
$error++;
} else {
$info = userInput($_POST['info']);
}
if ($error > 0) { // if we have errors don't insert to db
echo "you have " . $error . " error(s) on your form plz fix them";
} else { // no errors lets insert
// prepare and bind
$sql = $cn->prepare("INSERT INTO miltb(name, email, password, interest, info) VALUES (?, ?, ?,?,?)");
$sql->bind_param("sssss", $name, $email, $hash, $interest, $info);
if ($sql->execute()) {
echo "INSERTED SUCCESSFULLY!";
} else {
echo "could not insert ";
}
}
$sql->close();
$cn->close();
}
function userInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Hope this will help and you will learn a thing or two, I stand to be corrected where I'm wrong
Use something like this to be sure values are inserted:
$name = isset($_POST['fname']) ? strval($_POST['fname']) : null;
if (empty($name)){
echo "Name can't be empty!";
exit();
}
Note: beware of SQL Injection. Using php function strval() is the least possible secutiry, but atleast use that, if nothing more.

Validating form then submitting to database with php

I've been reluctant to come back to Stackoverflow to ask this question. It's definitely been asked many times over, but every answer hasn't been able to fix the problem. I've attempted the Header() fix: https://stackoverflow.com/a/18820079/3831297 to no avail and now I have been trying to instead just validate and submit from the same page.
When I was using the Header redirect nothing would happen, no redirect to the next page while also not giving any errors for a reason. Which leaves me with the method below.. A mess of code that I've spent 60+ hours on trying to get to work from answers found on here as well as other websites.
What I've been trying to do with this version is validate with:
if(empty()) {
display error
}else{
variable = true
if(variable = true){
post to database
}
I apologize for the repeated question as well as for my complete lack of knowledge. I am learning as I go with these hands-on projects.
<?php
if (mysqli_connect_errno()) {
echo "Connection to the database failed! Submitting a story will not work! Try again in a few minutes!" . mysqli_connect_error();
}else{
echo "<br>";
echo "<h4>" . "Database connected successfully... It is safe to submit a story!" . "</h4>";
}
$TitleErr = $StoryErr = $AuthorErr = $DateErr = "";
$Title = $Story = $Author = $Date = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Title"])) {
$TitleErr = "Title is required!";
}else{
$valid1 == true;
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Story"])) {
$StoryErr = "Story is required!";
}else{
$valid2 == true;
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Author"])) {
$AuthorErr = "Author is required!";
}else{
$valid3 == true;
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["Date"])) {
$DateErr = "Date is required!";
}else{
$valid4 == true;
}
}
if ($valid1 = $valid2 = $valid3 = $valid4 = true) {
$Title = mysqli_real_escape_string($con, $_POST['Title']);
$Date = mysqli_real_escape_string($con, $_POST['Date']);
$Author = mysqli_real_escape_string($con, $_POST['Author']);
$Story = mysqli_real_escape_string($con, $_POST['Story']);
$sql="INSERT INTO Moderate (Title, Story, Author, Date)
VALUES ('$Title', '$Story', '$Author', '$Date')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}else{
echo "<br>";
echo "Story submitted for moderation!";
}
}
mysqli_close($con);
//Insert into database
//$sql="INSERT INTO Moderate (Title, Story, Author, Date)
//VALUES ('$Title', '$Story', '$Author', '$Date')";
?>
<h2>Submit News</h2>
<?php// echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<span class="error">* <?php echo $TitleErr;?></span>
Title: <input type="text" name="Title">
<span class="error">* <?php echo $AuthorErr;?></span>
Author: <input type="text" name="Author">
<span class="error">* <?php echo $DateErr;?></span>
Date: <input type="date" name="Date">
<input type="submit"><br>
<span class="error">* <?php echo $StoryErr;?></span>
Story: <br><textarea type="textarea" rows="40" cols="100" name="Story" method="post"></textarea>
</form>
</div>
<?php
//// escape variables for security
//$Title = mysqli_real_escape_string($con, $_POST['Title']);
//$Story = mysqli_real_escape_string($con, $_POST['Story']);
//$Author = mysqli_real_escape_string($con, $_POST['Author']);
//$Date = mysqli_real_escape_string($con, $_POST['Date']);
//Insert into database
?>
I'm going to hazard an answer. Main thing I see is you are using == as assignment and = as comparison. This is backwards.
$valid4 == true; should be $valid4 = true;
if ($valid1 = $valid2 = $valid3 = $valid4 = true) should be if ($valid1 == $valid2 == $valid3 == $valid4 == true) or not really, since it actually has to be:
if ($valid1==true && $valid2==true && $valid3==true && $valid4==true)
With assignment you can stack up the operator, but with boolean comparison, combine the compares with and (&&).
Just some advise, don't make pages submit to themselves. Make a separate page to handle the form from the one that displays the form. That way if you ever want to upgrade to using Ajax, its much easier. Also after doing a db update like this you always need to redirect to another page to prevent double submit (unless using ajax). The page doing the db update should not print anything out but just do the db update and redirect, unless there's a validation error.
Change your PHP to this:
if (isset($_POST['Title'],$_POST['Date'], $_POST['Author'], $_POST['Story'] )){
$con = mysqli_connect("localhost", "my_user", "my_password", "db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$title = $_POST['Title'];
$date = $_POST['Date'];
$author = $_POST['Author'];
$story = $_POST['Story'];
$query = "INSERT INTO Moderate (Title, Story, Author, Date)
VALUES (?, ?, ?, ?)"
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, $query)) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ssss", $city);
/* execute query */
mysqli_stmt_execute($stmt);
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($con);
}

PHP elseif statement usage for form validation and insert to db

I am trying to make my form validation and db insert script work but am facing problems again. I am using an elseif statement to do:
Check if the form was actually submitted by the user clicking the submit button and all data fields completed, if not warn and redirect back to the form page (this is the only part that seems to be working)
If the form has been completed fully and submit button clicked then connect to mysql server and select db or die and display error message
If there is a connection to the database then insert the form data to the table
I can prevent the entry of empty fields but that is all,everything else seems to break. I cannot seem to figure out why. tail -f /var/log/apache2/error.log displays nothing. Perhaps I have over complicated things. I have been using this site as a reference and http://www.w3schools.com/php/php_if_else.asp for elseif syntax, newbie still screwing things up.
Here is the code:
<?php
//Form fields passed to variables
$manu = mysql_real_escape_string($_POST['inputManu']);
$model = mysql_real_escape_string($_POST['inputModel']);
$desc = mysql_real_escape_string($_POST['inputDesc']);
//Connect to database using $conn
include ('connection.php');
//Insert record into table
$sql = "INSERT INTO gear (`id`,`manu`,`model`,`desc`)
VALUES (NULL,'$manu','$model','$desc')";
//Check for empty fields
if ($_POST['submit'])
{
foreach($_POST as $val)
{
if(trim($val) == '' || empty($val))
{
die();
echo "Please complete all form fields!";
echo "<meta http-equiv='Refresh' content='3; URL=../add.php'>";
//header("Location: ../add.php?error=empty_fields");
}
}
}
elseif (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
else
{
//echo "1 record added";
echo "Success, You added the ".$manu." ".$model."";
echo "<meta http-equiv='Refresh' content='3; URL=../index.php'>";
}
mysqli_close($conn);
?>
Here is the code that works but I am sure there are some more refinements that could be made:
<?php
//Connect to database using $conn
include ('connection.php');
//Form fields passed to variables
$manu = mysqli_real_escape_string($conn, $_POST['inputManu']);
$model = mysqli_real_escape_string($conn, $_POST['inputModel']);
$desc = mysqli_real_escape_string($conn, $_POST['inputDesc']);
//Insert record into table
$sql = "INSERT INTO gear (`id`,`manu`,`model`,`desc`)
VALUES (NULL,'$manu','$model','$desc')";
//Check for empty fields
if (isset($_POST['submit']))
{
foreach($_POST as $val)
{
if(trim($val) == '' || empty($val))
{
// echo "Please complete all form fields!";
echo "<meta http-equiv='Refresh' content='3; URL=../add.php'>";
die('Error: Please complete all form fields!' . mysqli_error());
}
}
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
else
{
//echo "1 record added";
echo "Success, You added the ".$manu." ".$model."";
echo "<meta http-equiv='Refresh' content='3; URL=../index.php'>";
}
}
else
{
echo "some error";
}
mysqli_close($conn);
?>
you need to move the query execution part inside the first if.your full code should look like this:
<?php
//Connect to database using $conn
include ('connection.php');
//Form fields passed to variables
$manu = mysqli_real_escape_string($_POST['inputManu']);
$model = mysqli_real_escape_string($_POST['inputModel']);
$desc = mysqli_real_escape_string($_POST['inputDesc']);
//Insert record into table
$sql = "INSERT INTO gear (`id`,`manu`,`model`,`desc`)
VALUES (NULL,'$manu','$model','$desc')";
//Check for empty fields
if (isset($_POST['submit']))
{
foreach($_POST as $val)
{
if(trim($val) == '' || empty($val))
{
die();
echo "Please complete all form fields!";
echo "<meta http-equiv='Refresh' content='3; URL=../add.php'>";
//header("Location: ../add.php?error=empty_fields");
}
}
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
else
{
//echo "1 record added";
echo "Success, You added the ".$manu." ".$model."";
echo "<meta http-equiv='Refresh' content='3; URL=../index.php'>";
}
}
else
{
echo "some error";
}
mysqli_close($conn);
?>

Categories