How to avoid mysql injections using PDO - php

How can I avoid mysql injections? This is the PHP file I have right now
<?php
include 'config.php';
$Name = $_GET['Name'] ;
$sql = "Select * from tables where names =\"$Name\"";
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->query('SET CHARACTER SET utf8');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$names = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"key":'. json_encode($names) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
When I put $stmt = $dbh->query($sql); $stmt->execute(array(':name' => $name)); to the code it doesn't work. So how should I do it?

Read about pdo prepared statements
Here is an example
$stmt = $dbh->prepare("SELECT * FROM tables WHERE names = :name");
$stmt->execute(array(':name' => $name));

Related

PDO return success but no data is updated on database

when i try to update a row with PDO function it returned success and when i check database there was no data updated
so i followed this question PDOStatement::execute() returns true but the data is not updated which has answers already but didn't work here is what i did
Below is code i tried
<?php
$Fuid = '105199239598939142575';
sendOT($Fuid);
echo '<br>Below is var_dump() Rsult<br>';
check($Fuid);
function sendOT($Fuid) {
try {
$phone = '6381211774';
$otp = '1234';
$conn = new PDO("mysql:host=" . DBHOST . ";port=3306;dbname=" . DBNAME, DBUSER, DBPASS);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8");
$stmt2 = $conn->prepare("UPDATE members SET verification_code=:veri_code AND phone=:phone WHERE Fuid=:Fuid");
$stmt2->bindParam(':Fuid', $Fuid, PDO::PARAM_STR);
$stmt2->bindParam(':veri_code', $otp, PDO::PARAM_STR);
$stmt2->bindParam(':phone', $phone, PDO::PARAM_STR);
$stmt2->execute();
echo 'Updated succeeded';
} catch (Exception $e) {
echo $e;
}
}
function check($Fuid) {
$conn = new PDO("mysql:host=" . DBHOST . ";port=3306;dbname=" . DBNAME, DBUSER, DBPASS);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8");
$stmt2 = $conn->prepare("SELECT * FROM members WHERE Fuid=:Fuid");
$stmt2->bindParam(':Fuid', $Fuid, PDO::PARAM_STR);
$stmt2->execute();
$unr = $stmt2->fetch(PDO::FETCH_ASSOC);
var_dump($unr);
}
?>
Output
as per the answer in this question PDOStatement::execute() returns true but the data is not updated may be there is no row with WHERE so i tried with the same WHERE with SELECT query and it showed result.
WHY is my UPDATE query doesn't update in database?
After many tries i managed to update with this query.
$stmt2 = $conn->prepare("UPDATE members SET verification_code=:veri_code, phone=:phone WHERE Fuid=:Fuid");
it worked after removing AND from query using como , in update queries.

why php-pdo don't insert values [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 3 years ago.
I'm setting to do a simple query using PDO. However, when I run it, it does not insert. The database is called "famous" and the table is called "pessoas" containing only two columns called (codigo and nome).The connection works, but when I execute it return "Error to save".
<?php
function getConnection(){
$dsn = 'mysql:host=localhost;bdname=pessoas';
$user = 'root';
$password = 'init4289';
try{
$pdo = new PDO($dsn, $user, $password);
echo 'SUCESSO AO CONECTAR!';
return $pdo;
}catch(PDOExeption $ex){
echo 'erro: '. $ex->getMessage();
}
}
?>
#end page "conexao_pdo.php"
<?php
include 'conexao_pdo.php';
$conn = getConnection();
$sql = "INSERT INTO famosos (codigo, nome) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, 6);
$stmt->bindValue(2, 'Antonio');
if($stmt->execute()){
echo 'Success to save';
}else{
echo '<p>'.'Error to save';
}
?>
You may consider the following:
probably it's just a typing error - bdname should be dbname in 'mysql:host=localhost;bdname=pessoas'
database and table names - 'famous' and 'pessoas' in the question, 'pessoas' and 'famous' in the code
include exception handling with PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
your function getConnection() should return false on failure
Code, based on your question:
<?php
function getConnection(){
$dsn = 'mysql:host=localhost;dbname=pessoas';
$user = 'root';
$password = 'init4289';
try {
$pdo = new PDO(
$dsn,
$user,
$password,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
echo 'SUCESSO AO CONECTAR!';
} catch (PDOExeption $ex){
echo 'Error: '. $ex->getMessage();
return false;
}
return $pdo;
}
?>
<?php
include 'conexao_pdo.php';
// Connection
$conn = getConnection();
if ($conn === false) {
exit;
}
// Statement
try
$sql = "INSERT INTO famosos (codigo, nome) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, 6);
$stmt->bindValue(2, 'Antonio');
if ($stmt->execute()) {
echo 'Success to save';
} else {
echo '<p>'.'Error to save';
}
} catch (PDOExeption $ex){
die ('Error: '. $ex->getMessage());
}
?>

prepared statement PDO Probably small mistake

im rewriting all my database queries so that they are prepared and with PDO (before I used mysqli) so that they are save against sql injections. Now I'm new to PDO so its probably a small mistake that I dont see, so I hope u guys can help me out because this code doesnt work.
<?php
function getUserBalance($steamid)
{
include 'settings.php';
$conn = new PDO("mysql:host="$servername";dbname="$dbname"", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $conn->prepare("SELECT balance FROM users WHERE steamid= :steamid");
$stmt = $conn->prepare($sql);
$stmt->bind_param(":steamid", $steamid, PDO::PARAM_STR);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
return $row['balance'];
}
}
$stmt->close();
?>
Okey so now I changed it to new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);, moved the $stmt->close(); within the function (oops) , and changed bind_param to bindParam, Thx guys its working now
<?php
include 'ChromePhp.php';
function getUserBalance($steamid)
{
include 'settings.php';
$db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT balance FROM users WHERE steamid= :steamid";
$stmt = $db->prepare($sql);
$stmt->bindParam(':steamid', $steamid, PDO::PARAM_STR);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
return $row['balance'];
}
$stmt->close();
}
?>
Change this line
$conn = new PDO("mysql:host="$servername";dbname="$dbname"", $username, $password);
to this
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

Can I include one pdo connection

Im a just moving to using PDO for my development and I see in most tutorials that the connection is opend for each db query like in Jeffery Ways example below
$id = 5;
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Can I still do a connection in an external file and include it at the top of my page like with previous procedural coding and then do my queries below in the page?
<?php include 'includes/db.php';?>
You probably misunderstood what he says. To open one connection and use it throughout the whole application is not that something you "can" but actually you should.
So - yes, you are doing it right.
Also note that this thing with
try {
...
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
that Jeffery taught you is wrong. Never use a try catch to echo an error message. PHP will handle it better
So, your code should be like this
include 'includes/db.php';
$stmt = $pdo->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
while db.php has to contain something like this
<?php
$dsn = "mysql:host=localhost;dbname=test;charset=utf8mb4";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $username, $password, $opt);
Also note that when using this PDO object, you have to be aware of the variable scope.
Further reading: https://phpdelusions.net/pdo
The short answer is yes,
if you are farmilier with OOPHP it might be worth creating a wrapper class to help with running queries but just creating the connection in a file and including it will get the job done
in the above example you can put
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
into your db.php and the run the queries
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
wherever you need.
it may also be worth mentioning that you dont have to use prepared statements with PDO which can speed things up in coding however if you wish to do that i would highly recomend a database wrapper class
non prepared statement
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$query = "
SELECT
col_1,
col_2
FROM
table_1
WHERE
col_3 = " . $conn->quote($_POST['input']); //the quotr is important, it escapes dangerous characters to prevent SQL injection
//this will run the query for an insert this is all thats needed
$statement = $conn->query($query);
//fetch single col
$col = $statement->fetch(PDO::FETCH_ASSOC);
//fetch all collums
$cols = $statement->fetchAll(PDO::FETCH_ASSOC);
the advantage of this way is that you can build up the query SQL in a more simple to follow manner, i should not that i havent tested this code but in theory it should be fine as this is how i do database handling
Edit:
Your Common Sense brings up a good point about the echo 'ERROR: ' . $e->getMessage(); being a bad idea and this is a prime example of why you should NEVER blindly copy and paste code
Yes, example:
db.php
<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
FROM:
http://www.php.net/manual/en/pdo.error-handling.php
Then just include db.php. I name my connection $PDO, seems more implicit, especially when you are building a prepared statement on that.

Login script using PDO extension not working

I am unsure if I am doing it properly but I just started working with PDO and I am not able to get my code to work. I continue to get the error "sorry could not connect" and I am unable to figure out what is wrong.
Included below is the code that I am using:
function doRun( $data )
{
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare(' SELECT
username, pass
FROM
testTable
WHERE
username = :name
AND
pass = :pass
');
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
$stmt->execute();
//$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result = $stmt->fetchColumn();
if($result == false)
{
echo 'sorry could not connect';
}
else
{
$_SESSION['username'] = $user;
echo 'logged in as' . $user;
}
}
catch (PDOException $e)
{
echo "throw";
}
$db = NULL;
}
This would give you 0 rows as it seems that $username and $pass are not defined:
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
^^^^^^^^^
You probably want some elements from $data variable you are feeding to the function as a username and password.
Later on you are using a variable $user that is undefined as well.
What does $data contain?
The reason that you are "unable to connect", even though you are connecting but you're not finding a match, is because your user variables are not defined.
Try the following solution:
<?php
function doRun( $data )
{
$msg = '';
$username = isset($_POST['name']);
$pass = isset($_POST['pass']);
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare('
select
username
,pass
from
testTable
where
username = :name
and pass = :pass
');
$stmt->execute(array(':name' => $username, ':pass' => $pass);
$result = $stmt->fetchAll();
if(!empty($result)){
$_SESSION['username'] = $user;
$msg = "logged in as $user";
}else{
$msg = "Unable to connect";
}
} catch (PDOException $e) {
echo "Error: $e";
}
echo $msg
$db = NULL;
}
?>

Categories