I have a wordpress page where i got a option list filled with an array. Code below:
$option = array("Zomervakantie", "Goede vrijdag", "Vrijdag na HV", "Bijzonder verlof", "Medisch", "Leeftijdsuren", "Bapo-uren", "EHBO-uren", "Compensatieverlof",
"3 en 4e paasdag", "Meivakantie", "Herfstvakantie");
echo "Selecteer hier je type verlof: ";
echo "<br />" . "<br />";
echo "<select id='selectList' name='selectList'>";
foreach ( $option as $list )
{
echo "<option value='" . $list . "'>" . $list . "</option>";
}
echo "</select>";
When i'm trying to insert this the whole query doesn't work anymore.
This is a part of my query: $wpdb->insert('table',array(column=>$_POST['selectList']));
I'm using a wordpress query.
Anyone knows what the correct way to insert this in a database? i'm using phpmyadmin.
Thanks in advance!
My knowledge of wordpress is very limited.
However, this appears to be invalid PHP to me (unless 'column' is a wordpress constant):
$wpdb->insert('table',array(column=>$_POST['selectList']));
Try
$wpdb->insert('table',array('column'=>$_POST['selectList']));
If you don't already, you should get an IDE which points out syntax errors as you type, such as Netbeans or PHPStorm. I assume Eclipse also does this.
You can insert a array directly to database just use these code
$option = array("Zomervakantie", "Goede vrijdag", "Vrijdag na HV", "Bijzonder verlof", "Medisch", "Leeftijdsuren", "Bapo-uren", "EHBO-uren", "Compensatieverlof",
"3 en 4e paasdag", "Meivakantie", "Herfstvakantie");
$wpdb->insert('table',$option);
If you want to store an array in a database, you can serialize it, or encode it in JSON (there is a PHP function for JSON encoding). It becomes a String, which you can store easily.
It works with objects too.
Example :
$array = array("1" => "PHP code tester Sandbox Online",
"foo" => "bar", 5 , 5 => 89009,
"case" => "Random Stuff",
"PHP Version" => phpversion()
);
$string = json_encode ($array);
echo($string);
echo "\n";
$array2 = json_decode($string);
foreach( $array2 as $key => $value ){
echo $key."\t=>\t".$value."\n";
}
Related
hoping someone here might be able to advise on what the syntax should be to get the data in the transactions array within the data object below
{
"data": {
"pages":10,
"current":1,
"token":"1234-1234-1234-1234",
"transactions":[{"id"}]
}
}
im trying to output the data
<?php foreach ($someArray as $key => $value){
echo "<tr><td>". $value[columns][tranid];
echo "</td><td>". $value[recordtype];
echo "</td><td>". $value[columns][trandate];
echo "</td><td>". $value[columns][poref];
echo "</td><td>". $value[columns][ref][name];
echo "</td><td>$". number_format($value[columns][amount], 0.00, '.', ',');
echo "</td><td><a class='woocommerce-button button' href='https://test.com/?a=print&token=". $pmToken ."&i=". base64_encode("PM-" + $value[columns][internalid][internalid]) ."' target='_new'>Print</a>";
echo "</td></tr>";
}
?>
Im so new to PHP Im not sure how to grab the data
I assume in alot of other languages its just a case of
$someArray.transactions would be the way to do it, but I cant figure out how to get it in PHP
If you want to convert object into array, so you should use php function
$object = json_decode(json_encode($array), FALSE);
Lets say your object is:
$obj = '{
"data":
{
"pages":10,
"current":1,
"token":"1234-1234-1234-1234",
"transactions":[{"id"}]
}
}';
$arr = (array)$obj;
var_dump($arr); //This will be displayed as array
Working example:
http://codepad.org/uCIB7kfh
Use json_decode()
In your case, put
$s = '{"key":"value"}'
$someArray = json_decode($s);
before the for loop, you can then add
var_dump($someArray);
to view the structure and fetch the corresponding data value.
PHP noob here. I am using PHP to present a supply order form. The list of supplies that can be ordered are dynamic, so I'm pulling them from a MySQL database. Here is the PHP code that is generating the HTML form fields by looping through the results of the query:
while($row = mysqli_fetch_array($itemresult))
{
echo "<input type='hidden' name='Item_ID[]' value='" . $row['Item_ID'] . "'></TD>";
echo "<TR><TD class='itemdesc'>" . $row['Item_Name'] . " </TD>";
echo "<input type='hidden' name='Item_Name[]' value='" . $row['Item_Name'] . "'></TD>";
echo "<TD>" . $row['Item_Qty'] . " </TD>";
echo "<TD class='itemprice'>" . $row['Price'] . " </TD>";
echo "<input type='hidden' name='Item_Price[]' value='" . $row['Price'] . "'></TD>";
echo "<TD><input type='text' size='3' name='Order_Qty[]'></TD>";
echo "<TD><input type='checkbox' name='Off_Day[]'></TD>";
}
I have no experience using arrays, however it makes sense that I need these form values passed to my process.php file in an array format. For now, the purpose of my process.php is to simply print a list of Item_Name and the associated Order_Qty by themselves, pretty much like:
Pencils 10
Pens 7
and on and on.
Being new to arrays and PHP, I have no idea how to accomplish this in my process.php files and would appreciate some guidance. Thanks!
+++++++++++++++++++++++++++++++++++++++++++++++
*#yknivag*
Thank you! That helps me understand me the structure. I've been testing various foreach examples online, am hitting a roadblock and could use some additional help. My array result looks like this.
[Item_Name] => Array (
[0] => One Item
[1] => Second Item
[2] => Third Item
[3] => Fourth Item )
[Item_Price] => Array (
[0] => 0.00
[1] => 64.50
[2] => 110.00
[3] => 38.45 )
How do I reference a particular value in the array, such as 'Second Item'? I can't seem to figure out the syntax for referencing a particular item. For instance, this statement returns no data.
echo "Item: " . $_POST[Item_Name] . "<BR>";
What would also be helpful, is to know how to display corresponding array items such as 'Second Item' and '64.50' together?
The following foreach loop seems like it should do the trick, however it doesn't return any data either.
foreach ($myarray as $key => $value)
{
echo "<p>".$key." ".$value."</p>";
}
Everything I've read says this should give me what I want, and I'm confused as to why it's returning nothing.
In your process.php file begin with:
<?php
print "<pre>" . PHP_EOL;
print_r($_POST);
print "</pre>" . PHP_EOL;
?>
Then you will see the structure of the data which is being sent back and that should help you to work out how to process it.
Once you have the structure, examine the foreach command.
You want an associative array
array("pencil" => 9.99, "pen" => 3.23, "paper" => 21.11)
If you are submitting your form through AJAX, you would use JavaScript to post the values to your PHP page.
var pencil = document.getElementById("pencil").value;
var pen = document.getElementById("pen").value;
var paper = document.getElementById("paper").value;
$.post("process.php", {pencil: pencil, pen: pen, paper: paper});
On your "process" page, you would grab the values that were posted
$pencil = $_POST["pencil"];
$pen = $_POST["pen"];
$paper = $_POST["paper"];
then build your array with the following
$myarray = array("pencil" => $pencil, "pen" => $pen, "paper" => $paper);
Edit
In your WHILE loop, build yourself an array by putting this at the end
$myarray[$name] = $price;
Then outside of the loop, encode your array into a JSON object
$myjson = json_encode($myarray, JSON_HEX_APOS);
Now that you have a JSON object, you'll need to grab it in JavaScript
var myjson = <?php echo $myjson; ?>;
Then you can do whatever you want with the key / value pairs
for(var key in myjson){
var item_name = key;
var item_price = myjson[key];
//where the magic happens
}
$icecream = array (
"Choco" => array('2 Dollars'),
"Mango" => array('3 Dollars')
);
print $icecream[0][0];
expected output:
2 Dollars
Edit: I have a huge list of icecream sorts and i do want to use a loop to output all the information as a HTML DOM. So I do not want to go through each array value and echo it with the explicit value (i.e. 'Choco', 'Orange', etc...).
I want to use values as keys for the "first array level" ($icecream[0]),
It does output nothing at all. What is my logical flaw with this solution?
try this:
echo $icecream['Choco'][0]
Your problem here is calling the wrong key for the 1st dim
.
.
For your updated question, try this:
$ice_k = array_keys($icecream);
echo $icecream[$ice_k[0]][0];
You're not using the associative array right. You need to use the right key.
echo $icecream['choco'][0];
You can use position but it will be a counter like this:
$counter = 0;
foreach($icecream As $k=>$v) {
echo $icecream[$k][0] . ' [' . $counter . ']';
$counter++;
}
and if you want to get only value you can use previous code
$ice_k = array_keys($icecream);
$position = 5;
if( isset($ice_k[$position]) ) {
echo $icecream[$ice_k[$position]][0];
}
I am using HighCharts Bar graph to plot data from mysql resultset into a bar graph.
Now the resultset of my query is as below:
Name Expense
-----------------
July 700.0000
August 450.0000
September 1700.0000
The series property of HighCharts require data in below format to plot the graph
[
{name:"July",data:[700.0000]},
{name:"August",data:[450.0000]},
{name:"September",data:[1700.0000]}
]
So I thought of coverting my resultset into a JSON object using json_encode($row).
But I got the following output:
[{"name":"July","data":"700.0000"},
{"name":"August","data":"450.0000"},
{"name":"September","data":"1700.0000"}]
Doubts:
Is there a way to get/convert the resultset in exactly the same format as is required by the series property of HighCharts?
Also can I use an object of created in the php block, directly into the javascript? Say I create an object $jsonNameData out of my resultset. Then can I use it in the javascript as
series: <? echo $jsonNameData ?>
EDIT:
I was able to solve Q1 by doing the following:
$count = 0;
$strSeries = "[";
while($r = mysql_fetch_assoc($result)) {
if($count == 0){
$strSeries .= "{name:'" . $r['name'] . "',";
$strSeries .= "data:[" . $r['data'] . ']}';
$count = 1;
}
else {
$strSeries .= ",{name:'" . $r['name'] . "',";
$strSeries .= "data:[" . $r['data'] . ']}';
}
$rows[] = $r;
}
$strSeries .= "]";
Got the required string into $strSeries.
Now the problem is the second question. I assigned the value of $strSeries to a variable in javascript but when I use that variable as
series: variableName
It is not plotting the graph properly even though the variable has proper value (checked through alert).
Not got a chance to run the code below, but this should work or something very similar to this
$series=array();
while($item = mysql_fetch_assoc($result)) {
$serie=array(
"name" => $item['name'],
"data" => array(floatval($item['data']))
);
array_push($series,$serie);
}
echo json_encode($series);
An advice is to always stick to json_encode() for doing the jsonification. You may want to go through this example on the reference page to learn about how json_encode works with arrays in particular
EDIT: To answer your 2nd question. You may be getting a highchart error #14 in the javascript console? Have a look at this question Highcharts returning error 14
P.S. Please don't mix multiple questions in one, post them separately, also use tools like javascript console and SO search more effectively
I would try this :
$jsonObj = '[';
foreach($mysqlResul as $item){
$jsonObj .= '{"name":"'.$item['name'].'","data":['.$item['data'].']},';
}
// strip off last comma
$jsonObj = substr(0,strlen($jsonObj)-1,$jsonObj);
$jsonObj .= ']';
select concat('{name:"', name, '",data:[', expense, ']}') as foo
from bar
I have an array in javascript that I need to join and send through a URL to PHP such as the following:
var objects = [];
objects.splice("red",0,"apple");
objects.splice("yellow",0,"banana");
objects.splice("purple",0,"grape");
var string = objects.join("+");
$("#print_div").load("fruits.php?fruits=" + string);
In PHP, I want to recieve the string and convert it back to an array... something like this:
$fruits = explode(" ", $_REQUEST['fruits']);
foreach($fruits as $key => $value){
echo "The " . $value . " is " . $key;
}
Maybe it is the join or the splice in javascript that wont make this work, or maybe the explode in php. Im not sure, but I need a solution to be able to create custom indexes to an array in javascript and then send to php and still be able to access the index and value names.
Thanks for your help!
If you use objects.join("+") in javascript you should use explode("+", $_REQUEST['fruits']) in PHP
Try using push() to add elements to an array.
You may want to look into parse_str which takes a GET string and parses it into an array, keyed and everything.
Suppose this is your object:
var fruits = {
red: "apple",
yellow: "banana",
purple: "grape"
};
Pass it to php like so: (ref)
$("#print_div").load("fruits.php", {fruits: fruits});
Use it like so:
$fruits = $_REQUEST['fruits'];
foreach($fruits as $key => $value){
echo "The " . $value . " is " . $key;
}
You are using splice wrong. Check it here.
You could pass the data to the .load method like below, it's much simple.
var data = {
"red": "apple",
"yellow": "banana",
"purple": "grape"
};
$("#print_div").load("fruits.php", data);
And in php:
foreach($_GET as $key => $value){
echo "The " . $value . " is " . $key;
}
Even if you change nothing else in the original code, this line
$("#print_div").load("fruits.php?fruits=string");
should probably be
$("#print_div").load("fruits.php?fruits="+string);