First I have to say that I am a total newbie, I have literally 0 experience with PHP.
Here is my problem. I have a sensor, that sends data into mysql database in following form:
http://192.168.1.2/add.php?i=mit=0106,22:5113/07/2016,liv=175cm,livp=000%,b=12.0V,t=36;
Now I am able to display this in my mysql table:
"mit=0106,22:5113/07/2016,liv=175cm,livp=000%,b=12.0V,t=36;"
but I would like to display each argument separately.
Do you know how to change the separator from "&" to ","?
Ideal solution would be to change the url command to this form:
http://192.168.1.2/add.php?i=mit=0106&22:5113/07/2016&liv=175cm&livp=000%&b=12.0V&t=36;
but unfortunately I can reprogramm the sensor, so I need to change the separator from "&" to ",".
arg_separator.input is the configuration directive you are looking for:
arg_separator.input string
List of separator(s) used by PHP to parse input URLs into variables.
Note:
Every character in this directive is considered as separator!
Be aware the setting mode is PHP_INI_PERDIR, meaning it "can be set in php.ini, .htaccess, httpd.conf or .user.ini (since PHP 5.3)" (http://php.net/manual/en/configuration.changes.modes.php)
If you can't change this setting, you might look at the query string as a whole (see $_SERVER variable), and split it at the comma yourself, using explode or something like that.
If I got it right, you have to store all name=value pairs from that string into separate columns in database table.
In this case you can't use explode() because of first value that contains comma.
Assuming that you already have created columns called mit, liv, livp, b and t with required data-type, and your string is double-checked before it goes to database to avoid SQL injections, you can do something like this:
# your input string
$input = "mit=0106,22:5113/07/2016,liv=175cm,livp=000%,b=12.0V,t=36;";
# loop through it and determine all name=value pairs
while (strlen($input)>2) {
preg_match ('/([a-z]+)\=(.*?)(?:,[a-z]+=|;)/', $input, $m);
# store names here
$d1[] = "'{$m[1]}'";
# and values here
$d2[] = "'{$m[2]}'";
$input = substr($input, strlen($m[1]) + strlen($m[2]) + 2);
}
# join arrays into string
$d1 = join(",", $d1);
$d2 = join(",", $d2);
# and put them into query
$sql = "INSERT INTO mytable ($d1) VALUES ($d2);";
echo $sql;
This will print out a query like this
INSERT INTO mytable ('mit','liv','livp','b','t')
VALUES ('0106,22:5113/07/2016','175cm','000%','12.0V','36');
How that while loop works?
It uses $input as argument and look for name=value followed by another name= (for inner pairs) or ; (for last pair) to determine its end. Than it extracts name into separate array d1 and value into another array called d2. Removes first match from the beginning of the string and takes another turn in loop until the $input string is empty. Course, elements into those two arrays are stored surrounded with single quotes for later use in query.
At the end, I joined both arrays (separately) with comma between elements and put them into query string called $sql.
Please note (again) that it's dangerous to send data this way directly from URI's GET parameter into database with no previous validation of data.
Not sure what you mean exactly but you can use str_replace() to help you or possibly you can convert this into an array using explode() then do what you need to do with the data and put it back into a string using implode().
edit: thanks, fixed the mixup.
echo "http://192.168.1.2/add.php?i=" . str_replace(",","&","mit=0106,22:5113/07/2016,liv=175cm,livp=000%,b=12.0V,t=36;");
Related
This question already has answers here:
Is storing a delimited list in a database column really that bad?
(10 answers)
Closed 4 years ago.
I need to store a comma delimited string (array of urls) inside mysql table.
for example:
"https://google.com,https://yahoo.com,https://something.com"
fetching this from the table inside php I'm using explode function to get an array.
$arr = explode(',', $string);
Problem is because some url can contain comma character inside itself and this can produce confusion.
In fact, url can contain any character, escaped or not - it will produce error in explode function.
Any help?
You can use urlencode()
$stupidCommaUrl = 'http://why.com/is,there/a/comma';
echo urlencode($stupidCommaUrl);
// outputs http%3A%2F%2Fwhy.com%2Fis%2Cthere%2Fa%2Fcomma
You can use urldecode() to convert it back.
Your DB design sounds flawed. As Nigel said in the comments above, look into database normalisation.
Try to use a set of characters that you will never find in a url like $&$ to separate your values, that will act as a comma, so when you retreive the values you will do this: $arr = explode('$&$', $string);
You can also build an array and use json_encode and save the string, you will get rid of the explode function, example:
$arrayOfUrls = [your array];
$urlsInJson = json_encode($arrayOfUrls);
Then store $urlsInJson in database
To retrieve your data you will use
$arrayOfUrls = json_decode($yourQueryResult['URLS'])
Hope it helps.
# Check arrary not empty
if (!empty($results)) {
$this->code($results);
// got the mail code from database
// which is PG-000001
// how do i add , like something PG-000001 ++
}
this will return a result from database , my intention is to keep adding up the code that return from my database and the update back to the database.
now it was return PG-000001, how do i make it add up and be like PG-000002 and then update it and next time it will be PG-000002 and up to 000003 and so on.
how do i add up the text PG-000001?
If all of your codes look like this, then your really shouldn’t store them that way. It appears that the PG- at the beginning is just a prefix. If you store the actual value as an integer, you can increment as much as you like.
Anyway, the solution to your question is that you will need to
split the string
increment the second part
zero-pad the second part
combine again
Here is a little test script:
$test='PG-000001';
$pattern='/(.*-)(\d+)/';
preg_match($pattern,$test,$matches);
list(,$prefix,$value)=$matches;
$value=sprintf('%06d',$value+1);
$test="$prefix$value";
print $test;
Translation:
/(.*-)(\d+)/ is the pattern that will split the string into the prefix & numeral
preg_match applies the pattern and returns the result into the array $matches.
$matches has the original string, and then the two matches
list() copies elements of the array into variables. The leading comma skips the first element
sprintf formats the data. In this case, the code 0-pads to 6 digits
the double-quoted string is a simple way of recombining your data.
I have a column in my database that stores a string of numbers, separated by commas.
,,133,,,,444,,,,555,,,,6,
Rules:
The first number in the string is always preceded by 2 commas
There are always 4 commas between the middle numbers
The last number only has 1 comma after it
The example above is how I always want the string to look..
What happens is when some of these numbers are removed the updated string looks like this:
,,31,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,998,,,,476,,,,,
Making it look messy in the database and sometimes causing trouble with the extra commas when I try to output each number
I've been manually updating each value to follow the format I want but I'd like to make a script that runs each night and takes each of these strings and updates them with the correct format following the rules I listed above.
What can I use to format the string to follow the rules above?
You could create a php script that loads the values from the database, manipulate the rows, and store the manipulated values back to the database. I don't know what database and table structure you use, but the manipulation part is simple:
// load the string from the database into the $value variable
$numbers= preg_split("/,+/", $value); // split the string
$numbers= array_filter( $numbers); // remove empty array elements
$newvalue = implode(',,,,', $numbers); // join the array elements to a string separated by ,,,,
$newvalue = ',,' . $newvalue . ','; // add ,, at the beginning and , at the end of the new value
// store $newvalue in the database
I'm trying to change a variable name in a query string, so it's usable by my PHP code.
The query gets posts from an external system, so I can't control that they are posting a variable name with a space in it. And that makes it impossible for me to use the PHP $_GET function.
I need to change variable%20name to ?new1
And I need to change variable2 to new2
There are many variables passed in the query, but only these two need to be changed. The rest can stay the same or even disappear.
So ?variable%20name=abc&variable2=xyz
Needs to end up as ?new1=abc&new2=xyz
Also, they may not be in this order and there may be more variables
So ?variable%20name=abc&blah=123&blah2=456&variable2=xyz
Could end up as ?new1=abc&new2=xyz
OR as ?new1=abc&blah=123&blah2=456&new2=xyz
Either way would be fine!
Please give me the mod_rewrite rule that will fix this.
Thank you in advance!
Parsing the query string with mod_rewrite is a bit of a pain, has to be done with RewriteCond and using %n replacements in a subsequent RewriteRule, probably easier to manually break up the original query string in PHP.
The full query string can be found (within PHP) in $_SERVER['QUERY_STRING'].
You can split it up using preg_split() or explode(), first on &, then on =, to get key/value pairs.
Using custom%20cbid=123&blahblahblah&name=example as an example.
$params = array();
foreach (explode("&", $_SERVER['QUERY_STRING']) as $cKeyValue) {
list ($cKey, $cValue) = explode('=', $cKeyValue, 2);
$params[urldecode($cKey)] = urldecode($cValue);
}
// Would result in:
$params = array('custom cbid' => 123,
'blahblahblah' => NULL,
'name' => example);
I know the title isn't very clear. I'm new to PHP, so there might be name for this kind of thing, I'll try to explain as best as I can. Sometimes in a URL, when using PHP, there will be a question mark, followed by data. I'm sorry, I know this is very noobish, but I'm not sure what it's called to look for a tutorial or anything. Here is what I mean:
http://www.website.com/error_messages.php?error_id=0
How do you configure it to display different text depending on what the number is (in this example it's a number)
Could somebody please tell me what this is called and how I could do this? I've been working with PHP for a couple days and I'm lost. Thank you so very much for understanding that I am very new at this.
That "data" is the URL querystring, and it encodes the GET variables of that HTTP request.
Here's more info on query strings: http://en.wikipedia.org/wiki/Query_string
In PHP you access these with the $_GET "super-global" variable:
// http://www.website.com/error%5Fmessages.php?error%5Fid=0
// %5F is a urlencoded '_' character, which your webserver will most likely
// decode before it gets to PHP.
// So ?error%5Fid=0 reaches PHP as the 'error_id' GET variable
$error_id = $_GET['error_id'];
echo $error_id; // this will be 0
The querystring can encode multiple GET variables by separating them with the & character. For example:
?error_id=0&error_message=Something%20bad%20happened
error_id => "0"
error_message => "Something bad happened"
In that example you can also see that spaces are encoded as %20.
Here's more info on "percent encoding": http://en.wikipedia.org/wiki/Percent-encoding
The data after the question mark is called the "query string". It usually contains data in the following format:
param1=value1¶m2=value2
Ie, it is a list of key-value pairs, each pair separated with the ampersand character (&). In order to pass special characters in the values, they have to be encoded using URL-encoding format: Using the percent sign (%) followed by two hexadecimal characters representing the character code.
In PHP, parameters passed via the query string are automatically propagated to your script using the super-global variable $_GET:
echo $_GET['param1']; // will produce "value1" for the example above.
The raw, unprocessed query string can be retrieved by the QUERY_STRING server variable:
echo $_SERVER['QUERY_STRING'];
It's called the query string.
In PHP you can access its data via the superglobal $_GET
For example:
http://www.example.com/?hello=world
<?php
// Use htmlspecialchars to prevent cross-site scripting attacks (XSS)
echo htmlspecialchars($_GET['hello']);
?>
If you want to create a query string to append to a URL you can use http_build_query():
$str = http_build_query(array('hello' => 'world'));
As previously described, the data after the ? is the querystring (or GET data), and is accessed using the $_GET variable. The $_GET variable is an array containing the name=value pairs in the querystring.
Here is a breif description of $_GET and an example of it's usage:
http://www.w3schools.com/php/php_get.asp
Data can also be submited to a PHP script as POST data (found in the $_POST variable), which is used for passwords, etc, and is not stored in the URL. The $_REQUEST variable contains both POST and GET data. POST and GET data usually originates from being entered into a web form by a user (but GET data can also come directly from a link to an address, like in your example). More info about using web forms in PHP can be found here:
http://www.w3schools.com/php/php_forms.asp
its called "query string"
and you can retrieve it via $_SERVER["QUERY_STRING"]
or you can loop through $_GET
in this case the error_id, you can check it by something like this
echo $_GET['error_id'];
The term you are looking for is GET. So in php you need to access the GET variables in $_GET['variable_name'], e.g. in the example you gave $_GET['error_id'] will contain the value 0. You can then use this in your logic to echo back different information.
The bit after the question mark is called a Query String. The format is typically, although not necessarily always, key-value pairs, where the pairs are separated by an ampersand (&) and the value is separated from the name by an equals sign (=): ?var1=value1&var2=value2&.... Most web programming environments provide an easy way to access name-value pairs in this format. For example, in PHP, there is a superglobal, which is an associative array of these key-value-pairs. In your example, error_id would be accessible via:
$_GET['error_id']
The reason for the name "GET" is that query string variables are typically associated with a HTTP GET request. POST requests can contain GET variables too, whereas GET requests can't contain POST variables.
As to the rest of your question, you could approach the text issue in a number of ways, the simplest being switching on the error id:
$error_id = isset($_GET['error_id']) ? $_GET['error_id'] : 0;
switch($error_id) {
case 1:
echo "Error 1";
break;
default:
echo "Unknown Error";
break;
}
and more complex ways involve looking up the error message from a file, database or what have you.