Am I using PDO correctly to prevent sql injections? - php

I've spent the last day trying to figure out how to incorporate PDO into my code to prevent sql injections. This is what I have come up with. However, whenever I submit my information from the browser, it is not updated into my table and no error messages are shown. Something is wrong but I'm not sure what. I'm postive the syntax is not the problem because I've checked that multiple times. I know my database can be accessed so I'm thinking there is a problem with the way I'm using PDO. Please help me guys.
The PSBE_LOGIN contains all the information to access my database
<?php
require_once 'PSBE_LOGIN.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL:" . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database:" . mysql_error());
if (isset($_POST['title']) &&
isset($_POST['author']) &&
isset($_POST['isbn']))
//This checks to see if there is a value inputted into the form at the bottom
{
$title = get_post('title');
$author = get_post('author');
$isbn = get_post('isbn');
//This retrieves information from the user and assigns it to a variable
$stmt = $pdo->prepare('INSERT INTO classifieds(title, author, isbn)
. VALUES(:title, :author, :isbn)');
$stmt->execute(array('title'=> $title, 'author'=> $author, 'isbn' => $isbn));
}
echo <<<_END
<form action="PSBE_POST_AD.php" method="post">
Title <input type="text" name="title" />
Author <input type="text" name="author" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</form>
_END;
?>
EDIT: CODE REWRITTEN TO INCLUDE PDO API.
<?php
require_once'connection.php';
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
if (isset($_POST['title']) &&
isset($_POST['author']) &&
isset($_POST['isbn']))
//This checks to see if there is a value inputted into the form at the bottom
{
$title = get_post('title');
$author = get_post('author');
$isbn = get_post('isbn');
//This retrieves information from the user and assigns it to a variable
$stmt = $pdo->prepare('INSERT INTO classifieds(title, author, isbn)
. VALUES(:title, :author, :isbn)');
$stmt->execute(array('title'=> $title, 'author'=> $author, 'isbn' => $isbn));
}
echo <<<_END
<form action="PSBE_POST_AD.php" method="post">
Title <input type="text" name="title" />
Author <input type="text" name="author" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</form>
_END;
function get_post($var){
return mysql_real_escape_string($_POST[$var]);
}
?>

Get rid of both
$title = get_post('title');
$author = get_post('author');
$isbn = get_post('isbn');
and
function get_post($var){
return mysql_real_escape_string($_POST[$var]);
}
because the function you're using is based on an mysql_ function and those two APIs do not mix.
You don't need it, because you're already using placeholders.
while replacing it with
$title = $_POST['title'];
$author = $_POST['author'];
$isbn = $_POST['isbn'];
You also need to change
$stmt = $pdo->prepare(...
to
$stmt = $db->prepare(...
given your PDO connection $db = new PDO(...

You are not using them correctly. You need to connect using the PDO API (you're connecting using the mysql_ API). Otherwise, the preparation is correct.

Related

I am having trouble saving my PHP data to MySQL database

My .php page is connected to mySql database successfully. It can see the table and pull from the tables but won't save data from the text-box in my php form to the database.
config.php
<?php
try{
$db = new PDO("mysql:host=localhost;dbname=nolarec;port=3307","root","");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch(Exception $e) {
echo $e->getMessage();
exit;
}
?>
fball_event.php
<form method="post" action="fball_create.php">
<input type="hidden" name="submit" value="true">
<fieldset>
<legend>New Event</legend>
Id: <input type="text" name="id"/> <br/>
Name: <input type="text" name="name"/> <br/>
Time: <input type="text" name="time"/> <br/>
Type: <input type="text" name="type"/> <br/>
</fieldset>
<br />
<input type="submit" value="Create New Event" />
</form>
<?php
require_once('config.php');
if (isset($_POST['submit'])){
include ('config.php');
$id = $_POST['id'];
$name = $_POST['name'];
$time = $_POST['time'];
$type = $_POST['type'];
$results = $db->prepare ("INSERT INTO nolarec.fball_event (id, name, time, type) VALUES ('$id','$name','$time','$type')");
}
?>
First of all you should be using placeholders for your data inputs in the query, second of all you need to actually execute it, you've just prepared it. Try:
$id = $_POST['id'];
$name = $_POST['name'];
$time = $_POST['time'];
$type = $_POST['type'];
$results = $db->prepare ("INSERT INTO nolarec.fball_event (id, name, time, type) VALUES (:id,:name,:time,:type)");
$results->bindValue(":id", $id);
$results->bindValue(":name", $name);
$results->bindValue(":time", $time);
$results->bindValue(":type", $type);
$results->execute();

PHP Database: value not inserting in table

insert.php
<?php
mysql_connect("localhost","root",""); mysql_select_db("basic");
$name=$_POST['fname'];
$twait=$_POST['twait'];
$cprice=$_POST['cprice'];
$dprice=$_POST['dprice'];
$order= "INSERT INTO calculator
(name,total_wt,crt_price,dollar_rate) VALUES
('$name','$twait','$cprice','$dprice')";
$result = mysql_query('$order');
echo "Done";
?>
HTML page:
<!DOCTYPE html>
<html>
<head>
<title>JN DIAMONDS</title>
</head>
<body>
<form align="center" method="POST" action="insert.php">
<fieldset>
<legend>Info</legend><br>
<input type="text" name="fname" placeholder="Name"><br><br>
<input type="text" name="twait" placeholder="Total Rough Weight"><br><br>
<input type="text" name="cprice" placeholder="1 Carat Price"><br><br>
<input type="text" name="dprice" placeholder="Dollar Rate"><br><br>
<input type="submit" name="submit"value="Submit"><br>
</fieldset>
</form>
</body>
</html>
$order is a variable containing your mysql string.
When you put $order in quotes, then you are not sending $order into the mysql string, you are actually trying to execute the query '$order' which is not a valid mysql query.
Simply remove the quotes.
$result = mysql_query($order);
The actual error in your code has already been pointed out.
The mysql_* extension is deprecated and will be removed in the upcoming version 7 of php; choose another api to connect to your MySQL server, e.g. PDO. Using prepared statements will take care of the worst sql injections as well.
<?php
if ( !isset($_POST['fname'], $_POST['twait'], $_POST['cprice'], $_POST['dprice']) ) {
trigger_error('missing POST parameter in '.var_export($_POST, true), E_USER_WARNING);
echo '<html><head><title>...</title><body><h1>missing POST parameter</h1></body></html>';
}
else {
$pdo = new PDO('mysql:host=localhost;dbname=basic;charset=utf8', 'root', '', array(
PDO::ATTR_EMULATE_PREPARES=>false,
PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
$stmt = $pdo->prepare('
INSERT INTO
calculator
(name,total_wt,crt_price,dollar_rate)
VALUES
(:fname,:twait,:cprice,:dprice)
');
$stmt->execute(array(
'fname'=>$_POST['fname'],
'twait'=>$_POST['twait'],
'cprice'=>$_POST['cprice'],
'dprice'=>$_POST['dprice']
));
echo "Done";
}
Pls try this code
<?php
mysql_connect("localhost","root",""); mysql_select_db("basic");
$name=$_POST['fname'];
$twait=$_POST['twait'];
$cprice=$_POST['cprice'];
$dprice=$_POST['dprice'];
$order= "INSERT INTO calculator
(name,total_wt,crt_price,dollar_rate) VALUES
('$name','$twait','$cprice','$dprice')";
$result = mysql_query($order);
echo "Done";
?>
Use mysqli instead of mysql.
$con = mysqli_connect('localhost', 'root', '', 'basic');
$name=$_POST['fname'];
$twait=$_POST['twait'];
$cprice=$_POST['cprice'];
$dprice=$_POST['dprice'];
$order= "INSERT INTO `calculator` (name,total_wt,crt_price,dollar_rate)
VALUES ('".$name."','".$twait."','".$cprice."','".$dprice."')";
$result = mysqli_query($con,$order);
echo "Done";

Can't send query to db

im trying out some code by my own. I just started to learn PHP & mysql. Could anyone tell me where is the mistake? I got a error when processing the query.
My db is set like in the code.
Db name: sweepstakes
Table name: alfa
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "sweepstakes";
$db = mysqli_connect($dbhost,$dbuser,$dbpass, $dbname);
if(mysqli_connect_errno()){
die("Database connection failed: " .
mysqli_connect_errno() .
" (" . mysqli_connect_errno() . ")"
);
}
if($_SERVER['REQUEST_METHOD']=='POST'
&& $_POST['submit']=='Submit'
&& !empty($_POST['name'])
&& !empty($_POST['description'])
&& !empty($_POST['adress'])) {
$name = $_POST['name'];
$desc = $_POST['description'];
$adress = $_POST['adress'];
$query = "INSERT INTO alfa (name, description, adress) VALUES ('$name', '$desc', '$adress')";
$result = mysqli_query($db, $query);
if($result){
}else{
die("Database query failed." . mysql_error() . " " . mysqli_connect_error($db));
}
} else { echo "Empty!";
}
?>
<form method="post" action="index.php">
<fieldset>
<legend>New Sweepstakes</legend>
<label>Name: </br>
<input type="text" name="name" maxlength="150" />
</label> </br>
<label>Description:</br>
<textarea name="description" cols="45" rows="10"></textarea>
</label> </br>
<label>Adress:</br>
<input type="text" name="adress" maxlength="1080" />
</label> </br>
<input type="submit" name="submit" value="Submit" />
</fieldset>
</form>
You're mixing mysql and mysqli functions. Stick with mysqli, mysql is deprecated (don't use it).
In case you didn't spot it: mysql_error() should be mysqli_error()
In addition to checking what Halcyon writes ( using mysqli_error() ), I would also check the query string itself. Just echo out $query right after it's built (the $query = "INSERT..." line) and when running the script look to see if the output matches what you expect to happen, ie that you see something like INSERT INTO alfa (name, description, adress) VALUES ('fred', 'blonde dude', 'Anywhere 32B'). If anything looks out of place (like maybe you have a ' or " in the inputed data and it's screwing up the string output), fix it and try again.
echo and print and print_r()are your friends when doing detective work on new code to see what is the output expected.
(edit)
After reading your update with Halcyon, you should probably check how your auto-incremented field is set up. If, for example, you've been tinkering with this for a while but only set the auto-increment field to INT(2), you might have run out of space for numbers (can only go up to 99 with INT(2)). Increase it to INT(11) or something similar, empty the table, and try again. You can also try ALTER TABLEtable_nameAUTO_INCREMENT = 1 to reset the auto numbering.

how to fetch data from mysql and write it to innerhtml of a div in PHP

Apologies for the newbie question, I just started with PHP, trying to fetch data when the user writes ID, and get info from database and write it into innerhtml of div's inside the form. How can I do it? thanks.
<form action="read.php" method="post">
Bring Data of ID <input type="text" name="id" />
<br/>
<input type="submit" />
<br/>
<div id="username" style="font-weight:bold;" /></div>
<br/>
<div id="email" style="font-weight:bold;" /></div>
<br/>
<div id="password" style="font-weight:bold;" /></div>
</form>
<?php
$db_username = "root";
$db_password = "";
$con = new PDO('mysql:host=localhost;dbname=test', $db_username, $db_password);
if (!$con) {
echo "error";
}
else {
echo "connected";
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$query = $con->prepare(" SELECT * FROM bucky (username, email, password) WHERE id=:id ");
$query->execute(array(
':id' => $_POST['id']
));
}
else {
die("Die hacker!");
}
In your read.html, append your html code at the end:
<?php
[...]
$query = $con->prepare(" SELECT * FROM bucky (username, email, password) WHERE id=:id ");
$query->execute(array(
':id' => $_POST['id']
));
$result = $sth->fetchAll();
}
else {
die("Die hacker!"); // seriously?
}
?><html><body><?php
print_r($result); ?>
</body></html>
This will print you the result of your query.
You can also iterate over the result, but i think you should really just read the documentation on PDO and how to use it. Maybe a simple introduction to PHP as well. This is a VERY basic Question.

Adding my form data to the database using PHP

Hi there I am struggling with getting my form to post its data to MySQL database.
I have a config file setup like this:
// server info
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'cms';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
The form php page:
<?php
include("config_database.php")
?>
<?php
include("addproduct.php")
?>
<article>
<section class="Input">
<fieldset><legend><span> Add a product to the database </span></legend>
<form action="addproduct.php" method="post">
<label> product name: </label><input type="text" name="name"><br />
<label> product quantity: </label><input type="text" name="quantity"><br />
<label> product description: </label><input type="text" name="description"><br />
<label> product price: </label><input type="text" name="price"><br />
<input type="submit" class="reg">
</form>
then a "addproduct.php" to hopefully send the data to the database:
require_once ("config_database.php");
if (isset($_POST['name']) &&
!empty($_POST["name"]) &&
isset($_POST['quantity']) &&
!empty($_POST["quantity"]) &&
isset($_POST['description']) &&
!empty($_POST["description"]) &&
isset($_POST['price']) &&
!empty($_POST["price"]))
{
$name = get_post('name');
$quantity = get_post('quantity');
$description = get_post('description');
$price = get_post('price');
$query = "INSERT INTO products VALUES" .
"('', '$name', '$quantity', '$description', '$price')";
}
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
How do I get the data entered in my form into my database?
You try the insert query like this using mysqli.
$query = "INSERT INTO products VALUES (NULL, '$name','$quantity', '$description','$price')";
$mysqli->query($query);
and also use real escape string like this for mysqli.
$mysqli->real_escape_string($_POST[$var]);

Categories