I am getting content from another page, it has two variables, From
and Body
. Both the variables are strings, I am storing both of them in variables.
$number = $_POST['From'];
$body = $_POST['Body'];
the $body
has data like this, MT 80, SP 30, UP 45
I want to make a dictionary or a hashmap of the same. where in MT
is the key and 80
is its value.
I will be later storing them in the database, so can you please tell me how to do this? I am new to PHP.
First of all split all of the comma separated values into an array
$array = preg_split( '/(,\s|,)/', $body);
Now we want to separate the sets of letters and numbers (e.g MT and 80). So we split each of these by the whitespace between them
$result = array();
for($i=0;$i<count($array);$i++){
$temp = explode(" ",$array[$i]);
$result[$temp[0]] = $temp[1];
}
The variable $result will contain the associative array e.g. $result['MT'] = 80; etc
As for the database, I would recommend using PDO(PHP Data Object):
try{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// Make it show exceptions if something goes wrong
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $conn->prepare("INSERT INTO tableName (key, value) VALUES (:key, :value)");
foreach($result as $key => $value){
$query->execute(array(":key"=>$key,":value"=>$value));
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
This example is assuming that you will be using mysql. Obviously you will need to replace $servername, $dbname, $username, $password and tableName with the appropriate values.