get the values of a form field and save in database - php

I have a form in which i use two dimensional array for field names.The fields names are below
myform[message][]
myform[name][]
myform[add][]
it means there are three arrays.Every array has arrays inside it.when i var_dump my form after putting values and submitting it.I get the below structure of 2d array.
array
''message'' =>
array
0 => string 'adnan' (length=5)
1 => string 'khan' (length=4)
2 => string 'salman' (length=6)
''name'' =>
array
0 => string 'khan' (length=4)
1 => string 'kamran' (length=6)
2 => string 'khan' (length=4)
''add'' =>
array
0 => string 'asad' (length=4)
1 => string 'khan' (length=4)
2 => string 'abrar' (length=5)
As you can see the associative array.I want to store the values of message,name and add in a database table having three fields to store the values of message,name and add fields in a single query by using some loop like foreach.
when i use this code
foreach($_REQUEST['myform'] as $val)
foreach($val as $v)
{
echo $v;
}
I get all the values of the array.But i think i am unable to save it to database table
as all the values are in the variable $v.How to store message in a message field,name in name field and add in an add field in a table of a db.
please advice.Thanks

The looping is the easy part.
if (isset($_REQUEST['myform']))
{
foreach($_REQUEST['myform'] as $key=>$value)
{
// DO SOMETHING
}
}
The hard part is knowing what you want to do. You say put it in a database but you don't give any real info about what or where. Just make sure you carefully escape any user input before storing it, or better yet use prepared queries.

Related

PHP Form Data with Multi-dimensional Array

Say I have a form containing an input field with
name="my_options[my_elements][1][name]"
and another with
name="my_options[my_elements][1][category]"
When I submit the form all is well and a new array containing name and category keys/values is added to the my_elements array in the my_options array in the DB.
I can also use name="my_options[my_elements][][name]"
to create a new array within my_options[my_elements]
However I obviously can't then use name="my_options[my_elements][][category]"
as this will put the category value into a further new array.
Is there a way of dynamically keeping track of the position of the new array created with the first [] so that values can be added at that particular level of the multidimensional array?
To clarify, I'm looking to dynamically add elements to the following array:
'my_options' =>
array (size ?)
0 =>
'my_elements' =>
array (size=2)
0 =>
array (size=2)
'name' => 'name 1'
'category' => 'cat 1'
1 =>
array (size=2)
'name' => 'name 2'
'category' => 'cat 2'
`
I wouldn't use array definitions in the html part of your application.
Stick with a input name, like name="category" and in your php file fetch the submitted data and organize it in an array the way you want it.
assuming you use POST as form method:
$category = $_POST['category'];
(don't forget to validate the input)

Accessing Multi dimensional array object in PHP

I have an item object in PHP, which has the following structure on var_dump :
$item->properties:
array (size=1)
1 =>
array (size=4)
'Key1' => string 'Value1' (length=6)
'Key2' => int 1
'Key3' => string 'true' (length=4)
'Key4' => string 'true' (length=4)
I want to access Key, value in a foreach loop and assign Key, value pair to some internal variables, however when i am using the foloowing code to loop pver array of array, i am getting error in accessing the values in the way i want. Here is what i am doing :
foreach($item->properties as $property) {
foreach($property as $value) {
echo $value;
}
}
Anyone have an idea what am i doing wrong, and how can i fix that ?
one of the things you provide to the foreach isn't a a valid argument, as the error says. Find out which of the 2 it is (linenumber) and var_dump that argument to see what type it is (probably "not an array" ).
In the end either $item->properties itself, or the array values of that array (if it is one), so $property is not an array.
It could be, for instance, that maybe the first key of the properties IS an array, but the second isn't? then you could use is_array to check.

Converting array to individual variables

I am using simplehtmldom to parse a webpage and extract a data and then put it in a mysql database. I successfully extracted the data and put it in array but now the problem i am facing is how to convert this array to variable so that I may use it in my database query to insert the record in the specific fields. I want to convert array to individual variables
here is the code
<?php
include("simple_html_dom.php");
$html = file_get_html('abc.html');
$sched = array();
foreach ( $html->find('tr[class=highlight-darkgrey]') as $event ) {
$item['title'] = trim($event->find('td', 1)->plaintext);
$sched[] = $item;
}
var_dump($sched);
?>
and the output is
array (size=6)
0 =>
array (size=1)
'title' => string 'Network admin, field engineer, engineering analyst, sales executive, PA to HR director Required by Telecommunication Company' (length=124)
1 =>
array (size=1)
'title' => string 'Karachi, Hydrabad, Lahore, Rawalpindi, Peshawar, Multan, Faisalabad' (length=67)
2 =>
array (size=1)
'title' => string '5 - 6 Years' (length=11)
3 =>
array (size=1)
'title' => string 'Knowledge of Field' (length=18)
4 =>
array (size=1)
'title' => string '' (length=0)
5 =>
array (size=1)
'title' => string '- Salary and incentives are not full and final. Can be discussed on final interview.
Can please somebody help me in achieving it. Thanks in advance
Well, if this needs to go in specific fields then you can do something like this:
INSERT INTO table_name (column1, column2, column3,...)
VALUES ($sched[0]['title'], $sched[1]['title'], $sched[2]['title'],...);
Php has a function for getting individual variables, extract() http://php.net/manual/en/function.extract.php
However I don't know why you would do that instead of just using a loop to go though your array.
You mean somethign like
foreach($sched as $item) {
$title = $item['title'];
insert_into_db($title);
}
?
Why do you want to move data from one perfectly good location i.e. the array into a scalar variable.
Double your memory usage for no actual reason.
I assume you are going to want to store the title's in a table
So you can :
foreach ( $sched as $one_sched ) {
// do your database update using $one_sched['title'] as the data identifier.
}
Why not use the array values directly? Also to me it makes no sense to build a subarray where every field is called title.
$sched = array();
foreach ( $html->find('tr[class=highlight-darkgrey]') as $event ) {
$sched[] = trim($event->find('td', 1)->plaintext);
}
Then access the values like:
$value0 = $sched[0];
$value1 = $sched[1];
// PDO example
$sth = $dbh->prepare(
'INSERT INTO table VALUES (?, ?, ...)'
);
$sth->execute(array($sched[0], $sched[1], ...));
// or if array count is right
$sth->execute($sched);

how to parse the json array elements using for loop to get the values one by one

i have a json array wherer i would like to pasre the json till the last element by using for loop for that i would like to get the number of array elements in the json array ,i have more than 3 objects in anarray ,so i am confused how to parse the json till the last element,
i can say you the idea
Count($json);
echo count;
for(i=0;i<l=count($json);i++)
{
then print the value of each key
}
i am stuck ,because there is no fixed lenght for the json i am getting as it is a server response it may return one object one may be twice or thrice or many ,so i thought it would be better to do with for loop ,as a json contain more than one json with 3 keys ,such as country can have more than one state,and one state can have more than one district ,plaese help me,i am stuck with question for last 2 days
thank you
An idea :
function printJson($json) {
foreach($json as $index=>$value) {
if(is_array($value)) {
printJson($value);
} else {
echo 'Value :'.$value.'<br />';
}
}
}
$stringJson = "{'location':[{...}]}"; //for example
printJson(json_decode($stringJson));
You can alternatively decode the json tring using json_decode() which will give u a php variable which u can then easily iterate over using php.
eg.
$string = '{"image":"fox.png","puzzlepieces":{"f":{"puzzlepiece":"one","position":"top:121px;left:389px;"},"x":{"puzzlepiece":"three","position":"top:164px;left:455px;"},"o":{"puzzlepiece":"two","position":"top:52px;left:435px;"}}}';
var_dump(json_decode($string));
will output as
object(stdClass)[1]
public 'image' => string 'fox.png' (length=7)
public 'puzzlepieces' =>
object(stdClass)[2]
public 'f' =>
object(stdClass)[3]
public 'puzzlepiece' => string 'one' (length=3)
public 'position' => string 'top:121px;left:389px;' (length=21)
public 'x' =>
object(stdClass)[4]
public 'puzzlepiece' => string 'three' (length=5)
public 'position' => string 'top:164px;left:455px;' (length=21)
public 'o' =>
object(stdClass)[5]
public 'puzzlepiece' => string 'two' (length=3)
public 'position' => string 'top:52px;left:435px;' (length=20)
My xdebug extension is on in WAMP so your var_dump might be a little differently formatted but overall you'd get a php variable from the array which u can iterate using foreach or other loops.
Read more on json_decode here

How to get content from array

I'm total newbie to PHP and Drupal but I fix this simple(?) thingo on my template. I want to get title, date, text and link path from this array? I can't get it out of there. I think its because its in inside of another array and because im noob in PHP I cant get it out of there ? Also I would like to get it to a loop. If theres more content, I would get it as a list or something. I would use foreach for this? Like foreach $contents as $content and so on?
I get this output from this: var_dump($contents);
array
'total' => string '1' (length=1)
'data' =>
array
0 =>
array
'cid' => string '13231' (length=3)
'title' => string 'TITLEBLABLABLA' (length=3)
'body_text' => string 'TEXTBLABLABAL' (length=709)
'created' => string '313131' (length=10)
'created' => string '2010-07-13 14:12:11' (length=19)
'path' => string 'http://goog.fi' (length=72)
Think of accessing multidimensional arrays in the same way you'd access a file in a subdirectory: just reference each level/directory in sequence. Assuming that array is stored in $arr, you'd get the title as follows:
$arr['data']['0']['title']
Here is a basic PHP array tutorial
It comes down to this:
You retrieve an element of an array with []
$array = array( 'a' => 'b');
echo $array['a']; //Prints b;
To loop through a multi-dimensional array and echo date try this...
foreach ($contents as $key => $content) {
echo $content[$key]['created'];
}
If that doesn't work, post the output of print_r($content) in your question so I can't build you exact array. I'm kinda confused over the structure of your array in your question.

Categories