Can I get a quick reality check?
The idea that I'm working on is that I have text in a HTML template that looks like {Field1} and I want to populate the values for that field from a MySQLi connection where the database field is Field1.
So in theory I should get the data in an array, then cycle through that array, (adding {} and) replacing the text in the HTML with the required values.
Is there a more elegant solution to my task here or is what I'm planning pretty much it?
Does anyone have any advice or tutorials on handling the associated array returned by MySQLi? Much appreciated. I'm still learning and I'm just banging my head on this problem for a bit too long.
Without seeing your source for PHP, it is VERY difficult to answer this question,
I believe what you want to do can be achieved using *array_map*
Following would add the braces as you wish around each element in the array
// $row = .... your getter from mysqli connection
$row = array_map("apply_braces", $row);
// end of loops and stuff -- begin functions below
function apply_braces($field) {
return '{' . $field . '}';
}
The above will set all values in $row, to "{" . $somevalue . "}", so whatever the value of the item in the array is, it will add the braces around it using the custom function.
Sure.
Check failed.
Do not re-invent the wheel.
Your idea on templates is wrong. Please learn how to use already existing templating systems before trying to create your own.
Does anyone have any advice or tutorials on handling the associated array returned by MySQLi?
Definitely NO.
Simply because there is absolutely nothing special in the associative arrays returned from mysql. They are exactly the same as any other associative array in PHP, no difference.
Related
Cutting out some of the code on the innermost foreach, I'm trying to change HERE to make it so that it alters the original value. I want to pass a pointer basically and alter it. I was able to kind of do this with the &$ keyword in the foreach but (as the docs state) it results in some buggy behavior and I'm trying to do it the way they, and others on SO suggest. The problem is all the examples I find are for a single foreach, not for nested.
The following code loops properly but when I get to the HERE it doesn't actually alter the original value. Also worth mentioning that $sources could be an array of arrays (by index) or an array of key values. This looping code seems to iterate over both fine though, just not overriding the original value of $sources
fwiw, on top of the &$ I also tried:
$sources[$sourceKey][$rowKey][$cellKey] = $date->format('m/d/Y');
Which $sources[$sourceKey][$rowKey][$cellKey] returns the right value if I print it but it still doesn't overwrite the original array.
function convertDates($sources) {
foreach($sources as $sourceKey => $sourceValue){
foreach ($sourceValue as $rowKey => $rowValue) {
foreach ($rowValue as $cellKey => $cellValue) {
HERE = $date->format('m/d/Y');
}
}
}
}
I never could get this to work correctly since there were two formats this loop could get (JSON encoded object and an array). Making it work for both was much harder than just doing it in JavaScript so instead of modifying on the server I format the data how I want client side and send it up. This formatting is purely presentational and for personal use so if someone were to put in a debugger and change the code to send a different format thats fine and there's no security issues.
So in the end, this code was rewritten in JS and since JS handles arrays and objects using the same pointers the above issue wasn't an issue any longer.
I'm working with Zend Framework 2's session manager in PHP, and want to unserialize the session data so I can change the way the data is stored. I thought regex was the way to do it, but I can't figure out how to make sure the regex is right for this type of string.
Sample input:
__ZF|a:2:{s:20:"_REQUEST_ACCESS_TIME";d:1099999999.9999999999999999999999;s:6:"_VALID";a:1:{s:25:"Zend\Session\Validator\Id";s:26:"xxxxxxxxxxxxxxxxxxxxxxxxxx";}}initialized|C:23:"Zend\Stdlib\ArrayObject":403:{a:4:{s:7:"storage";a:3:{s:4:"init";i:1;s:10:"remoteAddr";s:13:"127.000.00.01";s:13:"httpUserAgent";s:114:"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";}s:4:"flag";i:2;s:13:"iteratorClass";s:13:"ArrayIterator";s:19:"protectedProperties";a:4:{i:0;s:7:"storage";i:1;s:4:"flag";i:2;s:13:"iteratorClass";i:3;s:19:"protectedProperties";}}}
Expected output:
'__ZF|a:2:{s:20:"_REQUEST_ACCESS_TIME";d:1099999999.9999999999999999999999;s:6:"_VALID";a:1:{s:25:"Zend\Session\Validator\Id";s:26:"xxxxxxxxxxxxxxxxxxxxxxxxxx";}}'
'initialized|C:23:"Zend\Stdlib\ArrayObject":403:{a:4:{s:7:"storage";a:3:{s:4:"init";i:1;s:10:"remoteAddr";s:13:"127.000.00.01";s:13:"httpUserAgent";s:114:"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";}s:4:"flag";i:2;s:13:"iteratorClass";s:13:"ArrayIterator";s:19:"protectedProperties";a:4:{i:0;s:7:"storage";i:1;s:4:"flag";i:2;s:13:"iteratorClass";i:3;s:19:"protectedProperties";}}}'
What I tried:
$pattern = '/\w+\|.*?}}+/'; // this works for the sample input, but may be too general and certainly won't work for serialized data without a nested array
$pattern = '/\w+\|(a:\d+:{.*?}|o:\d+:\"[a-z0-9_]+\":\d+:{.*?})/'; // doesn't capture the `initialized` data
Where I am stuck:
Put generally, I can't figure out the best way to split apart the __ZF data from the initialized data (especially when there are other non-Zend variables in the session). Specifically, I can't figure out what regex to use to get serialized data.
I tried to put an example on RegexPlanet, but couldn't figure out the interface, and it only seemed to produce bizarre results. If it helps, I'm fairly sure ZF PHP produces its serialized session data like this:
$text = "";
foreach ($_SESSION as $key => $value) {
$text .= $key . "|" . serialize($value);
}
...but I haven't found the source code for that.
I found out about ini_set('session.serialize_handler', 'php_serialize'); It changes the serialization to use PHP's regular serialize method instead of the alternate, which solves the problem. – Miryafa
The funny thing is that I can't find a good Explanation for this question.
Is there any disadvantage when I don't use a "while-loop" to fetch a mysql result?
Everywhere I see this line of code:
while ($row = mysql_fetch_array($result)) {
// do something with $row
}
I'm not sure that I have ever seen code that used a foreach-loop to fetch mysql results.
So is there anything wrong with other Loops or is the while-loop the only Loop that is easy and simple to use for it?
I guess there is no performance problem for regular uses with while-loops or foreach-loops with 100-1000 resultsets, isn't it?
I guess the answer is that :
"Foreach" is used when we want to loop through a code for each element in an array.(It handles each element inan array)
"For" is used when we want to loop through a block of code a specified number of times.
"While" : is used to loop through a block of code as long as a special condition is true .
I hope everything is clear for more info you may visit this website : http://www.tutorialspoint.com/php/php_loop_types.htm
I have a long PHP file and I want to copy all the variable names only and build an insert sql query. Is there a way where I can search for a pattern using regular expression and concatenate the find result till I collected all the variable and spit it out in a statement?
I am using TextMate and am familiar with regular expression search. Regex search result give $0,$1 and so forth argument. Do not know if this possible though. Solution in any editor will do not just text mate.
I have just too many variable (+100) don't feel like copy every single one. Here my sample file
$ID = $_POST['id'];
$TXN_TYPE = $_POST['txn_type'];
$CHARSET = $_POST['charset']
$CUSTOM = $_POST['custom'];
You could try something with get_defined_vars(). However this function also lists GLOBAL vars. You can use this snippet to remove them if you don't want them and display only the vars you defined
$variables = array_diff(get_defined_vars(), array(array()));
However this snippet generates Notices and I haven't found a way to solve them yet.
If you've only got $_POST variables you can loop through the $_POST array itself
You create the SQL programmatically while looping through the array.
My own solution is, do the inverse. It is not probably possible.
Leave only the variable names Remove all the rest. Use
[space].+ regex to remove everything that is after the variable name.
clean the file so that only variable names are left. then do a couple more find and replace to bring the variable name in the form you want.
If you're looking to match only the variable names (not the $_POST array indices), then the regular expression is pretty much provided in the PHP documentation:
\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
This will, of course, include $_POST, but that should be easy enough to remove. If not, you could do it with negative lookahead (if TextMate supports it):
\$(?!_POST($|[^a-zA-Z0-9_\x7f-\xff]))[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
What would you say is the most efficient way to get a single value out of an Array. I know what it is, I know where it is. Currently I'm doing it with:
$array = unserialize($storedArray);
$var = $array['keyOne'];
Wondering if there is a better way.
You are doing it fine, I can't think of a better way than what you are doing.
You unserialize
You get an array
You get value by specifying index
That's the way it can be done.
Wondering if there is a better way.
For the example you give with the array, I think you're fine.
If the serialized string contains data and objects you don't want to unserialize (e.g. creating objects you really don't want to have), you can use the Serialized PHP library which is a complete parser for serialized data.
It offers low-level access to serialized data statically, so you can only extract a subset of data and/or manipulate the serialized data w/o unserializing it. However that looks too much for your example as you only have an array and you don't need to filter/differ too much I guess.
Its most efficient way you can do, unserialize and get data, if you need optimize dont store all variables serialized.
Also there is always way to parse it with regexp :)
If you dont want to unseralize the whole thing (which can be costly, especially for more complex objects), you can just do a strpos and look for the features you want and extract them
Sure.
If you need a better way - DO NOT USE serialized arrays.
Serialization is just a transport format, of VERY limited use.
If you need some optimized variant - there are hundreds of them.
For example, you can pass some single scalar variable instead of whole array. And access it immediately
I, too, think the right way is to un-serialize.
But another way could be to use string operations, when you know what you want from the array:
$storedArray = 'a:2:{s:4:"test";s:2:"ja";s:6:"keyOne";i:5;}';
# another: a:2:{s:4:"test";s:2:"ja";s:6:"keyOne";s:3:"sdf";}
$split = explode('keyOne', $storedArray, 2);
# $split[1] contains the value and junk before and after the value
$splitagain = explode(';', $split[1], 3);
# $splitagain[1] should be the value with type information
$value = array_pop(explode(':', $splitagain[1], 3));
# $value contains the value
Now, someone up for a benchmark? ;)
Another way might be RegEx ?