First time working with Wordpress. I am looking to get a random row from a formcraft table so I can publish the winner of a draw from a bunch of registrations on a page.
The content I want from the formcraft table is stored like this in a column called content in a table called wp_formcraft_3_submissions:
[
{\"label\":\"Name\",\"value\":\"Annette\",\"identifier\":\"field1\",\"type\":\"oneLineText\",\"page\":1,\"page_name\":\"Step 1\",\"width\":\"100%\",\"altLabel\":\"Name\"},
{\"label\":\"Company Name\",\"value\":\"My Co \",\"identifier\":\"field3\",\"type\":\"oneLineText\",\"page\":1,\"page_name\":\"Step 1\",\"width\":\"100%\",\"altLabel\":\"Company Name\"},
{\"label\":\"Email\",\"value\":\"annette#email.com\",\"identifier\":\"field6\",\"type\":\"email\",\"page\":1,\"page_name\":\"Step 1\",\"width\":\"100%\",\"altLabel\":\"Email\"}
]
I am trying to pull a random row, then publish name, company name.
I am stuck, and wordpress is not logging any errors though I have turned on error logging. I am doing this via a shortcode. I would like to echo the contents on the screen to start with, but ultimately, echo just the three fields.
function wa_awards_winner() {
global $wpdb;
$sql = $wpdb->query("
SELECT *
FROM wp_formcraft_3_submissions
ORDER BY RAND()
LIMIT 1
");
$result = $wpdb->get_results( $sql );
if ( ! $result ) { return false; }
$winner = json_encode($result[0]->content);
echo $winner;
}
add_shortcode( 'get_wa_awards_winner', 'wa_awards_winner' );
Untilmately I am trying to get these values like this but it is not working:
// NAME
echo '<h3 class="col">' . $winner[0][0] . '</h3>';
// COMPANY NAME
echo '<h3 class="col">' . $winner[1][0] . '</h3>';
// EMAIL
echo '<h3 class="col">' . $winner[2][0] . '</h3>';
Appreciate any help. Thanks.
Trying suggestion below like this:
$winner = json_decode(stripslashes($result[0]->content),true);
echo '<div style="color:white;">' . print_r($winner, true) . '</div>';
I get;
[13-Jun-2019 12:28:25 UTC] PHP Notice: Undefined offset: 0 in /var/www/site.com/wp-content/themes/dp-click-Child/functions.php on line 30
[13-Jun-2019 12:28:25 UTC] PHP Notice: Trying to get property 'content' of non-object in /var/www/site.com/wp-content/themes/dp-click-Child/functions.php on line 30
This works thanks to suggestion below:
$sql = "
SELECT *
FROM wp_formcraft_3_submissions
ORDER BY RAND()
LIMIT 1
";
$result = $wpdb->get_results( $sql );
I then try and access the info lke this:
$winner = json_decode(stripslashes($result[0]->content),true);
echo var_dump($winner);
echo '<h3 style="color: white;">NAME: ' . $winner[0]["Name"] . '</h3>';
echo '<h3 style="color: white;">COMPANY: ' . $winner[1]["Company Name"] . '</h3>';
echo '<h3 style="color: white;">EMAIL: ' . $winner[2]["Email"] . '</h3>';
The var_dump returns:
array(3) { [0]=> array(8) { ["label"]=> string(4) "Name" ["value"]=> string(14) "Annette" ["identifier"]=> string(6) "field1" ["type"]=> string(11) "oneLineText" ["page"]=> int(1) ["page_name"]=> string(6) "Step 1" ["width"]=> string(4) "100%" ["altLabel"]=> string(4) "Name" } [1]=> array(8) { ["label"]=> string(12) "Company Name" ["value"]=> string(19) "My Company" ["identifier"]=> string(6) "field3" ["type"]=> string(11) "oneLineText" ["page"]=> int(1) ["page_name"]=> string(6) "Step 1" ["width"]=> string(4) "100%" ["altLabel"]=> string(12) "Company Name" } [2]=> array(8) { ["label"]=> string(5) "Email" ["value"]=> string(20) "annette#email.com" ["identifier"]=> string(6) "field6" ["type"]=> string(5) "email" ["page"]=> int(1) ["page_name"]=> string(6) "Step 1" ["width"]=> string(4) "100%" ["altLabel"]=> string(5) "Email" } }
But my variables return empty:
NAME:
COMPANY NAME:
EMAIL:
First you need to make "stripslashing" and to turn the given string to JSON data. Then you need to decode it, not encode.
Here it is:
$winner = json_decode(stripslashes($result[0]->content),true);
echo $winner[0]["value"];
And one more thing. $wpdb->query can't be used inside get_results. Remove those and use this instead
$sql = "
SELECT *
FROM wp_formcraft_3_submissions
ORDER BY RAND()
LIMIT 1
";
$result = $wpdb->get_results( $sql );
Related
I have a SQL Query result (array): "title", "content" and "name"
Here is my var_dump:
array(28) {
[0]=>
array(3) {
["title"]=>
string(10) "Basis Task"
["content"]=>
string(43) "https://www.wrike.com/open.htm?id=440908999"
["name"]=>
string(14) "Christian Wahl"
}
[1]=>
array(3) {
["title"]=>
string(10) "Basis Task"
["content"]=>
string(5) "MySQL"
["name"]=>
string(14) "Christian Wahl"
}
[2]=>
array(3) {
["title"]=>
string(4) "Test"
["content"]=>
string(3) "PHP"
["name"]=>
string(14) "Christian Wahl"
}
[3]=>
array(3) {
["title"]=>
string(4) "Test"
["content"]=>
string(3) "PHP"
["name"]=>
string(14) "Christian Wahl"
}
[4]=>
array(3) {
["title"]=>
string(10) "Basis Task"
["content"]=>
string(7) "content"
["name"]=>
string(9) "Elena Ott"
}
(I cut off the end of the array to make it a little clearer to see)
These are Tasks who are assigned to a User.
Now i want to output the "Name" (panel-heading)
and the "title" and "content" (panel-body).
It should look smth like this but for each given name:
how it should look like
I tried to find a solution on my own, but without success :(
I hope u can help me?
thx a lot
-Taddl
just loop on your data and render it
$data = [];
foreach ($databaseResult as $row) {
$data[$row['name']][] = $row;
}
foreach($data as $name => $stuff) {
echo $name . '<br>';
foreach($stuff as $row) {
echo $row["title"] . ':' . $row["content"] . '<BR>';
}
}
You can use foreach loop. As example:
foreach($yourarrayvariable as $data)
{
echo "<tr>";
echo "<td class='heading'>".$data['name']."</td>";
echo "<div class='content'>";
echo "<td>".$data['title']."</td>";
echo "<td>".$data['content']."</td>";
echo "</div>";
echo "</tr>";
}
And create your desired template look classes as per your need inside foreach.
I am trying to retrieve my city visitor from my website using codeigniter
Here is code to show city
$city = $this->geolocation->get_city();
Here the output from geolocation is like
array(11) { ["statusCode"]=>string(2) "OK" ["statusMessage"]=> string(0) "" ["ipAddress"]=> string(12) "202.60.21.15" ["countryCode"]=> string(2) "ID" ["countryName"]=> string(9) "Indonesia" ["regionName"]=> string(10) "Jawa Timur" ["cityName"]=> string(11) "Pacarkeling" ["zipCode"]=> string(5) "60132" ["latitude"]=> string(6) "-7.258" ["longitude"]=> string(7) "112.758" ["timeZone"]=> string(6) "+07:00" } OK202.67.41.25IDIndonesiaJawa
I am using
$cities = json_decode($city, true);
foreach ($cities as $c) {
echo $c;
}
and the output is like this
OK202.67.01.25IDIndonesiaJawa TimurPacarkeling60132-7.258112.758+07:00
How can I get each data from the output? I want to print each data from Geolocation library in Codeingiter like
Your Visitor Country : Indonesia
Your IP Visitor : 202.67.01.25
Your City Name : Pacarkeling
Thank you very much :)
Are you asking for the keys of the array? If so, you can do something like this:
$city = $this->geolocation->get_city();
$city_info = json_decode($city, true);
foreach ($city_info as $key=>$value) {
echo 'Your ' . $key . ' : ' . $value . '<br>';
}
I'm using following code php to get timezone:
$url = 'http://api.geonames.org/timezone?lat=' . $latitude . '&lng=' . $longitude . '&username=demo';
$xml = simplexml_load_file($url);
foreach($xml->children() as $timezone)
{
echo "TimezoneId: ".$timezone->timezoneId." ";
echo "DstOffset : ".$timezone->dstOffset." ";
echo "GmtOffset : ".$timezone->gmtOffset." ";
}
it work but for latitude and longitude of Antartica for example it give error status message:
<status message="no timezone information found for lat/lng" value="15"/>
How to echo this message?
I'm tryng this:
if ($xml->status) {
echo "error: ".$timezone->status['message']. "";
}
but don't work
You are trying to get an element from object, which doesn't exist. In such a XML element you have attributes and some values like in your case: countryCode, countryName, dstOffset, gmtOffset and etc. If you use var_dump() the result you can see the error message is in these attributes, which is an array.
Here you are an example:
var_dump() on a location without problem:
object(SimpleXMLElement)#4 (12) {
["#attributes"]=>
array(1) {
["tzversion"]=>
string(11) "tzdata2014i"
}
["countryCode"]=>
string(2) "KG"
["countryName"]=>
string(10) "Kyrgyzstan"
["lat"]=>
string(7) "40.4246"
["lng"]=>
string(7) "74.0021"
["timezoneId"]=>
string(12) "Asia/Bishkek"
["dstOffset"]=>
string(3) "6.0"
["gmtOffset"]=>
string(3) "6.0"
["rawOffset"]=>
string(3) "6.0"
["time"]=>
string(16) "2015-07-09 19:53"
["sunrise"]=>
string(16) "2015-07-09 05:41"
["sunset"]=>
string(16) "2015-07-09 20:36"
}
And here a var_dump() of Antartica:
object(SimpleXMLElement)#4 (1) {
["#attributes"]=>
array(2) {
["message"]=>
string(41) "no timezone information found for lat/lng"
["value"]=>
string(2) "15"
}
}
You can easily handle and print this error message like that:
if ($xml->status) {
echo 'error:' . $timezone->attributes()->message;
}
try this,
<?php
$url = 'http://api.geonames.org/timezone?lat=' . $latitude . '&lng=' . $longitude . '&username=demo';
$xml = simplexml_load_file($url);
foreach ($xml->geoname as $o_location){
printf(
'Name %s<br>
lat is %s<br>
lon is %s<br>
geonameId is %s<br>
countryCode is %s<br>
countryName is %s<br>
fcl is %s<br>
fcode is %<br>
',
$o_location->name,
$o_location->lat,
$o_location->lng,
$o_location->geonameId,
$o_location->countryCode,
$o_location->countryName,
$o_location->fcl,
$o_location->fcode
);
}
?>
HTML file:
http://www.arifoorum.com/test/html.htm
I got this html contents with simplehtmldom library:
array(66) {
[0]=>
array(14) {
[0]=>
string(4) "Item"
[1]=>
string(11) "Date, time:"
[2]=>
string(8) "mõõdikud"
[3]=>
string(6) "Name 2"
[4]=>
string(6) "Name 3"
[5]=>
string(9) "Meter ID:"
[6]=>
string(6) "V_HeEn"
[7]=>
string(6) "U_HeEn"
[8]=>
string(3) "V_V"
[9]=>
string(3) "U_V"
[10]=>
string(6) "V_InTe"
[11]=>
string(6) "U_InTe"
[12]=>
string(6) "V_OuTe"
[13]=>
string(6) "U_OuTe"
}
[1]=>
array(14) {
[0]=>
string(1) "1"
[1]=>
string(19) "24.01.2013 22:23:33"
[2]=>
string(9) "Meter 002"
[3]=>
string(6) " "
[4]=>
string(6) " "
[5]=>
string(8) "40380040"
[6]=>
string(6) " "
[7]=>
string(6) " "
[8]=>
string(6) " "
[9]=>
string(6) " "
[10]=>
string(6) " "
[11]=>
string(6) " "
[12]=>
string(6) " "
[13]=>
string(6) " "
}
[2]=>
...
}
}
Full output: http://www.arifoorum.com/test/test.php
How do I get certain element from that array?
For example: lets say i want value where mõõdikud = 01 and name 2 = külm (that should be 72,114) .
Thanks
This could be useful for other users, so I made a little function that gets the value of a cell from a table, based on values of other cells (conditions):
function getCellValue(DOMElement $table, $cellName = null, array $conditions = array()){
// get all table rows
$trs = $table->getElementsByTagName('tr');
// assume first TR is the table header
$head = $trs->item(0);
// find cell names and their index
$keys = array();
foreach($head->childNodes as $th)
if(!($th instanceof DomText))
$keys[] = trim($th->nodeValue);
if($invalidKeys = array_diff(array_keys($conditions), $keys))
throw new Exception(sprintf('Non-extistent key(s) in table: ', implode(', ', $invalidKeys)));
// find the row that meets all conditions
$targetRow = null;
foreach($table->childNodes as $tr){
// internal counter because we can't rely on DOM index
$idx = 0;
foreach($tr->childNodes as $td){
if($td instanceof DomText)
continue;
$value = trim($td->nodeValue);
// check if all conditions match
if(array_key_exists($keys[$idx], $conditions))
$targetRow = ($value != $conditions[$keys[$idx]]) ? null : $tr;
$idx++;
}
// stop if we found a match
if($targetRow)
break;
}
if(!$targetRow)
throw new Exception('No row matches your conditions');
// build an array with row cells
$values = array();
$idx = 0;
foreach($targetRow->childNodes as $td)
if(!($td instanceof DomText))
$values[$keys[$idx++]] = trim($td->nodeValue);
// return the cell value if a specific cell was requested
if($cellName !== null)
return isset($values[$cellName]) ? $values[$cellName] : null;
// otherwise return all values from the matched row
return $values;
}
It uses DomDocument because the question wasn't tagged as simplehtmldom
#OP: in your case you would use it like:
$html = file_get_contents('http://www.arifoorum.com/test/html.htm');
$dom = new DomDocument();
$doc->preserveWhiteSpace = false;
$dom->loadHtml($html);
$table = $dom->getElementsByTagName('table')->item(0);
print getCellValue($table, 'V_V', array(
'mõõdikud' => '01',
'Name 2' => 'külm',
));
So I run some code like this:
$quote = simplexml_load_string($xml);
$quote = $quote->Stock;
echo 'Name: ';
echo $quote->Name;
echo '<br>';
echo 'Sybmol: ';
echo $quote->Symbol;
echo '<br>';
echo 'Last Price: ';
echo $quote->Last;
echo '<br>';
echo 'Earnings To Price Ratio: ';
echo $quote->P-E;
echo '<br>';
I know that the second to last line ($quote->P-E) is incorrect - I don't think you can use dashes like that. But for some reason I can't figure out how to access that property. The weird thing is that's how it's written if I var_dump($quote) (It's towards the end):
object(SimpleXMLElement)#17 (16) { ["Symbol"]=> string(4) "AAPL" ["Last"]=> string(6) "271.87" ["Date"]=> string(9) "6/17/2010" ["Time"]=> string(6) "3:59pm" ["Change"]=> string(5) "+4.62" ["Open"]=> string(6) "270.72" ["High"]=> string(6) "272.90" ["Low"]=> string(6) "269.50" ["Volume"]=> string(8) "31195032" ["MktCap"]=> string(6) "247.4B" ["PreviousClose"]=> string(6) "267.25" ["PercentageChange"]=> string(6) "+1.73%" ["AnnRange"]=> string(15) "132.88 - 272.90" ["Earns"]=> string(6) "11.796" ["P-E"]=> string(5) "22.66" ["Name"]=> string(10) "Apple Inc." }
How should I be accessing this attribute/property?
$quote->{'P-E'};