Split PHP array and store in MySQL - php

I am really stuck at this part.. I have tried and searched but my mind is exploding because I can't figure it out.
I found this piece of code on the net, and I want to store every array on MySQL separately.
I need the code how to split this array and store each value in MySQL.
This is the output it has now:
Array ( [domain] => dslb-094-219-040-096.pools.arcor-ip.net [country] => NL - Netherlands [state] => Saarland [town] => Schiffweiler )
But I want to store NL - Netherlands in e.g. MySQL table country.
Can someone please help me out?
Here is the code I found:
<?php
$ip='94.219.40.96';
print_r(geoCheckIP($ip));
//Array ( [domain] => dslb-094-219-040-096.pools.arcor-ip.net [country] => DE - Germany [state] => Hessen [town] => Erzhausen )
//Get an array with geoip-infodata
function geoCheckIP($ip)
{
//check, if the provided ip is valid
if(!filter_var($ip, FILTER_VALIDATE_IP))
{
throw new InvalidArgumentException("IP is not valid");
}
//contact ip-server
$response=#file_get_contents('http://www.netip.de/search?query='.$ip);
if (empty($response))
{
throw new InvalidArgumentException("Error contacting Geo-IP-Server");
}
//Array containing all regex-patterns necessary to extract ip-geoinfo from page
$patterns=array();
$patterns["domain"] = '#Domain: (.*?) #i';
$patterns["country"] = '#Country: (.*?) #i';
$patterns["state"] = '#State/Region: (.*?)<br#i';
$patterns["town"] = '#City: (.*?)<br#i';
//Array where results will be stored
$ipInfo=array();
//check response from ipserver for above patterns
foreach ($patterns as $key => $pattern)
{
//store the result in array
$ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : 'not found';
}
return $ipInfo;
}
?>

you can save each part of the array separetely into a mysql database, that shouldn't be the problem.
you can check out this site on how to access mysql from within php:
http://www.tizag.com/mysqlTutorial/mysqlinsert.php
and the sql insert query should help:
mysql_query("INSERT INTO country (country) VALUES(".$ipInfo['country'].") ")

To me, the problem statement is a little vague.
If it's just a single unnested array as cited in the example, then what Petros advised should work, when you add the missing apostrophes so that you'll have the following statement:
mysql_query("INSERT INTO country (country) VALUES('".$ipInfo['country']."') ")
Note the added single-quote after the opening paren and before the closing paren.
My preference when writing SQL statement within PHP code block is by using the heredoc format like the following so that I can see what the SQL statement should be (and eyeball it to see if it's missing something or has typos):
$sql =<<<raw
INSERT INTO country (country)
VALUES ('%s');
raw;
mysql_query(sprintf($sql, $ipInfo['country']));
It's longer, but it helps make the code more legible to me.
If your data is an array of arrays, then you'll want to to create an array of countries first, then use the implode commands to join all the values.

Related

Truncated incorrect DOUBLE value: '12,11''

My POST form sends a value &messages=12,11
I get it using: $messages = $ep->remove($_POST["messages"]);
And my SQL string is:
$query = $db->prepare("DELETE FROM messages WHERE messageID IN ('".$messages."') AND accountID=:accountID");
$query->execute([':accountID' => $accountID]);
And the error appears....
<b>Fatal error</b>: Uncaught exception 'PDOException' with message 'SQLSTATE[22007]: Invalid datetime format: 1292 Truncated incorrect DOUBLE value: '12,11'' in /var/www/vhosts/xxx.xxx/xx/xxx/xx/xxxx/messages.php:17
This code deletes multiple messages from the database. But don't works for me. Any fix?
Remove the quotation marks:
$query = $db->prepare("DELETE FROM messages WHERE messageID IN (".$messages.") AND accountID=:accountID");
Otherwise the value you're sending is 12,11 (which isn't a number as per your database definition), as opposed to 12 and 11, which are both numbers.
Finally, this particular query structure is open to SQL injection. You may want to either sanitise the $messages variable (since it can only include numbers), or create a prepared statement.
For this example, sanitising could work as follows:
$messages = preg_replace('/[^0-9,]/', '', $messages);
//Removes all characters besides numbers and commas
You could also ensure that the list of numeric message IDs always matches the following regex pattern:
$\d+(?:,\d+)*$
That is, the parameter should always be some number, followed by an optional quantity of ,\d+ terms
if (!preg_match("/^\d+(?:,\d+)*$/", $messages)) {
// throw an exception, you are being injected
}
Just to add to the other answer, here is a way to properly prepare all the values
$array = explode(',', '1,2,3,4,5,6');
$keys = preg_replace('/(.+)/', ':v\1', array_keys($array));
print_r($keys);
$sql = "DELETE FROM messages WHERE messageID IN ( ".implode(',', $keys)." ) AND accountID=:accountID";
print_r($sql);
$params = array_combine($keys,$array);
$params['accountID'] = 'foo';
print_r($params);
//$stmt->execute($params);
Output
//print_r($keys);
Array
(
[0] => :v0
[1] => :v1
[2] => :v2
[3] => :v3
[4] => :v4
[5] => :v5
)
//print_r($sql);
DELETE FROM messages WHERE messageID IN ( :v0,:v1,:v2,:v3,:v4,:v5 ) AND accountID=:accountID
//print_r($params);
Array
(
[:v0] => 1
[:v1] => 2
[:v2] => 3
[:v3] => 4
[:v4] => 5
[:v5] => 6
[accountID] => foo
)
Sandbox
It was way too much for a comment.
Basically it takes the keys and using preg replace we can take the sequential number and add a string to it (placeholders have to start with a alpha). Technically the : in the array for execute is optional.
Then we can put that into the query, as it's all generated by PHP because the keys are made from explode. If you have keys from POST, don't use those instead use array_keys(array_values($array)) array values will make the array numerically indexed, then you use those keys.
Next using array combine we can merge those keys back into the original values and put that array into execute
In this case You can do it just with a regex, but I wanted to show something that was useful for more complex cases of IN.

PHP: remove from string_array_A all strings contained in string_array_B

what I need is quite simple (for real php programmers :-D )
I have 2 strings array.
string_array_A contains a set of words contained in a post on my forum
string_array_B contains a set of words I don't want to be indexed in the search engine of my forum (just for db occupation reason).
So I would like to remove, from string_array_A, all the words contained in the string_array_B.
I would do 2 while loop, but maybe there are some high level functions I could use.
Thanks for your help !
array_diff() is probably what you're looking for:
$result = array_diff($string_array_A, $string_array_B);
This will return an array containing values from $string_array_A that are not present in $string_array_B.
Example:
$string_array_A = ['foo','bar','baz'];
$string_array_B = ['baz','bak','qux'];
$result = array_diff($string_array_A, $string_array_B);
print_r($result);
Output:
Array
(
[0] => foo
[1] => bar
)
Demo

PHP adodb COM recordset returning variant:__set_state for dates/times, how can I just get them as strings?

I'm accessing an mssql db in PHP and creating the connection as a new COM() object. My query runs perfectly fine. When I do the query in Microsoft SQL Server 2008, everything looks great, the dates/times show up in columns and are readable.
But when I run the same query and return the results in PHP, I go to iterate through the results like so:
$selected_fields = array("FS.fund_name", "M.media_id", "MT.media_type_name", "modified_date", "file_upload_date", "issued_date", "filename");
//query goes here
$record_set = new COM("ADODB.Recordset");
while(!$record_set->EOF){ //loop through query results and add to inline cache variable
$temp_record = array();
foreach($selected_fields as $fieldname){ //go through fields and add to array
$fieldname_array = explode(".", $fieldname); //separate table and column
$fieldname = $fieldname_array[sizeof($fieldname_array)-1];
$temp_record[$fieldname] = $record_set->fields[$fieldname]->value;
}
print_r($temp_record);
$rs_array[] = $temp_record;
$record_set->movenext();
}
As I print each $temp_record, they end up looking like this:
Array ( [fund_name] => TEST [media_id] => 1001 [media_type_name] => 8937 Tax Forms [modified_date] => variant Object [file_upload_date] => variant Object [issued_date] => variant Object [filename] => form8937test.pdf )
So the dates are some kind of object, and I don't know how to access them in PHP. And when I go to save them as a cache file, they have this value:
variant::__set_state(array())
How can I retrive the date/time in a format that I can then manipulate using PHP? I want to filter them by year, and sort them by most recent.
According to Variant Object documentation, you should be able to access it by
$temp_record['modified_date']->value;
or
$val = (string)$temp_record['modified_date'];
From the same doc:
the variant is converted to a PHP value only when there is a direct
mapping between the types that would not result in a loss of
information. In all other cases, the result is returned as an instance
of the VARIANT class.
So to check if cast is needed, simply check if you have an object of Variant class:
if (is_object($var) && $var instanceof Variant) {
$val = (string)$var;
} else {
$val = $var;
}

PHP BBCode related issue. How to get values between two tags?

I need to do the following for my website.
$comment = "[item]Infinity Edge[/item]<br>[item]Eggnog Health Potion[/item]";
$this->site->bbcode->postBBCode($comment);
The BBCode function is like this:
function postBBCode($string)
{
$string = nl2br($string);
$string = strip_tags($string, '<br></br>');
$string = $this->tagItem($string);
return $string;
}
function tagItem($string)
{
//Get all values between [item] and [/item] values
//Appoint them to an array.
//foreach item_name in array, call convertItems($item_name) function.
//Now, each item_name in array will be replaced with whatever convertItems($item_name) function returns.
//return modified string
}
function convertItems($itemName)
{
// -- I already made this function, but let me explain what it does.
//Query the database with $itemName.
//Get item_image from database.
//Return '<img src="$row['item_image']></img>';
}
Okay, I already asked my questions between functions. I hope you understood what I am trying to do.
Basically, anything between [item] and [/item] tags will be converted into an image, but the image path of each items will be taken from database.
The part I am having hard times is getting values between [item] and [/item] tags correctly. It should be getting all the correct matches it finds, not the first match.
If you use a preg_match_all on $string, you'll get a result set with all the matches:
$results = array();
preg_match_all('#\[item\](.*?)\[\/item\]#', $string, $results);
$results will have an array of results that looks like this:
Array
(
[0] => Array
(
[0] => [item]Infinity Edge[/item]
[1] => [item]Eggnog Health Potion[/item]
)
[1] => Array
(
[0] => Infinity Edge
[1] => Eggnog Health Potion
)
)
Now you should be able to loop through the $results[1] and send it through convertItems.

Return A Single Variable From Array

i am using following script:
http://www.micahcarrick.com/php-zip-code-range-and-distance-calculation.html
To get the details for a ZIP code, I am using this:
$selected = $z->get_zip_details($zip);
$result = implode(",", $selected);
echo $result;
This returns all details of "$zip" :
32.9116,-96.7323,Dallas,Dallas,TX,Texas,214,Central
Could any1 help me to make the script return ONLY the city variable? The FAQ of the script, says the following:
get_zip_details($zip)
Returns the details about the zip code: $zip. Details are in the form of a keyed array. The keys are: latitude, longitude, city, county, state_prefix, state_name, area_code, and time_zone. All are pretty self-explanitory. Returns false on error.
Unfortunately I cant figure out how to get a single value (city). Would appreciate any help!
Thanks!
The functions is returning an array, so we have to store it in a variable.
$selected = $z->get_zip_details($zip);
Next, we can select the key which points to the city. The key is also called city.
echo $selected['city'];
Change this line
$result = implode(",", $selected);
To
$result = $selected['city'];
For future reference, implode() explode() etc. are array functions. So, if you're using them on something then you can print_r() it to see its structure.
If you had done print_r($selected); or var_dump($selected);, you would have gotten something like this as output:
Array ( [x] => 32.9116 [y] =>-96.7323 [city] => Dallas [state] => Texas [etc] => etc )
So you can see the keys of the array to know how to access the individual values.

Categories