Get the Actual SQL of a Prepared Statement with mysqli? [duplicate] - mysqli

This question already has answers here:
Is there a way to see a prepared query as it will be executed on the database? [duplicate]
(4 answers)
Closed 4 years ago.
Is there any way to get the actual SQL that is the result of preparing a statement when using the mysqli extension?
My problem:
I am using prepared statements. In all cases, they SHOULD update a record. I am not catching any errors. However, when I check for affected rows, there are none. So, I want to see the actual SQL that would be executed as a result of the prepare statement.
Is there any way to do this? I've check the mysqli reference docs, but they don't seem to have anything.

While I was looking for a Mysqli specific answer I found that all refer to PDO only thus not addressing the issue with using the ? placeholder.
So here I post my contribution of a simple function to replace all the ? for the parameters. (PHP 7)
function addParamsToSQL ( string $SQL, array $params ) : string {
foreach($params as $value)
$SQL = preg_replace ( '[\?]' , "'" . $value . "'" , $SQL, 1 );
return $SQL;
}

Related

Powershell response not expected on -contains [duplicate]

This question already has answers here:
powershell contains not working
(5 answers)
Closed 5 years ago.
I'm trying to create a powershell script that has an if statement depending on what a variable starts with basically.
I have this code:
if($content -contains "fail*") {
#Not all ID's exist/could not be created. pop up error code :(
"match"
} else {
#At this point, we should have a list of hardware id's identifier from our database.
"no match"
}
The powershell $_POST's data to my server, for a response. If that response starts with fail it should go down the first branch, if it returns anything else, it should go down the other branch.
My PHP code can only return 1 result right now, as I was testing this. This is my php code:
<?
include("db-connector.php");
echo "fail - ".$_POST['device'];
?>
The included file contains no output. As you can see, the result should ALWAYS go down the fail branch, but it actually doesn't. Why am I getting this result?
Consider using -like if you're using a wildcard to compare to.
about_Comparison_Operators

security for a simple php search form

I have a table that lists movies and I have incorporated a simple search function.
I have one text field in a form where a title or keyword can be entered and then the form is submitted.
php/mysql code that does the work is:
$find = $_POST['find'];
$find = mysql_real_escape_string($find);
$find = htmlspecialchars($find);
$sql = "SELECT * FROM tbl_buyerguide WHERE rel_date BETWEEN NOW() AND DATE_ADD(now(), INTERVAL 2 MONTH) AND title LIKE '%".$find."%' ORDER BY title";
where 'find' is the name of the text input in the search form.
This works well enough for the search functionality for the required purpose.
My question to all is:
Is the mysql_real_escape_string and htmlspecialchars enough to make my search form secure?
I have read all of the questions that I can find on stackoverflow about this, but I would really like someone in the know to just say to me "yes, that is all you need", or "no, you also need to take into account ...".
Thanks in Advance.
Cheers Al.
Remember the adage: Filter In, Escape Out.
You're not outputting the term there, so why are you escaping it for HTML purposes with htmlspecialchars()?
Instead, ONLY escape it for the database (you should be using prepared statements, but that's another point). So you should not be using htmlspecialchars there.
Instead, when you go to output the variable onto the HTML page, that's when you should escape it for HTML (again, using htmlspecialchars).
Right now, you're mixing database and html escaping, which is going to lead to neither being effective...
Yes it is enough to make it secure....you could always throw strip_tags() in there as well....
Although I would just do it in one line...instead of using three
$find = htmlspecialchars(mysql_real_escape_string($_POST['find']));
But to really make it secure and up to date, you should stop using mysql_* functions as they are deprecated, and will be removed in any future relases of PHP....
You should instead switch to either mysqli_* or PDO, and implement prepared statements which handles security for you.
Example...in PDO
$db = new PDO('mysql:server=localhost;dbname=test', 'username', 'password');
$find = $_POST['find'];
$query = $db->prepare('SELECT * FROM tbl_buyerguide WHERE rel_date BETWEEN NOW() AND DATE_ADD(now(), INTERVAL 2 MONTH) AND title LIKE :like ORDER BY title');
$query->bindValue(':like', '%' . $find . '%');
$query->execute();

SSIS - Passing Parameters to an ADO .NET Source query

I know this has been asked earlier.
Most of the answers were not relevant.
Google, shows that the solution is to configure the expression in the "data flow task" and set the query.
However in the ADO .NET source, when I try to preview the output I keep getting "Must declare the variable '#'"
It does not show the full variable in this error - "#[User::GLOBAL_PARAMETER]"
I think that's because "[USER::" isn't the correct syntax inside a SQL; but then how does one set it ?!
From your description it seems like you are having an error due to using the variable name inside the query string as opposed to the processed variable value. In other words:
"SELECT * FROM #[User::TABLE]" in the expression builder would be WRONG
"SELECT * FROM " + #[User::TABLE] would be CORRECT
It would help if you shared the expression you are using as a query

php5.3 - mysqli_stmt:bind_params with call_user_func_array warnings [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is it possible to pass parameters by reference using call_user_func_array()?
I have the following line of code which worked in PHP 5.1, but isn't working in PHP 5.3.
$input = array('ss','john','programmer');
call_user_func_array(array($mysqli_stmt, 'bind_param'), $input);
In PHP 5.3, I get the following warning message:
Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given in /var/www/startmission/em/class/cls.data_access_object.php on line 785
I changed the code to the following and it worked:
$a = 'johnl';
$b = 'programmer';
$mysqli_stmt->bind_param('ss',$a,$b);
I found this in the php documentation:
Care must be taken when using mysqli_stmt_bind_param() in
conjunction with call_user_func_array(). Note that
mysqli_stmt_bind_param() requires parameters to be passed by reference,
whereas call_user_func_array() can accept as a parameter a list of
variables that can represent references or values.
So my question is, how do I replicate the functionality of the call_user_func_array + bind_params such that i can dynamically bind variables at run time?
I found the answer to my problem in a user note by fabio at kidopi dot com dot br3 years ago on the PHP manual page of mysqli_stmt::bind_param() (slightly modified):
I used to have problems with call_user_func_array and bind_param after migrating to php 5.3.
The cause is that 5.3 requires array values as reference while 5.2 worked with real values (but also with references). So I created a secondary helper function to help me with this:
function refValues($arr)
{
$refs = array();
foreach ($arr as $key => $value)
{
$refs[$key] = &$arr[$key];
}
return $refs;
}
and changed my previous function from:
call_user_func_array(array($this->stmt, "bind_param"), $this->values);
to:
call_user_func_array(array($this->stmt, "bind_param"), refValues($this->values));
This way my db functions keep working in PHP 5.2/5.3 servers.

How can I use a stored procedure in a MySql database with Zend Framework?

I'm recently have learned to use Zend Framework. I did a simple CRUD application. But now I want to use a existing database for a more complex application and I want to know how I call a stored procedure in the Model, how to send parameters, how to read the results and store them in an array in PHP. Please. I appreciate any kind of help :)
It's not too hard. Here's an example of a MySQL stored procedure with an IN parameter, an OUT parameter, and a result set:
CREATE PROCEDURE MyProc(IN i INTEGER, OUT o INTEGER)
BEGIN
SELECT i+10 INTO o;
SELECT i, o;
END
You can call this with the query() method, and pass a parameter:
$stmt = $db->query("CALL MyProc(?, #output)", array(25));
print_r( $stmt->fetchAll() );
The trick is that MySQL stored procs might return multiple result sets (if the proc had multiple SELECT queries for instance). So the API must advance through all result sets before you can execute another SQL query. Or else you get the "Commands out of sync" error.
If you use the PDO_MySQL adapter:
while ($stmt->nextRowset()) { }
If you use the MySQLi adapter, you'll find that Zend_Db_Statement_Mysqli doesn't implement nextRowset(), so you have to call the internal mysqli connection object:
while ($db->getConnection()->next_result()) { }
Once you clear the result sets, you can run subsequent SQL queries, for example to fetch the value of the procedure's OUT parameter:
$stmt = $db->query("SELECT #output");
print_r( $stmt->fetchAll() );
Great answer from Bill. Just for completeness, if you encounter:
SQLSTATE[HY000]: General error: 2053
When using this method to get a result set from your procedure, check your arguments. I refactored a method and was passing NULLs as arguments to the procedure as the variables I'd used were out of scope. Once I'd fixed this silly mistake the problem went away (to be replaced by another):
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other
unbuffered queries are active. Consider using PDOStatement::fetchAll().
I'm using $stmt->fetchAll() though. I switched to using prepare() and execute() in place of query(). Switching to mysqli from pdo_mysql in my Zend_Db config finally got things working for me. I found this information from the following SO question:
Call Multiple Stored Procedures with the Zend Framework
If someone is looking for ZendFramework 2 \ Zend Expressive using Zend\Db :
There is another way to do this using createStatement() method.
// prepare create statement from adapter
$stmt = $this->getAdapter()->createStatement();
$stmt->prepare('CALL myproc("myVal")');
// execute sql query
$records = $stmt->execute();
// manipulate results
if ($records instanceof ResultInterface && $records->isQueryResult()) {
$resultSet = new ResultSet;
$resultSet->initialize($records);
// return records if found
if (count($resultSet)) {
// return array of result set
return $resultSet->toArray();
}
// if no records found
return array()
}
$db = Zend_Db_Table::getDefaultAdapter();
$stmt = $db->query("CALL procedure()");
$data = $stmt->fetchAll();