How to use values from one stored procedure into another? - php

For eg
I have a SP which give a result when i, CALL A1();
i fetch the result and store in $a.
But when I call another SP CALL A2('$a'); It is not executing. Showing Array() when I run the program

When you compose the SQL command "CALL A2('$a');" in PHP, the parser first expands the $a variable within your double-quoted string literal. However, as documented under Converting to string:
Arrays are always converted to the string "Array"
Therefore PHP interprets the string that is to be sent to MySQL as "CALL AS('Array');", which is obviously the root of your problem. Note also that allowing PHP to expand variables into SQL commands in this fashion is dangerous: see #deceze's blog article The Great Escapism (Or: What You Need To Know To Work With Text Within Text) to understand this better; and then How can I prevent SQL injection in PHP? to understand how variables should (generally) be passed from PHP to SQL.
However, in this case, the fix is not so straightforward. Since MySQL does not have an array datatype, even if you did properly serialise the array then it would only recognise the serial form (which will not be easy to use in your A2 procedure).
It should also be noted that stored procedures don't really "return" anything. Whilst they can output zero or more resultsets, resultsets can't be used as an input to another stored procedure. The normal workaround is to store the resultset (e.g. in a temporary table) and then later access that as required.
That said, it is very rare indeed that such an arrangement is necessary. Usually people attempt such things because they're trying to use SQL as a procedural language, whereas it is a very powerful declarative language. If you explain what it is that your procedures are collectively trying to do, I very much suspect that someone will be able to write a single SQL command to do the whole thing.

Related

How to process strings with embedded variables in Mysql

I am in need of some advice on how to best process code to keep things running efficiently while still returning dynamic strings to the user.
In my particular situation, I have a set of string responses that vary based on a set of six variables. Early in the project, it was easy to simply use nested if and switch statements. However, as the project advances, this set of code is becoming massive. I would very much like find a way to store this information in a database, but I am unaware of a way to do so that doesn't open up the database to vulnerabilities.
A sample script might look like the following:
printf("Let's say for a moment here, that I want to have a script that is something like this where, ". $yourname ." is printed as well as other pieces of information stored from a database such as: ".$yourfavoritefood." or ".$timesinceloggedon.". Clearly this output will be different from person to person.");
Now imagine I have hundreds of these variable driven scripts. Is there a way to SECURELY store scripts in a mysql database so that I can query only the script I need given the program driven variables at the time?
You can store the text you create in the database or in a file and use printf with arguments to output the text, http://php.net/manual/en/function.printf.php,
printf("Let's say for a moment here, that I want to have a script that is something like this where, :s is printed as well as other pieces of information stored from a database such as: :s or :s. Clearly this output will be different from person to person.", [$yourname, $yourfavoritefood, $timesinceloggedon);
By taking all parts that are different for different users into parameters you can find a common string which can be stored where you store translations

MySQL / PHP - Storing parameters in a database table: Good or bad idea?

So far I store all the relevant parameters that I need for my website as variables in a php file; then I point to this file through a requirestatement in each page that needs those parameters.
This is most of times good and easy to mantain, but sometimes I need to change those variables "on the fly" and I feel the need of some sort of web-panel where I can change them even more easily (I'm thinking to a web page with a form to update the parameters).
So I've created a table in my MySQL database to store parameters (basically, this table has two columns: ParamName and ParamValue; I've stored the parameter names as a varchar without the $ sign at the beginning), in order to create the web-panel I've in my mind.
I was thinking to extract all the parameters names and values using this query:
$query=$mysqli->query('select * from parameters');
while($row=mysqli_fetch_assoc($query)) {
$ParamName=$row["ParamName"];
$$ParamName=$row["ParamValue"]; }
Is this a good or a bad idea?
What are the main issues I could encounter doing so (in terms of security, too)?
How deprecable and dangerous is the use of $$ParamName?
I'd better change my mind or can I proceed this way?
EDIT: I changed mysql_ syntax into mysqli_ as suggested.
Using arbitrary values in a database as variable references is highly risky. What you'd want to do is fetch the data from your key/value store into a self-contained associative array and use that instead.
You also do not want to be using mysql_query for anything these days. Please, put that thing away.
If the parameters are all constants that will not be changed over time, it is faster to use a single file that stores them as constants in a simple associative array.
If these parameters will change, using a database that specializes in key-value stores might be more useful for you instead of using a standard relational database.
If you cannot change your database from a relational database, or you are not changing the values often, it would be faster to cache them using something like memcached.

mysqli bind param data types

I’m currently working on a small set of database access and management classes in php. while trying to understand our well known mysqli better, I still fail to understand why and how variable-types defined in mysqli_stmt::bind_param could and would enhance security/utility within the current application.
The advantages of having a mysql statement going on are clear. Query and values are submitted on two different paths and that of course makes the application more secure and more error proof! But what happens to these variables… are these checked prior by php or after on in mysql?
Is it just mysqli being lazy for doing something like?
!is_numeric($v) && ( !is_null($v) || $v != “NULL”) ? “‘$v’” : $v
Or is there any var type definition on the mysql side which I don’t know?
“PREPARE stmt_name FROM … “;
“SET #var1 = 3”;
“SET #var2 = ‘foo’”;
“EXECUTE stmt_name USING #var1, #var2”;
It doesn’t seem there’s much going on this values. quite anything passed as a string is evaluated properly… then why bother?
There’s another side-question even though related to this one: is there any way to replicate mysqli’s way of sending blob string in packets?
Thanks bye
As nobody has given an answer yet... i do have one now! The data-type definition within bind_param does noting more than adding those quotes to the query, although, variables are bound at a lower level than a php script could be ever capable of! formally going though any different path apart from mysqli/pdo would mean to transfer all the data by strings!
thats it, cheers!

what's the point of serializing arrays to store them in the db?

I see that people store arrays as like:
a:6:{i:0;s:5:"11148";i:1;s:5:"11149";i:2;s:5:"11150";i:3;s:5:"11153";i:4;s:5:"11152";i:5;s:5:"11160";}
why can't they just be:
11148,11149,11150,11153...
and have sql "Type" be "Array" ?
this way it's shorter and you can change the values directly in the databse without having to alter "s:" or "i:".
One thing you can't do with CSV notation (1,2,3,4) is represent multi-dimensional arrays.
Neither way is really appropriate though. The data should be normalized into separate related tables. If there's a real need to store serialized data in a database that can't be or doesn't need to be normalized, it should be stored as JSON, which is language independent and smaller.
there is no mysql type array, and the reason is so you can recreate the array easily, if your data was as you showed it not hard but what about a multidimensional array with non numeric keys. Of course this is NOT good db practice in the first place, breaking normilisation
Not all DB servers have an array type (mysql being one)
if you have a csv list, you have to explode it, or loop over it to recreate the array
multi dimensions aren't possible
With serialize and unserialize you are using native php functions that run faster than php based loop constructs etc. serialize and unserialize are the way to go if you absolutely positively have to store an array in the db (like for sessions). Otherwise you may want to reconsider your application design to not store php array in the database. It may cause problems down the road if you try to access the data with a language other than php.
It's because PHP has the serialize() function that takes a PHP array and turns it into a string like the one you quoted above, and then has another function, unserialize(), that takes the array string and converts it back into a PHP array.
This makes it very easy to turn an array into a string when it needs saving in a database and then turn it back into a proper PHP array after you select it from the database later.
See the PHP manual here:
http://php.net/serialize
and:
http://php.net/unserialize
I've not seen this a whole lot. But it's clearly done for implementation ease. Serializing data allows to store quasi binary data.
Your second example is a CSV scheme. This is workable for storing confined string lists. While it's easier to query or even modify within the database, it makes more effort for unmarshalling from/to the database API. Also there is really only limited list support anyway. http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_find-in-set
However, true, the serialized data is unneeded in your example. It's only a requirement if you need to store complex or nested array structures. And in such cases the data blob is seldomly accessed or queried within the database.

Functions in MySQL or PHP

Is it generally better to run functions on the webserver, or in the database?
Example:
INSERT INTO example (hash) VALUE (MD5('hello'))
or
INSERT INTO example (hash) VALUE ('5d41402abc4b2a76b9719d911017c592')
Ok so that's a really trivial example, but for scalability when a site grows to multiple websites or database servers, where is it best to "do the work"?
I try to think of the database as the place to persist stuff only, and put all abstraction code elsewhere. Database expressions are complex enough already without adding functions to them.
Also, the query optimizer will trip over any expressions with functions if you should ever end up wanting to do something like "SELECT .... WHERE MD5(xxx) = ... "
And database functions aren't very portable in general.
I try to use functions in my scripting language whenever calculations like that are required. I keep my SQL function useage down to a minimum, for a number of reasons.
The primary reason is that my one SQL database is responsible for hosting multiple websites. If the SQL server were to get bogged down with requests from one site, it would adversely affect the rest. This is even more important to consider if you are working on a shared server for example, although in this case you have little control over what the other users are doing.
The secondary reason is that I like my SQL code to be as portable as possible. I don't even want to try to count the different flavors of SQL that exist, so I try to keep functions (especially non-standard extensions) out of my SQL code, except for things like SUM or MIN/MAX.
I guess what I'm saying is, SQL is designed to store and retrieve data, and it should be kept to that purpose. Use your serving language of choice to perform any calculations beforehand, and keep your SQL code portable.
Personally, I try to keep the database as simple (to the minimum) with Insert, Update, Delete without having too much function that can be used in code. Stored Proc is the same, contain only task that are very close to persistence data and not business logic related.
I would put the MD5 outside. This will let met have this "data manipulation" outside the storage scope of the database.
But, your example is quite "easy" and I do not think it's bad to have it inside...
Use your database as means of persisting and mantaining data integrity. And leave business logic outside of it.
If you put business logic, any of it, in your database, you are making it more complex to manage and mantain in the future.
I think most of the time, you're going to want to leave the data manipulation to the webserver but, if you want to process databases with regards to tables, relations, etc., then go for the DB.
I'm personally lobbying my company to upgrade our MySQL server to 5.0 so that I can start taking advantage of procedures (which is killing a couple of sites we administer).
Like the other answers so far, I prefer to keep all the business logic in one place. Namely, my application language. (More specifically, in the object model, if one is present, but not all code is OO.)
However, if you look around StackOverflow for (my)sql-tagged questions about whether to use inline SQL or stored procedures, you'll find that most of the people responding to those are strongly in favor of using stored procs whenever and whereever possible, even for the most trivial queries. You may want to check out some of those questions to see some of the arguments favoring the other approach.

Categories