I've got a legacy app that uses mysqli_*() functions (actually, it uses mysql_*() functions. Gah!). I am using aura/sqlquery as a SQL query generator. For example:
$queryFactory = new Aura\SqlQuery\QueryFactory('mysql');
$select = $queryFactory->newSelect();
$select->from('sometable AS t')
->where('t.field1 = 0')
->where("t.field2 <> ''");
Then we get the raw SQL by casting to string:
$sql = (string) $select;
Now I want to do do some variable binding in a where():
$select->where('t.somefield = ?', $somevalue);
When I cast to string, the escaping/binding never seems to be occur. It appears that the binding only takes place when one uses PDO and prepared statements.
Any ideas how to get variable binding in aura/sqlquery when using a mysqli connection?
If your PHP version is >= 5.6, here is a function that you can use to run a query from aura/sqlquery against mysqli
function mysqli_query_params($mysqli, $query, $params, $types = NULL)
{
$statement = $mysqli->prepare($select);
$types = $types ?: str_repeat('s', count($params));
$statement->bind_param($types, ...$params);
$statement->execute();
return $statement;
}
used like this
mysqli_query_params($mysqli, $select->getStatement(), $select->getBindValues())
You can use $select->getBindValues() to get the bind values.
I will say make use of Aura.Sql than pdo for it helps you in certain other cases like IN () query.
Taking an example from readme.
// a PDO connection
$pdo = new PDO(...);
// prepare the statment
$sth = $pdo->prepare($select->getStatement());
// bind the values and execute
$sth->execute($select->getBindValues());
Let me know in case you need more clarification for the same.
Thank you.
Related
I am trying to find a way to convet my PDO::PARAM_INT and the other pdo values in the switch statement below to use mysqli. I am doing a portfolio project and for school and found out we are not allowed to use PDO for some reason so now I have to restructure 10 pages. Thanks in advance!
public function bind($param, $value, $type = null){
if(is_null($type)){
switch(true){
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
mysqli has a method called bind_param(). It works quite different, so it is not so easy to replace your code with it. The first parameter passed to bind_param() is a string composed of letters signifying the type of parameters. For the most part you can use s for all types. In your case you would need to map booleans to integers presumably. MySQL doesn't have a true boolean data type so all booleans are saved as 0 or 1.
An example would look like this:
$int = 2;
$bool = (int) false;
$string = '0';
$stmt = $mysqli->prepare('INSERT INTO dates VALUES(?,?,?)');
$stmt->bind_param('sss', $int, $bool, $string);
$stmt->execute();
All parameters must be bound in a single call to bind_param and the variables must be passed by reference, so they can't be literals.
You can't just replace your method with a mysqli equivalent. You would need to rewrite your code logic. I would strongly recommend to stick with PDO; it is easier and better than mysqli. If you must use mysqli, then you should probable write or use an existing database abstraction class. Using mysqli on its own is not recommended.
This is en example of what such class could look like:
class DBClass extends mysqli {
public function __construct(
$host = null,
$username = null,
$passwd = null,
$dbname = null,
$port = null,
$socket = null
) {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
parent::__construct($host, $username, $passwd, $dbname, $port, $socket);
$this->set_charset('utf8mb4');
}
public function safeQuery(string $sql, array $params = []): ?array {
$stmt = $this->prepare($sql);
if ($params) {
$stmt->bind_param(str_repeat("s", count($params)), ...$params);
}
$stmt->execute();
if ($result = $stmt->get_result()) {
return $result->fetch_all(MYSQLI_BOTH);
}
return null;
}
}
$int = 2020;
$bool = false;
$string = '0';
$conn = new DBClass('localhost', 'inet', '5432', 'test');
$conn->safeQuery('INSERT INTO dates VALUES(?,?,?)', [$int, (int) $bool, $string]);
var_dump($conn->safeQuery('SELECT * FROM dates WHERE year=2020'));
This is by means not the best class ever, but I use it to illustrate how one could go about extending mysqli with a simpler helper method. It has the same constructor as mysqli class, but the constructor enables error reporting and sets the proper charset. The new method is just a wrapper around the cumbersome prepare/bind/execute pattern. It should work for all kinds of queries.
First off, this whole function is useless by itself. You never need such a function with PDO when you can send all values directly to execute().
Also, it is useless because PDO::PARAM_NULL always being applied automatically, PDO::PARAM_BOOL doesn't work with mysql and most values you are sending to database are strings, making PDO::PARAM_INT of no use either.
Moreover, it could be even harmful in some circumstances. Sending an int as string is all right but sending a string as int could be a disaster.
Either way, there is no way to bind values in mysqli manually, you only have an option to bind all values at once.
As you are already have to rewrite some code, I would suggest you a code which is much simpler yet more powerful than your current approach. Here is a mysqli helper function I wrote. You can use it instead your PDO class. Check out the Examples section there, but just to give you an idea:
Suppose before you had to write something like
$sql = "SELECT * FROM tmp_mysqli_helper_test WHERE id=?";
$db->prepare($sql);
$db->bind(1, $id);
$db->execute();
$row = $db->results();
With this helper function you can have almost the same but simpler:
$sql = "SELECT * FROM tmp_mysqli_helper_test WHERE id=?";
$row = prepared_query($conn, $sql, [$id])->get_result()->fetch_assoc();
I have seen similar questions answered already but I can't seem to apply the same solutions to my code.
$a=1;
$results = DB::query('SELECT posts.`postbody`, posts.`filepost`, posts.`likes`, posts.`posted_at`, users.`id`, posts.`id_of_post` FROM posts, users WHERE posts.`post_id` = users.`id` ORDER BY id_of_post DESC LIMIT :a', array(':a'=>$a));
class DB {
private static function connect() {
$pdo = new PDO('mysql:host=127.0.0.1;dbname=SocialNetwork;charset=utf8', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
public static function query($query, $params = array()) {
$statement = self::connect()->prepare($query);
$statement->execute($params);
if (explode(' ', $query)[0] == 'SELECT') {
$data = $statement->fetchAll();
return $data;
}
}
}
For the record the following code works fine.
$results = DB::query('SELECT posts.`postbody`, posts.`filepost`, posts.`likes`, posts.`posted_at`, users.`id`, posts.`id_of_post` FROM posts, users WHERE posts.`post_id` = users.`id` ORDER BY id_of_post DESC LIMIT 1');
Not ideal, but you could do away with the PDO parameters.
$a = 1;
$sql = "SELECT stuff FROM table LIMIT {$a};";
Then run your query from the $sql string.
As stated in the previous answers if you do not define:
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
You have to define the parameter to be binded as integer:
foreach($params as $key => $value){
if(is_numeric($value))
$statement->bindParam($key,$value,PDO::PARAM_INT);
else
$statement->bindParam($key,$value,PDO::PARAM_STR);
}
$statement->execute();
This is still not a perfect solution, but if you trust the key value pairs(ie they are from code, not user input) it's good enough.
In MySQL's LIMIT clause, it's an error to do this:
LIMIT '1'
Because LIMIT must take an integer, not a string.
If PDO is configured to emulate prepare() (by interpolating values into your SQL string), it's likely to make the interpolated value a quoted string, which will cause an error.
To avoid this, you must use a native integer as your bound variable and you just specify PDO::PARAM_INT.
$statement = self::connect()->prepare($query);
$statement->bindParam('a', $a, PDO::PARAM_INT);
$statement->execute();
That will let the driver know to avoid putting quotes around the interpolated value.
You can also avoid the error if you set the PDO attribute to disable emulated prepares. I always do this, because I don't trust "emulated prepare."
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
See also my tests I wrote up here: Parametrized PDO query and `LIMIT` clause - not working
Im new to database and i have written a LOT of PHP code that accesses a database using MySQL.
I didnt take into account SQL injection attacks so i have to re-write all that PHP code to use mysql prepared statements.
After looking at videos on how to used prepared SQL statements, to perform just ONE SQL command requires a whole lot of "prepared" statements. My existing code has lots of different SQL statements all over the place, it would be a nightmare to change all that code to pack and unpack all the required preparation for each "prepared" statement command.
Is there some kind of wrapper i can use to prevent turning one line of regular SQL into 6 or 7 lines of prepared statements?
For example use to do this line line of SQL
SELECT * from users where userid=10
needs many more lines of prepared SQL statements, especially if there are lots of other SQL statements too it now becomes very complex.
Is there was some sort of one line wrapper that i can call that accepts the template SQL string, plus the parameters, which also executes the command and returns the result in just one line of wrapper for different types of MYSQL statements it would be great and the code would be much less confusing looking and error prone.
For example
$users=WrapAndExecute($db,"SELECT * from users where userid=?","s",$userid);
$data=WrapAndExecute($db,"UPDATE table SET username=?,city=?","ss",$name,$city);
$result=WrapAndExecute($db,"DELETE from table where id=?","s",$userid);
$result=WrapAndExecute($db,"INSERT into ? (name,address) VALUES(?,?)","ss","users",$name,$address);
Each of those lines above would create a prepared statement template, do the bind, execute it and return the result that a regular MYSQL statement would. This would create minimal impact on existing code.
Anybody knows how to do this or if some easy php library or class already exists to do this, that i can just import and start using it?
Thanks
You don't need to change a query to a prepared statement if it has no PHP variables in it. If it has just constant expressions, it's safe from SQL injection.
$sql = "SELECT * from users where userid=10"; // Safe!
$stmt = $pdo->query($sql);
$data = $stmt->fetchAll();
You don't need to change a query that contains PHP variables, as long as the value of that variable is a constant specified in your code. If it doesn't take its value from any external source, it's safe.
$uid = 10;
$sql = "SELECT * from users where userid=$uid"; // Safe!
$stmt = $pdo->query($sql);
$data = $stmt->fetchAll();
You don't need to change a query that contains PHP variables, as long as you can filter the value to guarantee that it won't risk an SQL injection. A quick and easy way to do this is to cast it to an integer (if it's supposed to be an integer).
$uid = (int) $_GET['uid'];
$sql = "SELECT * from users where userid=$uid"; // Safe!
$stmt = $pdo->query($sql);
$data = $stmt->fetchAll();
That leaves cases where you are using "untrusted" values, which may have originated from user input, or reading a file, or even reading from the database. In those cases, parameters are the most reliable way to protect yourself. It's pretty easy:
$sql = "SELECT * from users where userid=?"; // Safe!
// two lines instead of the one line query()
$stmt = $pdo->prepare($sql);
$stmt->execute([$_GET['uid']]);
$data = $stmt->fetchAll();
In a subset of cases, you need one additional line of code than you would normally use.
So quit your whining! ;-)
Re your comment about doing prepared statements in mysqli.
The way they bind variables is harder to use than PDO. I don't like the examples given in http://php.net/manual/en/mysqli.prepare.php
Here's an easier way with mysqli:
$sql = "SELECT * from users where userid=?"; // Safe!
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $_GET['uid']);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_all();
I don't like the stuff they do in their examples with bind_result(), that's confusing and unnecessary. Just use get_result(). So with mysqli, you need two more lines of code than you would with PDO.
I've written query wrappers for mysqli that emulate the convenience of PDO's execute() function. It's a PITA to get an array mapped to the variable-arguments style of bind_param().
See the solution in my answers to https://stackoverflow.com/a/15933696/20860 or https://stackoverflow.com/a/7383439/20860
I were in the same boat, and I wrote such a wrapper that works exactly the way you want, save for it's being a class, not a function.
$user = $sdb->getRow("SELECT * from users where userid=?s", $userid);
$sdb->query("UPDATE table SET username=?s, city=?s", $name, $city);
$sdb->query("DELETE from table where id=?s", $userid);
$sdb->query("INSERT into ?n (name,address) VALUES(?s,?s)","users", $name, $address);
The above is a working code, as long as you have somewhere in your bootstrap file
$db = mysqli_connect(...);
...
require 'safemysql.class.php';
$sdb = new SafeMySQL('mysqli' => $db);
Note that none of the other suggestions could do anything like that.
Also note that if I were writing it today, I would have used PDO, as this class is duplicating a lot of functionality already exists in PDO.
Take a look at the PDO extension in PHP - http://php.net/manual/en/intro.pdo.php: it it secure against injections thanks to prepared statements; also, it allows you to connect to many different databases (e.g. MySQL, MSSQL, etc.).
You can then build your own wrapper as you wish to keep it clean; for example your own wrapper could be as follows:
(following example will return user rows as objects)
// connect to DB
$GLOBALS['default_db'] = new DB('localhost','db_name','username','password') ;
// Get users and output results
$query = new DBQuery('SELECT * FROM users WHERE userid = ?',array(10)) ;
var_dump($query -> results()) ;
var_dump($query -> num_rows()) ;
// DB connection
class DB {
public $connection;
public function __construct($host , $dbname , $username , $password) {
$this->connection = new \PDO('mysql:host=' . $host . ';dbname=' . $dbname , $username , $password);
}
}
// Wrapper
class DBQuery {
private $num_rows = 0;
private $results = array();
public function __construct($query , $params = null , $class_name = null , DB $db = null) {
if ( is_null($db) ) {
$db = $GLOBALS['default_db'];
}
$statement = $db->connection->prepare($query);
$statement->execute($params);
$errors = $statement->errorInfo();
if ( $errors[2] ) {
throw new \Exception($errors[2]);
}
$fetch_style = ($class_name ? \PDO::FETCH_CLASS : \PDO::FETCH_OBJ);
$this->results = $class_name ? $statement->fetchAll($fetch_style , $class_name) : $statement->fetchAll($fetch_style);
$this->num_rows += $statement->rowCount();
while ( $statement->nextrowset() ) {
$this->results = array_merge($this->results,$class_name ? $statement->fetchAll($fetch_style , $class_name) : $statement->fetchAll($fetch_style));
$this->num_rows += $statement->rowCount();
}
}
public function num_rows() {
return $this->num_rows;
}
public function results() {
return $this->results;
}
}
Since a key requirement seems to be that you can implement this with minimal impact on your current codebase, it would have been helpful if you had told us what interface you currently use for running your queries.
While you could use PDO:
that means an awful lot of work if you are not already using PDO
PDO exceptions are horrible
Assuming you are using procedural mysqli (and have a good reason not to use mysqli_prepare()) its not that hard to write something (not tested!):
function wrapAndExecute()
{
$args=func_get_args();
$db=array_shift($args);
$stmt=array_shift($args);
$stmt_parts=explode('?', $stmt);
if (count($args)+1!=count($stmt_parts)) {
trigger_error("Argument count does not match placeholder count");
return false;
}
$real_statement=array_shift($stmt_parts);
foreach ($args as $k=>$val) {
if (isnull($val)) {
$val='NULL';
} else if (!is_numeric($val)) {
$val="'" . mysqli_real_escape_string($db, $val) . "'";
}
$real_statement.=$val . array_shift($stmt_parts);
}
return mysqli_query($db, $real_statement);
}
Note that this does not handle IS [NOT] NULL nicely nor a literal '?' in the statement nor booleans (but these are trivial to fix).
I'm looking to improve the security of database access on a website, and the general consensus seems to be to use prepared statements. I have an idea of how they work, but I want to generalize their use so the only things I need to supply are a query, the parameter types, and values. However, I haven't found any particularly good resources for this and as a result, I'm sort of lost as to how I should approach this.
Basically, what I want is as follows.
$query = "SELECT * FROM Table WHERE Column1 = ? AND Column2 = ?";
$array[0] = "string";
$array[1] = 5;
$parameters = "si";
$dbHandler = new mysqli("server", "user", "password", "database");
$stmt = $dbHandler->prepare($query);
$stmt->bind_param($parameters, $array);
$stmt->execute();
//Process results
I'm aware that this isn't the proper procedure but that's the problem. What can I do to make this work? The idea is that the number of variables within $array may change, as will the parameter list.
I need to supply are a query, the parameter types, and values.
Here you go:
function mysqli_query_params($mysqli, $query, $params, $types = NULL)
{
$statement = $mysqli->prepare($query);
$types = $types ?: str_repeat('s', count($params));
$statement->bind_param($types, ...$params);
$statement->execute();
return $statement;
}
which can be used exactly the way you described:
$query = "SELECT * FROM Table WHERE Column1 = ? AND Column2 = ?";
$params = ["string", 5];
$types = "si";
$mysqli = new mysqli("server", "user", "password", "database");
$data = mysqli_query_params($mysqli, $query, $params, $types)->get_result()->fetch_all();
Note that most of time you can avoid setting types explicitly and let them be mound as strings by default.
However, PDO indeed is way more usable than raw mysqli, and you better use it. You may learn it from this tutorial
P.S. You need PHP >=5.6 and mysqlnd installed for this code to run. Otherwise the amount of code will be increased tenfold. That's another reason to use PDO.
I'm using PHP with MySQLi, and I'm in a situation where I have queries like
SELECT $fields FROM $table WHERE $this=$that AND $this2=$that2
So far I've written some code that splices up an array that I give it, for example:
$search = array(name=michael, age=20) //turns into
SELECT $fields FROM $table WHERE name=michael AND age=20
Is there a more efficient way to do this?
I'm rather worried about MySQL injections - this seems very vulnerable.
Thanks!
Oddly enough, the title to your question is basically the answer to it. You want to do something like this, using mysqli parameterized queries:
$db = new mysqli(<database connection info here>);
$name = "michael";
$age = 20;
$stmt = $db->prepare("SELECT $fields FROm $table WHERE name = ? AND age = ?");
$stmt->bind_param("si", $name, $age);
$stmt->execute();
$stmt->close();
More information in the mysqli section of the manual, specifically the functions related to MySQLi_STMT.
Note that I personally prefer using PDO over mysqli, I don't like all the bind_param / bind_result stuff that mysqli does. If I have to use it I write a wrapper around it to make it work more like PDO.