SQL Real Escape String not showing in database - php

I have a registration form on my site and I figured I should protect from SQL injection. I can't have that table being dropped maliciously.
Using POST, I collect the input from the form, check it, and then add it to the database. My code is below. I've been testing the form, and though the form is submitted successfully, the table is filled with an empty row...not the data from the form.
What's going on here?
<?php
$type = $_POST['type']; // a dropdown
$color = $_POST['color']; // a dropdown
$name = mysql_real_escape_string($_POST['name']);
$address = mysql_real_escape_string($_POST['address']);
$city = mysql_real_escape_string($_POST['city']);
$state = $_POST['state']; // a dropdown
$zip = mysql_real_escape_string($_POST['zip']);
$phone = mysql_real_escape_string($_POST['phone']);
$email = mysql_real_escape_string($_POST['email']);
$where = mysql_real_escape_string($_POST['where']);
$price = mysql_real_escape_string($_POST['price']);
$use = mysql_real_escape_string($_POST['use']);
include 'php/Connect.php';
$ct = new Connect();
$con = $ct->connect();
if(check($email, $con)) {
if(register($type, $color, $name, $address, $city, $state, $zip, $phone, $email, $where, $price, $use, $con)) {
echo '<h1>Success!</h1><p>Thanks for registering your product. A confirmation email has been sent to '.$email.'.</p>';
}
else {
echo '<h1>Error!</h1><p>There were errors processing your registration. Please try again.</p>';
}
}
else {
echo '<h1>Error!</h1><p>This product has already been registered.</p>';
}
function check($email, $con) {
$query = "SELECT * FROM registrations WHERE email='$email'";
$res = mysql_query($query, $con);
if ($con) {
$row = mysql_fetch_assoc($res);
if($row) {
return false; // product registration exists
}
else {
return true; // product registration does not exist
}
}
else {
return false;
}
}
function register($type, $color, $name, $address, $city, $state, $zip, $phone, $email, $where, $price, $use, $con) {
$query = "INSERT INTO registrations VALUES ('$type', '$color', '$name', '$address', '$city', '$state', '$zip', '$phone', '$email', '$where', '$price', '$use')";
$res = mysql_query($query, $con);
if (!$con) {
return false;
}
else {
mysql_close($con);
return true;
}
}
?>

Connect to database before using mysql_real_escape_string
However it is better to use the newer version
$connect=mysqli_connect(.......);
mysqli_real_escape_string($connect,$string);

Fixed it with PeeHaa's help. Here's the corrected code:
<?php
include 'php/Connect.php';
$ct = new Connect();
$db = $ct->connect();
$type = $_POST['type'];
$color = $_POST['color'];
$name = $_POST['name'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$where = $_POST['where'];
$price = $_POST['price'];
$use = $_POST['use'];
if(check($email, $db)) {
if(register($type, $color, $name, $address, $city, $state, $zip, $phone, $email, $where, $price, $use, $db)) {
echo '<h1>Success!</h1><p>Thanks for registering your product. A confirmation email has been sent to '.$email.'.</p>';
}
else {
echo '<h1>Error!</h1><p>There were errors processing your registration. Please try again.</p>';
}
}
else {
echo '<h1>Error!</h1><p>This product has already been registered.</p>';
}
function check($email, $db) {
$stmt = $db->prepare("SELECT * FROM registrations WHERE email=?");
$stmt->execute(array($email));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($db) {
if($rows) {
return false; // product registration exists
}
else {
return true; // product registration does not exist
}
}
else {
return false;
}
}
function register($type, $color, $name, $address, $city, $state, $zip, $phone, $email, $where, $price, $use, $db) {
$stmt = $db->prepare("INSERT INTO registrations VALUES(?,?,?,?,?,?,?,?,?,?,?,?)");
$stmt->execute(array($type, $color, $name, $address, $city, $state, $zip, $phone, $email, $where, $price, $use));
if (!$db) {
return false;
}
else {
mysql_close($db);
return true;
}
}
?>

Related

how to forbid to send data to sql

I'm using strlen to check my inputs values. I want to forbid to the users to send data to my database if the strlen is too long. I didn't find any way to forbid it, so anyone can send as long values as he wants right now. Here's my code:
if (isset($_POST['sub'])) {
$name = $_POST['name'];
$phone = $_POST['phone'];
$phone2 = $_POST['phone2'];
$email = $_POST['email'];
$zipcode = $_POST['zipcode'];
$address = $_POST['address'];
$job = $_POST['job'];
$description = $_POST['description'];
$userid = $_SESSION['id'];
$stmt = $mysqli -> prepare('UPDATE cards SET name=?, phone=?, phone2=?, email=?, zipcode=?, address=?, job=?, description=?, visibility=?, confirmed=? WHERE id = ?');
if (
$stmt &&
$stmt->bind_param('ssssisssiii', $name, $phone, $phone2, $email, $zipcode, $address, $job, $description, $visibility, $confirmed, $id) &&
$stmt -> execute()
) {
echo "Sikeres módosítás!";
} else {
echo $mysqli -> error;
}
}
$getstmt = $mysqli->prepare("SELECT * FROM cards WHERE id= ?");
if ($getstmt and
$getstmt->bind_param('i', $id) and
$getstmt->execute() and
$result = $getstmt->get_result() and
$row = $result->fetch_assoc()
) {
if($row['userid'] == $_SESSION['id']){
$name = $row['name'];
$phone = $row['phone'];
$phone2 = $row['phone2'];
$email = $row['email'];
$zipcode = $row['zipcode'];
$address = $row['address'];
$job = $row['job'];
$description = $row['description'];
}else{
header("Location: index.php");
}
I check the length of inputs here:
if(strlen($name) > 30)
{
echo "test";
exit();
}
if(strlen($job) > 50)
{
echo "test";
exit();
}
if(strlen($email) > 50)
{
echo "test";
exit();
}
//more of these strlen checks
//and html code under that
How can I modify the echo parts to forbid to send the datas?
Well, if you really have to do it your way, you can throw an exception.
However, more common way is to bind your data to model, validate the model checking any business constraints (using the validator) and then acting accordingly. There is plenty of web frameworks providing such an abstraction in any programming language, for PHP see Laravel for inspiration.

Pass value when form submitted to If function on another file

I have two different files.
Checkoutstep4.php
Checkoutstep5.php
When the first form is submitted, I want to take the value of 'country' which has been submitted and use it in an IF function:
This is what I have so far using session variable...
however I get an error saying undefined index and I am not sure why.
checkoutDeliveryInfo (file that runs when the delivery details form is submitted).
<?php
session_start();
require_once 'DatabaseConnection.php';
$_SESSION['customerid'];
if (isset($_POST['submit'])) {
$stmt = $pdo->prepare("INSERT INTO DeliveryDetails (customerid,firstname,lastname, addressline1, addressline2, city, county, country, postalcode)
VALUES ({$_SESSION['customerid']}, :firstname, :lastname, :addressline1, :addressline2, :city, :county, :country, :postalcode)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':addressline1', $addressline1);
$stmt->bindParam(':addressline2', $addressline2);
$stmt->bindParam(':city', $city);
$stmt->bindParam(':county', $county);
$stmt->bindParam(':country', $country);
$stmt->bindParam(':postalcode', $postalcode);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$addressline1 = $_POST['addressline1'];
$addressline2 = $_POST['addressline2'];
$city = $_POST['city'];
$county = $_POST['county'];
$country = $_POST['country'];
$postalcode = $_POST['postalcode'];
$stmt->execute();
$_SESSION['country'] = $country;
header('location:../View/php_shopping_cart/CheckoutStep5.php');
}
IF function in the Checkoutstep5.php file where the session variable is being used:
<?php
include '../../Model/ShoppingCart.php';
$shoppingCart = new ShoppingCart;
// redirect to home if cart is empty
if ($shoppingCart->total_items() <= 0) {
header("Location: ../index.php");
}
?>
<div class="shippingcost"><strong>Shipping Cost <?php
if ($_SESSION['country'] != 'GIB') {
$shippingcost = '10.00';
} else {
$shippingcost = 'FREE';
}
echo $shippingcost;
?></strong>
</div>
Any help is appreciated.
Update: Error Message:
Notice: Undefined index: country in /home/k1509759/www/barbarycoast/View/php_shopping_cart/CheckoutStep5.php on line 246
I've managed to do it by extracting all variables from the session and then using the individual one i wanted.
extract($_SESSION);
if ($country == 'GIB') {
$shippingcost = 'FREE';
} else if ($country == 'GBR') {
$shippingcost = '£10.00';
} else if ($country == 'ESP') {
$shippingcost = '£10.00';
}

Query failed: SQLSTATE[42000]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]The multi-part identifier "msd#gmail.com" could not be bound

Whenever I tried to update my table am getting this error.
My SQL file where I have update function has this code:
function updateUser($userid, $firstname, $lastname, $phone, $email, $address, $zip, $city, $state, $password)
{
$firstname = str_replace('\'', '\'\'', trim($firstname));
$lastname = str_replace('\'', '\'\'', trim($lastname));
$phone = str_replace('\'', '\'\'',trim($phone));
$email = str_replace('\'', '\'\'',trim($email));
$address = str_replace('\'', '\'\'',trim($address));
$zip = str_replace('\'', '\'\'',trim($zip));
$city = str_replace('\'', '\'\'',trim($city));
$state = str_replace('\'', '\'\'',trim($state));
$password = str_replace('\'', '\'\'',trim($password));
$query = <<<STR
Update tbl_users
Set firstname = '$firstname', lastname = '$lastname', phone = $phone, email = $email,
address = '$address', zip = '$zip', city = '$city', state = '$state', password = '$password'
Where userid = $userid
STR;
executeQuery($query);
}
My profile page where am trying to update has the following code:
if (isset($_SESSION['user_id']))
{
// get the details for the movie to be edited
$userdetails = getUserDetailsByID($_SESSION['user_id']);
$_SESSION['userdetails'] = $userdetails;
}
$lastname = $_SESSION['userdetails'][0]['lastname'];
$firstname = $_SESSION['userdetails'][0]['firstname'];
$phone = $_SESSION['userdetails'][0]['phone'];
$email = $_SESSION['userdetails'][0]['email'];
$address = $_SESSION['userdetails'][0]['address'];
$zip = $_SESSION['userdetails'][0]['zip'];
$city = $_SESSION['userdetails'][0]['city'];
$state = $_SESSION['userdetails'][0]['state'];
$password = $_SESSION['userdetails'][0]['password'];
if (isset($_POST['register']) && count($userdetails)){
updateUser((int)$_POST['userid'], $_POST['firstname'], $_POST['lastname'], $_POST['phone'],
$_POST['email'], $_POST['address'], $_POST['zip'],$_POST['city'], $_POST['state'], $_POST['password']);
header("Location: profile.php");
echo '<h2>Thank you for Registering. You will now be redirected to the login page.<h2>';
die();
}
?>

PHP - getting last statements PK ID to use in second function Insert statement [duplicate]

This question already has answers here:
Getting the return value from a function
(2 answers)
Closed 6 years ago.
Duplicate Edit: This question is different because I'm trying to return a specific value, the primary key ID to be used in another functions INSERT statement as a foreign key, within the same action. The "duplicate" question does not answer this, rather it only shows how to get a return value from a function. Not how to get it and insert it correctly in another functions prepare statement. Which I wasn't sure I was doing correctly.
I have two tables, orders and customers that are to have data inserted from one form within the same action. The orders table has a primary key = orderID which also needs to be added into the customers table.
DB Relationship Diagram
I can upload the data to the orders table without a problem, but the second query function to the customers table does nothing. I'm pretty sure it's due to the foreign key constraint I've set. I've done some research and realize I need to get the foreign key id, possibly using $mysqli->insert_id or PDO::lastInsertId, but I'm lost as to how to use it with my current functions.
index.php
$product = $_POST['product'];
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$address = $_POST['address'];
$address2 = $_POST['address2'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$country = $_POST['country'];
$phoneNumber = $_POST['phoneNumber'];
$email = $_POST['email'];
/* Functions */
order_Data ($db, $product, $fName, $lName, $email);
// Need to have orderID from ^ table used in order_custData sql statement
order_custData($db, $orderID, $fName, $lName, $address, $address2, $city, $state, $zip, $country, $phoneNumber, $email);
functions.php
<?php
/** Order Data Function
*/
function order_Data($db, $product, $fName, $lName, $email) {
try {
$sql = "INSERT INTO orders SET product = :product, fName = :fName, lName = :lName, email = :email";
$ps = $db->prepare($sql);
$ps->bindValue(':product', $product);
$ps->bindValue(':fName', $fName);
$ps->bindValue(':lName', $lName);
$ps->bindValue(':email', $email);
$ps->execute();
return $orderID = $db->lastInsertId();
} catch (PDOException $e) {
die("Sorry, There was a problem order table.");
}
}
/** Customer Purchase Information Function
* #param $orderID -- I need to insert the orderID from orders table?
*/
function order_custData($db, $orderID, $fName, $lName, $address, $address2, $city, $state, $zip, $country, $phoneNumber, $email) {
try {
$sql = "INSERT INTO customers SET orderID = :orderID, fName = :fName, lName = :lName, address = :address, address2 = :address2,city = :city, state = :state, zip = :zip, country = :country, phoneNumber = :phoneNumber, email = :email";
$ps = $db->prepare($sql);
$ps->bindValue(':orderID', $orderID); // Foreign key from orders table
$ps->bindValue(':fName', $fName);
$ps->bindValue(':lName', $lName);
$ps->bindValue(':address', $address);
$ps->bindValue(':address2', $address2);
$ps->bindValue(':city', $city);
$ps->bindValue(':state', $state);
$ps->bindValue(':zip', $zip);
$ps->bindValue(':country', $country);
$ps->bindValue(':phoneNumber', $phoneNumber);
$ps->bindValue(':email', $email);
return $ps->execute();
} catch (PDOException $e) {
die("Sorry, There was a problem with the customer table!");
}
}
?>
Now the $orderID and :orderID IN THE order_custData function are just there for me as a visual representation to figure out the problem. I wasn't try to execute the sql statement with it originally. However, anything I've tried seems to throw errors underfined variable or fatal calls to the prepare function of the first function.
Thank you for your time.
The utility function order_Data() already returns the ID:
…
return $orderID = $db->lastInsertId();
(Rewrite to return $db->lastInsertId();, though.)
Simply carry the return value by assigning to a variable:
$orderID = order_Data ($db, $product, $fName, $lName, $email);
order_custData($db, $orderID, $fN …);
Try this. Simply carry the return value by assigning to a variable
<?php
require_once ("models/dbConn.php");
require_once ("models/functions.php");
$action = $_REQUEST['action'];
if ($action == NULL || empty($action)):
$action = '';
endif;
include_once ("views/header.php");
switch ($action) :
case '':
include ("views/main.php");
break;
case 'checkoutCart':
// Once form button is clicked action = completePurchase
include ("views/checkout.php");
break;
case 'completePurchase':
$product = $_POST['product'];
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$address = $_POST['address'];
$address2 = $_POST['address2'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$country = $_POST['country'];
$phoneNumber = $_POST['phoneNumber'];
$email = $_POST['email'];
/* Functions */
$orderID = order_Data ($db, $product, $fName, $lName, $email);
// Need to have orderID from ^ table used in order_custData sql statement
order_custData($db, $orderID, $fName, $lName, $address, $address2, $city, $state, $zip, $country, $phoneNumber, $email);
include ("views/complete.php");
break;
endswitch;
include_once ("views/footer.php");
?>
Your order_Data() function is returning the Order Id, but you are not assigning the the return value in index.php to $objectID.
I.e. Change this...
order_Data ($db, $product, $fName, $lName, $email);
... to this ...
$orderID = order_Data ($db, $product, $fName, $lName, $email);
I recommending checking your error reporting level for PHP on your development environment to include notices, as PHP will have triggered a notice for use of an undefined variable.

PHP insert into mysql database with dates

I would like to be able to add children into a database, which are connected to their parents (who has a member id MID). I believe that the error lies within the date format (atleast that's what I believe), I have also tried to use strtotime($dob), however this didn't change anything.
$name = htmlspecialchars($_GET['Name']);
$dob = $_GET['DOB'];
$newDOB = date("Y-m-d", $dob);
$mid = $_GET['mid'];
if(isset($_GET['Name'], $_GET['DOB'], $_GET['mid']))
$alert = true;
if(!empty($name) && !empty($newDOB) && !empty($mid))
add_family_member($mid, $newDOB, $name);
The function that adds the member:
function add_family_member($mid, $dob, $name)
{
global $con;
$sql = "INSERT INTO Children(MID, DOB, Name) VALUES(?, ?, ?)";
$stmt = $con->prepare($sql);
if($stmt)
{
$b = $stmt->bind_param("iss", $mid, $dob, $name);
if($b)
{
$e = $stmt->execute();
if($e)
return true;
}
}
return false;
}
function add_family_member($mid, $dob, $name)
{
global $con;
$sql = "INSERT INTO Children(MID, DOB, Name) VALUES(:mid, :dob, :name)";
$stmt = $con->prepare($sql);
if($stmt)
{
return $stmt->execute(array(
'mid' => $mid,
'dob' => $dob,
'name' => $name
));
}
return false;
}
see http://www.php.net/manual/en/pdostatement.execute.php for more examples
Try...
function add_family_member($mid, $dob, $name)
{
global $con;
$sql = "INSERT INTO Children(MID, DOB, Name) VALUES(:mid, :dob, :name)";
$stmt = $con->prepare($sql);
$stmt->bindParam(':mid', $mid);
$stmt->bindParam(':dob', $dob);
$stmt->bindParam(':name', $name);
if ($stmt->execute()) {
return true;
}
return false;
}

Categories