I've been having trouble with storing a password_hash into my MySql database. It's cutting off characters from the beginning and some in between.
I've tried setting the encoding to UTF 8 in the HTML, setting the same in the connect function and also I've changed the collation to every possible type. Yet I am able to paste the correct hash from an echo into the database and that works fine.
$password = $_POST['pno'];
$pno = password_hash($password,PASSWORD_DEFAULT);
MySqlDb::query('INSERT INTO user (name, email, pno, address_line_1, address_line_2, town, county, post_code, phone) VALUES (:name, :email, :pno, :address_line_1, :address_line_2, :town, :county, :post_code, :phone)',
[':name'=>$name, ':email'=>$email, ':pno'=>$pno, ':address_line_1'=>$address_line_1, ':address_line_2'=>$address_line_2, ':town'=>$town, ':county'=>$county, ':post_code'=>$post_code, ':phone'=>$phone]);
echo $pno;
So the echo will give me this: $2y$10$rtlUaDeXsyhtWS5.SS4nuu.xapBdrHXG7V.DpSLCLAAwYqXPJHKWi
But in the database it stores this:
y$rtlUaDeXsyhtWS5.SS4nuu.xapBdrHXG7V.DpSLCLAAwYqXPJHKWi
I've also tried the encode and decode functions, pretty much out of ideas.
class MySqlDb {
/**
* #var MySQLi instance
*/
protected static $link;
/**
* #var bool set to true to print query before executing
*/
public static $debug = false;
/**
* Creates a new MySQLi instance use getConnection() to retrieve
* #return none
*/
private function __construct() {
self::$link = #mysqli_connect(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME);
if (mysqli_connect_errno()) {
//die('MySqlDb Error: Could not connect to database ('.mysqli_connect_errno().')');
throw new Exception('MySqlDb::() Could not connect to database (' . mysqli_connect_errno() . ')');
}
}
/**
* Returns the MySQLi connection
* #return MySQLi instance
*/
public static function getConnection() {
if (!self::$link) {
new MySqlDb();
}
return self::$link;
}
/**
* Helper function for mysqli_query if params are given will use quote function
* see below MySqlDb:quote this is to help avoid sql injection attacks and automatically escape slashes etc
*
* #param string $sql
* #param array $params
* #return mysqli_query resource ...
*
* Example:
* MySqlDb::query("drop from user where id=$_GET['id']"); // very bad 'id' could contain "' or 1=1"
* MySqlDb::query("drop from user where id=:id", [':id' => $_GET['id']]); // much better
*/
public static function query($sql, array $params = null) {
$con = self::getConnection();
if (!empty($params)) {
$sql = self::quote($sql, $params);
}
if (self::$debug) {
echo $sql;
}
$res = mysqli_query($con, $sql);
if (!$res) {
//die('MySqlDb Error: query: '.mysqli_error($con));
throw new Exception('MySqlDb::query() ' . mysqli_error($con));
}
return $res;
}
/**
* Helper function to quote sql values similar to pdo::bindvalue using named parameters
* to help avoid sql injection attacks and avoid using stuff like addslashes
*
* #param string $sql sql string to quote
* #param array $params key value pairs of parameters and values to placed into them
* #return string sql quoted string
*
* Example:
* $sql = MySqlDb::quote("select * from users where id=:unique1 or id=:unique2", [':unique1'=>2, ':unique2'=>4])
* TODO:
* MySqlDb::quote("select * from users where id+5 = :id or id = :id",[':id'=>3] fails on number params dont match like pdo
* could convert 'substr_count($sql, ':')' into '$unique_sql_param_count'
* e.g. preg_match_all("/:[\w-_]+\b/i", $test, $matches); $paramcount = count(array_flip($matches[0]));
*/
public static function quote($sql, array $params) {
// check correct number of params
if (substr_count($sql, ':') != count($params)) {
//die('MySqlDb Error: quote: number params do not match');
throw new Exception('MySqlDb::quote() number params do not match');
}
$cnt = 0;
foreach ($params as $param => $value) {
//$sql = str_replace($param, "'".self::escape($value)."'", $sql, $cnt); // was matching sub strings :(
$sql = preg_replace("/$param\b/i", "'" . self::escape($value) . "'", $sql, -1, $cnt);
if ($cnt !== 1) {
//die("MySqlDb Error: quote: param '{$param}' not matched or is duplicate");
throw new Exception("MySqlDb::quote() param '{$param}' not matched or is duplicate");
}
}
return $sql;
}
/**
* Wrapper for mysqli_escape_string
* #param mixed $value
* #return escaped value
*/
public static function escape($value) {
return mysqli_escape_string(self::getConnection(), $value);
}
/**
* Helper function to return all rows in result as an associative array
* #param string $sql
* #return array array of arrays
*/
public static function all($sql, array $params = null) {
return mysqli_fetch_all(self::query($sql, $params), MYSQLI_ASSOC);
}
/**
* Helper function to return first row in result from potential multiple values
* #param string $sql
* #return array single array
*/
public static function first($sql, array $params = null) {
$res = mysqli_fetch_array(self::query($sql, $params), MYSQLI_ASSOC);
return is_array($res) ? $res : [];
}
/**
* Helper function to return first field in result from potential multiple values
* #param string $sql
* #return mixed single variable
*/
public static function scalar($sql, array $params = null) {
$res = mysqli_fetch_array(self::query($sql, $params), MYSQLI_NUM);
return is_array($res) ? $res[0] : null;
}
}
This line in your quote method is the direct cause of the problem.
$sql = preg_replace("/$param\b/i", "'" . self::escape($value) . "'", $sql, -1, $cnt);
The result of self::escape($value) will be your original hash,
$2y$10$rtlUaDeXsyhtWS5.SS4nuu.xapBdrHXG7V.DpSLCLAAwYqXPJHKWi
In the context of preg_replace, the $2 and $10 are meaningful. In the Parameters section of the preg_replace documentation it says
replacement may contain references of the form \n or $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern.
You have no parenthesized patterns, so those values are replaced with nothing.
You could fix it by escaping any $ in the replacement parameter, but I would rather recommend replacing your escape/replace-based quote method with a method that creates a prepared statement and binds the parameters before executing it.
Related
I want to view the SQL statement that is about to be executed below :
<?php
//Deleting existing robot
$success = $connection->delete(
"robots",
"id = 101"
);
//Next SQL sentence is generated
DELETE FROM `robots` WHERE `id` = 101
How can I add some kind of listener or just plain var_dump the select query that is about to generated by the $connection->delete
Thanks
The way I settled on is to use a logger class and the event system: Phalcon Events Manager
You create a class that extends the logger adapter
<?php
namespace PhalconX\Logger\Adapter;
/**
* Basic Array based Logging for debugging Phalcon Operations
* #package PhalconX\Logger\Adapter
*/
class Basic extends \Phalcon\Logger\Adapter
{
private $data = array();
/**
* Add a statement to the log
* #param string $statement
* #param null $type
* #param array $params
* #return $this|\Phalcon\Logger\Adapter
*/
public function log($statement, $type=null, array $params=null)
{
$this->data[] = array('sql'=>$statement, 'type'=>$type, 'params'=>$params); // array('sql'=>$statement, 'type'=>$type);
return $this;
}
/**
* return the log
* #return array
*/
public function getLog(){
return $this->data;
}
/**
* Required function for the interface, unused
* #param $message
* #param $type
* #param $time
* #param $context
*/
public function logInternal($message, $type, $time, $context){
}
/**
* Required function for the interface, unused
*/
public function getFormatter(){
}
/**
* Required function for the interface, unused
*/
public function close(){
}
}
and then attach it to your database, and plumb in the events by type
$eventsManager = new \Phalcon\Events\Manager();
$logger = new \PhalconX\Logger\Adapter\Basic();
$profiler = $phalconDi->getProfiler();
//Listen all the database events
/** #var $event \Phalcon\Events\Event */
/** #var $phalconConnection \Phalcon\Db\Adapter\Pdo\Mysql */
$eventsManager->attach('db', function($event, $phalconConnection) use ($logger, $profiler) {
if ($event->getType() == 'beforeQuery') {
$profiler->startProfile($phalconConnection->getSQLStatement());
$logger->log($phalconConnection->getSQLStatement(), \Phalcon\Logger::INFO, $phalconConnection->getSQLVariables());
}
if ($event->getType() == 'afterQuery') {
$profiler->stopProfile();
}
});
This presumes you have a 'db' key in your dependency injector.
My logger just stores the queries in an array so I can output them at the bottom of my page.
My trick to factor a closest to real SQL statement out of those prepared ones:
function statement2sql($connection) {
$stmt = $connection->getSQLStatement();
foreach ( $connection->getSQLVariables() as $k => $v ) {
// replaces :p1, .. :p11 .. and defined binds with binded values
$stmt = preg_replace('/:' . $k . '([^A-Za-z0-9])/', '\'' . $v . '\'$1', $stmt);
}
return $stmt;
}
Defined as method or function, you can push its result to profiler as in accepted answer:
$eventsManager->attach('db:beforeQuery', function($event, $connection) {
$profiler->startProfile(statement2sql($connection));
}
$eventsManager->attach('db:afterQuery', function($event, $connection) {
$profiler->stopProfile();
}
or store in other way - using logger or other debugging class.
I've had good luck wrapping my SQL execute call in a try/catch, then printing the exception. Any error message returned by MySQL is in the exception's message, which will contain the raw query.
function get_item_by_id ($db_connection, $item_id) {
try {
$stmt = 'SELECT * FROM inventory WHERE id=:id';
$prepared_stmt = $db_connection->prepare ($stmt);
$result = $db_connection->executePrepared ($prepared_stmt,
array (
"id" => $item_id
),
array (
"id" => Column::BIND_PARAM_INT
)
);
$result->setFetchMode (Phalcon\Db::FETCH_OBJ);
$item_arr = $result->fetchAll ();
return $item_arr;
}
catch (Exception $e) {
print_r ($e->getMessage());
}
}
Another option, my personal preference, is to look at the situation from the perspective of the database. Most SQL databases allow you to set a trigger for certain events (in your case, DELETE), and generate a log entry with the full text of the incoming request.
Reference: https://stackoverflow.com/a/10671410/1504367.
This question already has answers here:
Call to undefined method mysqli_stmt::get_result
(10 answers)
Closed 5 years ago.
On my server i get this error
Fatal error: Call to undefined method mysqli_stmt::get_result() in /var/www/virtual/fcb/htdocs/library/mysqlidbclass.php on line 144
And I am having a wrapper like this:
<?php
/* https://github.com/aaron-lord/mysqli */
class mysqlidb {
/**
* Set up the database connection
*/
public function __construct($server,$user,$password,$db){
$this->connection = $this->connect($server, $user, $password, $db, true);
}
/**
* Connect to the database, with or without a persistant connection
* #param String $host Mysql server hostname
* #param String $user Mysql username
* #param String $pass Mysql password
* #param String $db Database to use
* #param boolean $persistant Create a persistant connection
* #return Object Mysqli
*/
private function connect($host, $user, $pass, $db, $persistant = true){
$host = $persistant === true ? 'p:'.$host : $host;
$mysqli = new mysqli($host, $user, $pass, $db);
if($mysqli->connect_error)
throw new Exception('Connection Error: '.$mysqli->connect_error);
$mysqli->set_charset('utf8');
return $mysqli;
}
/**
* Execute an SQL statement for execution.
* #param String $sql An SQL query
* #return Object $this
*/
public function query($sql){
$this->num_rows = 0;
$this->affected_rows = -1;
if(is_object($this->connection)){
$stmt = $this->connection->query($sql);
# Affected rows has to go here for query :o
$this->affected_rows = $this->connection->affected_rows;
$this->stmt = $stmt;
return $this;
}
else {
throw new Exception;
}
}
/**
* Prepare an SQL statement
* #param String $sql An SQL query
* #return Object $this
*/
public function prepare($sql){
unset($this->stmt);
$this->num_rows = 0;
$this->affected_rows = -1;
if(is_object($this->connection)){
# Ready the stmt
$this->stmt = $this->connection->prepare($sql);
if (false===$this->stmt)
{
print('prepare failed: ' . htmlspecialchars($this->connection->error)."<br />");
}
return $this;
}
else {
throw new Exception();
}
}
public function multi_query(){ }
/**
* Escapes the arguments passed in and executes a prepared Query.
* #param Mixed $var The value to be bound to the first SQL ?
* #param Mixed $... Each subsequent value to be bound to ?
* #return Object $this
*/
public function execute(){
if(is_object($this->connection) && is_object($this->stmt)){
# Ready the params
if(count($args = func_get_args()) > 0){
$types = array();
$params = array();
foreach($args as $arg){
$types[] = is_int($arg) ? 'i' : (is_float($arg) ? 'd' : 's');
$params[] = $arg;
}
# Stick the types at the start of the params
array_unshift($params, implode($types));
# Call bind_param (avoiding the pass_by_reference crap)
call_user_func_array(
array($this->stmt, 'bind_param'),
$this->_pass_by_reference($params)
);
}
if($this->stmt->execute()){
# Affected rows to be run after execute for prepares
$this->affected_rows = $this->stmt->affected_rows;
return $this;
}
else {
throw new Exception($this->connection->error);
}
}
else {
throw new Exception;
}
}
/**
* Fetch all results as an array, the type of array depend on the $method passed through.
* #param string $method Optional perameter to indicate what type of array to return.'assoc' is the default and returns an accociative array, 'row' returns a numeric array and 'array' returns an array of both.
* #param boolean $close_stmt Optional perameter to indicate if the statement should be destroyed after execution.
* #return Array Array of database results
*/
public function results($method = 'assoc', $close_stmt = false){
if(is_object($this->stmt)){
$stmt_type = get_class($this->stmt);
# Grab the result prepare() & query()
switch($stmt_type){
case 'mysqli_stmt':
$result = $this->stmt->get_result();
$close_result = 'close';
break;
case 'mysqli_result':
$result = $this->stmt;
$close_result = 'free';
break;
default:
throw new Exception;
}
$this->num_rows = $result->num_rows;
# Set the results type
switch($method) {
case 'assoc':
$method = 'fetch_assoc';
break;
case 'row':
//return 'fetch_row';
$method = 'fetch_row';
break;
default:
$method = 'fetch_array';
break;
}
$results = array();
while($row = $result->$method()){
$results[] = $row;
}
$result->$close_result();
return $results;
}
else {
throw new Exception;
}
}
/**
* Turns off auto-committing database modifications, starting a new transaction.
* #return bool Dependant on the how successful the autocommit() call was
*/
public function start_transaction(){
if(is_object($this->connection)){
return $this->connection->autocommit(false);
}
}
/**
* Commits the current transaction and turns auto-committing database modifications on, ending transactions.
* #return bool Dependant on the how successful the autocommit() call was
*/
public function commit(){
if(is_object($this->connection)){
# Commit!
if($this->connection->commit()){
return $this->connection->autocommit(true);
}
else {
$this->connection->autocommit(true);
throw new Exception;
}
}
}
/**
* Rolls back current transaction and turns auto-committing database modifications on, ending transactions.
* #return bool Dependant on the how successful the autocommit() call was
*/
public function rollback(){
if(is_object($this->connection)){
# Commit!
if($this->connection->rollback()){
return $this->connection->autocommit(true);
}
else {
$this->connection->autocommit(true);
throw new Exception;
}
}
}
/**
* Return the number of rows in statements result set.
* #return integer The number of rows
*/
public function num_rows(){
return $this->num_rows;
}
/**
* Gets the number of affected rows in a previous MySQL operation.
* #return integer The affected rows
*/
public function affected_rows(){
return $this->affected_rows;
}
/**
* Returns the auto generated id used in the last query.
* #return integer The last auto generated id
*/
public function insert_id(){
if(is_object($this->connection)){
return $this->connection->insert_id;
}
}
/**
* Fixes the call_user_func_array & bind_param pass by reference crap.
* #param array $arr The array to be referenced
* #return array A referenced array
*/
private function _pass_by_reference(&$arr){
$refs = array();
foreach($arr as $key => $value){
$refs[$key] = &$arr[$key];
}
return $refs;
}
}
?>
Is there any way to use another function so that I won't have to rewrite whole app? Please tell me if any.
Please read the user notes for this method:
http://php.net/manual/en/mysqli-stmt.get-result.php
It requires the mysqlnd driver. if it isn't installed on your webspace you will have to work with BIND_RESULT & FETCH
http://www.php.net/manual/en/mysqli-stmt.bind-result.php
http://www.php.net/manual/en/mysqli-stmt.fetch.php
Extracted from here
The reason for this error is that your server doesn't have the mysqlnd driver driver installed. (See here.) If you have admin privileges you could install it yourself, but there is also an easier way:
I have written two simple functions that give the same functionality as $stmt->get_result();, but they don't require the mysqlnd driver.
You simply replace
$result = $stmt->get_result(); with $fields = bindAll($stmt);
and
$row= $stmt->get_result(); with $row = fetchRowAssoc($stmt, $fields);.
(To get the numbers of returned rows you can use $stmt->num_rows.)
You just have to place these two functions I have written somewhere in your PHP Script. (for example right at the bottom)
function bindAll($stmt) {
$meta = $stmt->result_metadata();
$fields = array();
$fieldRefs = array();
while ($field = $meta->fetch_field())
{
$fields[$field->name] = "";
$fieldRefs[] = &$fields[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $fieldRefs);
$stmt->store_result();
//var_dump($fields);
return $fields;
}
function fetchRowAssoc($stmt, &$fields) {
if ($stmt->fetch()) {
return $fields;
}
return false;
}
How it works:
My code uses the $stmt->result_metadata(); function to figure out how many and which fields are returned and then automatically binds the fetched results to pre-created references. Works like a charm!
Also posted here.
Doctrine 2 has the Doctrine\ORM\Tools\Pagination\Paginator class which can be used to paginate normal DQL queries.
However if I pass it a native query, I get this error:
Catchable fatal error: Argument 1 passed to Doctrine\ORM\Tools\Pagination\Paginator::cloneQuery() must be an instance of Doctrine\ORM\Query, instance of Doctrine\ORM\NativeQuery given
I've tried removing the type-hinting from the paginator class in the cloneQuery method, but this just gives further errors because other bits of the paginator class expect methods found in Query that aren't in NativeQuery.
Is there any easy way of paginating the native queries without needing to build a new paginator class or fetching every row from the database into an array?
I made my own paginator adapter class compatible with Zend_Paginator.
Probably won't be the most flexible since it relies on there being a " FROM " near the start of the query (see the count() method) but it's a relatively quick and easy fix.
/**
* Paginate native doctrine 2 queries
*/
class NativePaginator implements Zend_Paginator_Adapter_Interface
{
/**
* #var Doctrine\ORM\NativeQuery
*/
protected $query;
protected $count;
/**
* #param Doctrine\ORM\NativeQuery $query
*/
public function __construct($query)
{
$this->query = $query;
}
/**
* Returns the total number of rows in the result set.
*
* #return integer
*/
public function count()
{
if(!$this->count)
{
//change to a count query by changing the bit before the FROM
$sql = explode(' FROM ', $this->query->getSql());
$sql[0] = 'SELECT COUNT(*)';
$sql = implode(' FROM ', $sql);
$db = $this->query->getEntityManager()->getConnection();
$this->count = (int) $db->fetchColumn($sql, $this->query->getParameters());
}
return $this->count;
}
/**
* Returns an collection of items for a page.
*
* #param integer $offset Page offset
* #param integer $itemCountPerPage Number of items per page
* #return array
*/
public function getItems($offset, $itemCountPerPage)
{
$cloneQuery = clone $this->query;
$cloneQuery->setParameters($this->query->getParameters(), $this->query->getParameterTypes());
foreach($this->query->getHints() as $name => $value)
{
$cloneQuery->setHint($name, $value);
}
//add on limit and offset
$sql = $cloneQuery->getSQL();
$sql .= " LIMIT $itemCountPerPage OFFSET $offset";
$cloneQuery->setSQL($sql);
return $cloneQuery->getResult();
}
}
public function countTotalRecords($query, string $primaryKey = '*'): int
{
if ($query instanceof QueryBuilder) {
$paginator = new Paginator($query->getQuery());
return count($paginator);
} else if ($query instanceof NativeQuery) {
$rsm = new ResultSetMappingBuilder($query->getEntityManager());
$rsm->addScalarResult('count', 'count');
$sqlCount = "select count(".$primaryKey.") as count from (" . $query->getSQL() . ") as item";
$count = $query->getEntityManager()->createNativeQuery($sqlCount, $rsm);
if ($query->getParameter('limit')) {
$query->setParameter('limit', null);
}
$count->setParameters($query->getParameters());
return (int)$count->getSingleScalarResult();
}
return 0;
}
If you have a dbal query builder that you have constructed with
$yourDbalQueryBuilder = $connection->createQueryBuilder();
then you can use:
$yourDbalQueryBuilder->setFirstResult(0)
->setMaxResults(100000000)
->execute()
->rowCount();
I have a script that loops through and returns all records in the database table, code below.
PHP:
for($i=0;$i<$group_layer_row;$i++){
$my_layer_string="MyMap_".mb_convert_encoding(mssql_result ($rs_group_layer, $i, 0),"UTF-8","SJIS")."_".mb_convert_encoding(mssql_result ($rs_group_layer, $i, 1),"UTF-8","SJIS");
echo "var ".$my_layer_string.";\n";
}
What I am trying to do is turn this into an argument. Somewhat like this(this is an example, please don’t judge).
PHP:
function getLayers(){
$my_layer_string="MyMap_".mb_convert_encoding(mssql_result ($rs_group_layer, $i, 0),"UTF-8","SJIS")."_".mb_convert_encoding(mssql_result ($rs_group_layer, $i, 1),"UTF-8","SJIS");
$layers="var ".$my_layer_string.";\n";
echo $layers;
}
for($i=0;$i<$group_layer_row;$i++){
getLayers();
}
Any help on this would be very appreciated.
For reference I am including the sql query
$sql= "SELECT * FROM m_group_layer WHERE group_id=\"".$_SESSION["group_id"]."\" ORDER BY display_order";
$rs_group_layer= mssql_query ($sql, $con);
$group_layer_row =mssql_num_rows($rs_group_layer);
EDIT: This is almost the exact same loop just with different output.
for($i=0;$i<$group_layer_row;$i++){
$my_layer_string="MyMap_".mb_convert_encoding(mssql_result ($rs_group_layer, $i, 0),"UTF-8","SJIS")."_".mb_convert_encoding(mssql_result ($rs_group_layer, $i, 1),"UTF-8","SJIS");
echo "".$my_layer_string." = new OpenLayers.Layer.WMS( \"".$my_layer_string."\",\"http://192.0.0.0/cgi-bin/mapserv.exe?map=C:/ms4w/Apache/htdocs/mapserver/data/toyama/toyama_mymap.map&service=WMS&SRS=EPSG:2449&VERSION=1.1.1&format=image/PNG&layers=".$my_layer_string."\", {'layers': '".$my_layer_string."'}, {isBaseLayer: false, visibility: false,opacity:0.5,alpha:true});
map.addLayer(".$my_layer_string.");\n";
}
If I understand you correctly, this is a prime candidate for creating an object. As for making a function out of it, I think it's significantly cleaner to process the db resultset in a for loop. I don't see much benefit to creating a function (as passing the db result back and forth to a function inside a loop is very inefficient). Perhaps you might clarify your reasoning for wanting a function or what you are looking to accomplish?
BUT, if you really wanted to make a function out of it it would pretty much look how you outlined it ...
function getLayer($result_set, $row) {
$str = "MyMap_" . mb_convert_encoding(mssql_result($result_set, $i, 0),"UTF-8","SJIS")
$str .= "_".mb_convert_encoding(mssql_result($result_set, $i, 1),"UTF-8","SJIS");
return "var MyMap_$str;\n";
}
// $con = ...
$sql = "SELECT * FROM m_group_layer WHERE group_id=\"".$_SESSION["group_id"]."\" ORDER BY display_order";
$result = mssql_query ($sql, $con);
$row_count = mssql_num_rows($result);
for($i=0; $i<$row_count; $i++){
echo getLayer($result, $i);
}
UPDATE -- CLASS EXAMPLE
Okay, hopefully this doesn't scare you away. Everyone was afraid of OOP at some point. The important thing is to keep working at it and eventually you'll be like, 'OMG I <3 OOP LIKE GAGA LOVES HER LITTLE MONSTERS!!!'
I tried to document as much as possible. There's only so much you can explain without teaching a semester course :) How to use it is at the bottom of the code.
<?php
/**
* Retrieves layers from the db and provides methods for outputting
*/
class LayerMaker
{
/**
* Our MSSQL database connection
* #var MSSQL connection resource
*/
protected $db_conn;
/**
* Our array of records from the DB
* #var array
*/
protected $records;
/**
* Constructor function
*
* Called when you first instantiate the object. If you specify
* the db_conn, it will go ahead and retrieve the records as
* soon as the object is created.
*
* #param MSSQL connection resource $db_conn
*
* #return void
*/
public function __construct($db_conn=NULL)
{
if ($db_conn) {
$this->set_db_conn($db_conn);
$this->records = $this->query_db();
}
}
/**
* Setter function for protected $db_conn property
*
* You could just as easily create a method in the object
* to create the db connection, but for testing reasons that
* you likely don't care about it's better to inject the
* db connection into our object using a setter function like this.
*
* #param MSSQL link identifier $db_conn
*/
public function set_db_conn($db_conn)
{
$this->db_conn = $db_conn
}
/**
* How we get the records from the database into our object's $results property
*
* #return MSSQL record set on success or FALSE if no db connection is set
*/
protected function query_db()
{
// make sure we've set a database connection to use
// query the db and return the results
$sql = 'SELECT * FROM m_group_layer WHERE group_id="' .
$_SESSION["group_id"] . '" ORDER BY display_order';
return mssql_query($sql, $this->db_conn);
}
/**
* A function to get a count of the rows in our result set
*
* #return int Rows in the result property
*/
public function count_result_rows()
{
if ($this->records) {
return mssql_num_rows($this->records);
}
return 0;
}
/**
* Wrapper for mb_convert_encoding function
*
* #return string
*/
protected function layer_builder($row)
{
$str0 = mb_convert_encoding(mssql_result($this->records, $row, 0),"UTF-8","SJIS")
$str1 = mb_convert_encoding(mssql_result($this->records, $row, 1),"UTF-8","SJIS");
return "var MyMap_$str0_$str1";
}
/**
* Finally, build our layers!
*
* #param int $row Result set row number
*
* #return mixed Layer string if $row specified or Array of all layer strings
* if no specific row requested
*/
public function get_layers($row=NULL)
{
if ($row) {
// if we want one specific row ...
return $this->layer_builder($row);
} else {
// otherwise, give us back an array of all the rows
$layers = array();
for($i=0; $i<$this->count_result_rows(); $i++){
$layers[] = $this->layer_builder($i
}
return $layers;
}
}
/**
* Getter function for protected $records property
*
* Useful because you might want access to the resultset
* outside of the object context.
*
* #return array MSSQL record set
*/
public function get_records()
{
return $this->records;
}
}
// Now this is how you could use it
$conn = (however you retrieve a db connection);
$layer_obj = new LayerMaker($conn);
$layers = $layer_obj->get_layers();
print_r($layers);
?>
I want to see what PDO is preparing without looking into the MySQL logs. Basically the final query it has built right before it executes the query.
Is there a way to do this?
There is no built-in way to do it. bigwebguy created a function to do it in one of his answers:
/**
* Replaces any parameter placeholders in a query with the value of that
* parameter. Useful for debugging. Assumes anonymous parameters from
* $params are are in the same order as specified in $query
*
* #param string $query The sql query with parameter placeholders
* #param array $params The array of substitution parameters
* #return string The interpolated query
*/
public static function interpolateQuery($query, $params) {
$keys = array();
# build a regular expression for each parameter
foreach ($params as $key => $value) {
if (is_string($key)) {
$keys[] = '/:'.$key.'/';
} else {
$keys[] = '/[?]/';
}
}
$query = preg_replace($keys, $params, $query, 1, $count);
#trigger_error('replaced '.$count.' keys');
return $query;
}
This is just a derivation of #Maerlyn code above which accept non-asociative arrays for params like and where if the key starts already with ':' don't add it.
/**
* Replaces any parameter placeholders in a query with the value of that
* parameter. Useful for debugging. Assumes anonymous parameters from
* $params are are in the same order as specified in $query
*
* #param string $query The sql query with parameter placeholders
* #param array $params The array of substitution parameters
* #return string The interpolated query
*
* #author maerlyn https://stackoverflow.com/users/308825/maerlyn
*/
function interpolateQuery($query, $params) {
$keys = array();
# build a regular expression for each parameter
if (!isAssoc($params)){
$_params = []; // associative array
foreach($params as $param){
$key = $param[0];
$value = $param[1];
// $type = $param[2];
$_params[$key] = $value;
}
$params = $_params;
}
foreach ($params as $key => $value) {
if (is_string($key)) {
$keys[] = '/'.((substr($key,0,1)==':') ? '' : ':').$key.'/';
} else {
$keys[] = '/[?]/';
}
}
$query = preg_replace($keys, $params, $query, 1, $count);
#trigger_error('replaced '.$count.' keys');
return $query;
}