API doesn't allow text - php

I've just created a simple API for a CAD/MDT I'm working on, I've managed to get it to show the correct information when I do /citations/userid/1. This will then display all the correct values from the SQL database however, if I do /citations/issued_by/kevingorman1000 it will just throw an error. I can't tell what the error is as I'm using Slim php and can't seem to get the errors to display.
Any ideas why it isn't working ? I've added my code below..
$app->get('/citation/issuedby/{issued_by}', function(Request $request, Response $response){
$issued_by = $request->getAttribute('issued_by');
$sql = "SELECT * FROM ncic_citations WHERE issuedby = $issuedby";
try{
// Get DB Object
$db = new db();
// Call Connection to DB
$db = $db->connect();
$stmt = $db->query($sql);
$issby = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($issby);
} catch(PDOExecption $e) {
echo '{"error"} : {"text": '.$e->getMessage().'}';
}});
Any ideas why this is the case? Does it only allow getting via number or do I need too do something else? First time using this and kinda new to PHP as well.
Thanks for any help.

Your problem is called SQL injection. You can solve it by using prepared statements. Never escape the values with quotes or anything else, as others might have suggested.
$sql = "SELECT * FROM ncic_citations WHERE issuedby = ? ";
$stmt = $db->prepare($sql);
$stmt->execute([$issuedby]);
$issby = $stmt->fetchAll(PDO::FETCH_OBJ);
For a good tutorial on PDO and prepared statements I recommend: https://phpdelusions.net/pdo

It's because SQL error (missing quotes around string).
You try to send query
$sql = "SELECT * FROM ncic_citations WHERE issuedby = kevingorman1000";
Correct query has to be
$sql = "SELECT * FROM ncic_citations WHERE issuedby = 'kevingorman1000'";

Related

Using PHP variables with ADODB

I am trying to do a SQL query with ADODB, which is used in the OXID framework.
$database = oxDb::getDb();
$sql = 'SELECT oxobjectid FROM oxobject2discount WHERE oxdiscountid = '.$oxdiscountid;
$resultado = $database->execute($sql);
This will always throw and exception error. I know you can use the function Prepare with ADODB to sanitize the statement and get ready to use it. However I am unable to call it in Oxid, it seems.
Anyone knows what to do?
Use " quotes
$sql = 'SELECT oxobjectid FROM oxobject2discount WHERE oxdiscountid = "'.$oxdiscountid;.'"';

PHP - Passing pdo connection query via php function

So i'm trying to pass PDO Query by using php, like this(index.php):
include("dbconn.php");
mysqlConnect("'SELECT * FROM users WHERE name =' . $conn->quote($name))", "jeff");
while my dbconn file that contains the function is(dbconn.php):
function mysqlConnect($queryString, $name) {
// DB Credentials
$dbName = 'db';
$dbUser = 'root';
$dbPass = '';
$dbHost = 'localhost';
try {
$conn = new PDO("mysql:host=$dbHost;dbname=$dbName", $dbUser, $dbPass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Here goes the first parameter, then it uses the second parameter as a variable
$data = $conn->query($queryString);
// So the output should be this:
// $data = $conn->query('SELECT * FROM myTable WHERE name = ' . $conn->quote($name));
foreach($data as $row) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
So in my function call the php actually executes the $conn->quote($name)) code, making my application not work.
How should i do this? is this allowed in php?
Edit:
or in other words: i call a function and give it 2 parameters, one of the parameters(even tho it's in double quotes) is executed by php which shouldn't happen. How can i fix this
The way you wrote, it will never work. You just have to learn to distinguish a string literal from executable code.
Anyways, you don't need such a frankenstein at all. There is already a mechanism to put your variable in the query, called prepared statements. You just have to use them.
There are other issues with your code too. I've described them all in the article I wrote recently, The only proper guide on PDO, I am sure you will find it interesting - all the issues like wrong error handling, utterly wrong way to connect, lack of prepared statements - all described there. Having all of them solved, here goes the proper function you need:
function pdo($sql, $data=[])
{
global $pdo; // you can add a call to your favorite IoC here.
$stmt = $pdo->prepare($sql);
$stmt->execute($data);
return $stmt;
}
used as
include("dbconn.php");
$user = pdo("SELECT * FROM users WHERE name = ?", ["jeff"])->fetch();
var_dump($user);
this is how PDO have to be used.
By returning a statement, you'll be able to use all the power of PDO, getting data you need in one line, say a list
$news = pdo("SELECT * FROM news ORDER BY id DESC")->fetchAll();
var_dump($news); // already an array
or just a single value
$count = pdo("SELECT count(*) FROM posts WHERE author=?", [$id])->fetchColumn();
var_dump($count); // already a number
or simply by iterating results one by one
$news = pdo("SELECT * FROM news ORDER BY id DESC")->fetchAll();
foreach ($news as $row) {
var_dump($row);
}
and so on.

How to escape during PDO query statement in php? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
(Edit:Guys, Before jumping to any conclusions, I'm asking how do you escape a query variable from the Example#2 from php.net website. I tried lot of ways but they all gave me errors. If you can please read that Example and post your version of that exact Example#2. Also please read about why they have that example there.)
I was searching for a reliable 'row:count' method to use with PHP PDO across multiple database types, and came across below code from php.net
http://php.net/manual/en/pdostatement.rowcount.php (See Example:#2)
It says to do a row count to see if an entry exists in a database using a SELECT statement, the error proof method is to use PDO::query() instead of PDOStatement::fetchColumn().
My question is I know how to bind and execute with PDO, but I don't know how to assign a user submitted variable($username) to this $sql statement and escape it successfully?
Is it possible to bind parameters to this $sql mehod using PDO?
try{
$conn = new PDO($dsn, $db_username, $db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->db = $conn;
} catch(PDOException $e){
echo 'Error:'.$e;
}
public function usernameExists($username){
//Check db for a match.
$sql = "SELECT * FROM users WHERE username = '".$username."'";
$results = $this->db->query($sql);
if($results->fetchColumn() > 0){
//Matching username found in the db
return true;
}else{
//No matching username in db
return false;
}
}
You're looking for bindValue. With it, you can use a placeholder when writing your query, then pass the user's input afterward.
For example:
public function usernameExists($username){
//$result = $this->db->query('SELECT * FROM users WHERE username = ');
//Check db for a match.
$sql = "SELECT * FROM users WHERE username = :username";
$s = $conn->prepare($sql);
$s->bindValue(':username',$username);
$s->execute();
$results = $s->fetchAll();
if(count($results) > 0){
//Matching username found in the db
return true;
}else{
//No matching username in db
return false;
}
For more info, see the PHP manual.
You're going to want to use a parameterized query like this:
<?php
$value = "whatever";
$stmt = $dbh->prepare("SELECT * FROM TABLE_NAME where column_name = ?");
if ($stmt->execute(array($value))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>
If you really wanted to quote+escape the string, then that's possible too. It even looks somewhat more legible with complex variable interpolation than your original string patching:
$sql = "SELECT * FROM users WHERE username = {$this->db->quote($username)}";
// ->quote itself adds ↑ 'quotes' around
Now of course: don't do that. Use a placeholder, and pass it per ->execute([$var]); instead. Strive for consistency.

Code for Updating MySQLI PHP

A few keep telling me that my code for updating data in my mysqli query is extremely insecure. Actually, several people on this site. So I would like to know what they say would secure my code below so it is secure when updating my database. I would like to know how the would secure my mysqli query.
Okay, in my code for my database entries, this is what I do. Let me start by saying that I always send via POST method to avoid browser url complications.
When I get the POST data, this is my code.
$ID = 1;
$DATA = htmlentities(addslashes($_POST['data']));
$FIELD = "lifename";
$DBQUERY = "UPDATE `lifetable` SET `$FIELD` = '$DATA' WHERE `id` = $ID";
$DBRESULT = $MYSQLI->query($DBQUERY);
I am currently using this on my local site.
How is this unsafe if I have escaped all quotes, all slashes, all ampersands (from javascript through ajax) and all semi colons? How is this vunerable?
So can you tell me what I should change when adding information to my database.
Thanks
PS ... I am using mysqli and will continue to use it. Thanks
A few suggested that I change from mysqli to pdo, but I am not willing to completely 100% change how I access data from my databases. Someone posted another link before about prepare and bind_param and this is what I am going to use. So thank you.
This is now my code, and binding params is supposed to make it so that each param is only for the one part of my query and can not be for anything else, nothing else at all.
$DBQUERY = "UPDATE `lifetable` SET `lifename` = ? WHERE `id` = ?"; // EACH ? IS A PART OF bind_param BELOW IN ORDER AFTER TYPE.
$STMT = $MYSQLI->prepare($DBQUERY);
$STMT->bind_param('si', $DATA, $ID); // THIS MAKES SURE THAT THE VARIABLES ARE ONLY USED FOR THERE PLACE HERE AND NOTHING ELSE. ? in order.
$DATA = htmlentities($_POST['data']); // I STILL USE MY CODE HERE TO REMOVED ANY OTEHR CHARACTERS, JUST INCASE. AND BEFORE IT GETS HERE, IT USES encodeURIComponent TO OUTPUT FROM AJAX.
$ID = $COLUMN[1];
$STMT->execute();
$STMT->close();
My code worked before and it works now, just more secure, or so I am told.
Use PDO Class like:
$db = new PDO('mysql:host=localhost;dbname=<SOMEDB>', '<USERNAME>', 'PASSWORD');
$query = $db->prepare('UPDATE `lifetable` SET :FIELD = :DATA WHERE `id` = :ID');
$query->execute(array(
':FIELD' => $field,
':DATA' => $data,
':ID' => $id
));
$query->commit();
For more info Are there good tutorials on how to use PDO?
i think your security lies in the SQL injection, and the best way i know to make the query secure is using mysql_real_escape_string on the var. Here an example taken from php.net
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$city = $mysqli->real_escape_string($city);
$mysqli->query("INSERT into myCity (Name) VALUES ('$city')")
you can apply the same procedure to your query
$ID = 1;
$DATA = $MYSQLI->real_escape_string($_POST['data']));
$FIELD = "lifename";
$DBQUERY = "UPDATE `lifetable` SET `$FIELD` = '$DATA' WHERE `id` = $ID";
$DBRESULT = $MYSQLI->query($DBQUERY);
I edited the above because I forgot the quotes for lifename in my question. They should be there as they are in my original code.
now tour query should be secure :D
here the reference to php.net documentation :
http://cn2.php.net/manual/en/mysqli.real-escape-string.php

Query returns null

Hello I've got this query to get users by email, which is an unique field in the db.
However, when i want to get the data on it, it simply returns null.
Here's the code
public function getUserByEmail($email)
{
$statement = "SELECT id_user,nome,email,permissao,activo FROM sys_users
WHERE email=$email";
try
{
$sth = $this->db->query($statement);
$sth->setFetchMode(PDO::FETCH_OBJ);
$rcs_users = $sth->fetchAll();
return $rcs_users;
}
catch(PDOException $e)
{
"DB Error".$e->getMessage();
}
}
And the respective function call
$user_rcs = $user->getUserByEmail($email);
var_dump($user_rcs); //returns null
$_SESSION['email'] = $email;
$_SESSION['user'] = $user_rcs->nome;
$_SESSION['permissao'] = $user_rcs->permissao;
And then I get this error
Notice: Trying to get property of non-object in C:\xampp\htdocs\inacesso\admin\modules\auth\authhandler.php on line 24
Glad if you could help me!
Strings in SQL have to be quoted, so unless $email arrives in the function with ' and ' around it, the SQL will error.
But you shouldn't be building SQL by mashing together PHP strings anyway. Use PDO or mysqli_* with bound parameters (and prepared statements) and that will take care of quoting (and escaping) for you.
First off, seriously have a look at PDO.
Secondly I would imagine the email column is a string. As such, you'll need to surround $email with quotes in your query (after having sanitized it vigorously of course...)
WHERE email='$email'
PDO version:
$pdo = new PDO(...);
$query = $pdo->prepare('SELECT id_user,nome,email,permissao,activo '.
'FROM sys_users '.
'WHERE email = ?');
$result = $query->execute(array($email));

Categories