Get two acf fields comma separated - advanced-custom-fields

I want to show two acf fields comma separated in single line if both are available, otherwise show one field which is available without comma.
I got the code, but not sure where to put <?php code to make it work.
if (get_field('birthDate') {
$values[] = get_field('birthDate');
}
if (get_field('birthPlace') {
$values[] = get_field('birthPlace');
}
if (!empty($values)) {
echo implode(', ', $values);
}

Related

Yii2 Matching all values in IN clause

Im trying to get a query which matches all values within an IN clause. This is what I have right now in UsersSearch.php model:
$categoryIdsMatching = UsersCategoriesAssn::find()
->select('userID')
->distinct(true)
->joinWith('userCategory')
->andWhere(['IN', 'usersCategories.id', $this->catNameSearch])
->column();
$query->andWhere(['userID'=>$categoryIdsMatching]);
But it gets records matching at least one of the values... How can I set that andWhere clause to match all values instead of some of them?
This could be something similiar to:
$categoryIdsMatching = UsersCategoriesAssn::find()
->select('userID')
->distinct(true)
->joinWith('userCategory')
->andWhere(['IN', 'usersCategories.id', $this->catNameSearch])
->groupBy('userTable.userID')
->having('COUNT(userTable.userID) ='.count($this->catNameSearch));
There is propably no other way to filter IN operator to match all values in MySQL.
Yii2 where in clause
Model :
//GET MULTIPLE AREA
public function getAreaSelected() {
//GET SAVE COMMA SEPERARED VALUE CONVERT IN TO ARRAY
$areaArray = explode(",", $this->attributes['selected_area']);
$query = AreaMaster::find()->where(['IN', 'id', $areaArray])->all();
return $query; //$this->hasMany(AreaMaster::className(), ['IN', 'id', $pks]);
}
VIEW FILE :
<?php
print '<pre>';
print_r($model->areaSelected);
exit;
?>

mySQL query for building dynamically populated model

I have some code below which demonstrates a hard-coded example of what I would like to accomplish dynamically.
At a high level, I wish to do something like select * from view_data_$app_state and then get all of the data from that views table into my mustache templates dynamically.
The code I currently must use to group multiple rows of data for a specific column along with the views data is:
<?php
error_reporting(E_ALL);
class Example {
function __construct(){
try {
$this->db = new PDO('mysql:host=localhost;dbname=Example', 'root','drowssap');
}
catch (PDOException $e) {
print($e->getMessage());
die();
}
}
function __destruct(){
$this->db = null;
}
function string_to_array($links_string){
return explode(",", $links_string);
}
function get_view_data(){
$q = $this->db->prepare('select *, GROUP_CONCAT(`links`) as "links" from `view_data_global` ');
$q->execute();
$result = $q->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
$Example = new Example();
$result = $Example->get_view_data();
$result[0]["links"] = $Example->string_to_array($result[0]["links"]);
echo json_encode($result);
This gives me the perfect object while
GROUP_CONCAT seems to be doing the trick this way, however I MUST know the column name that will contain multiple rows before writing the query. I am trying to figure out an approach for this and wish to make a custom query + code example that will transform cols with multiple rows of null null and not empty data into an array like above - but return the data.. again like the code above.
Below is an output of the actual data:
[{"id":"1","title":"This is the title test","links":["main","about","store"]}];
How can I replicate this process dynamically on each view table?
Thank you so much SO!
You can use PDOStatement::fetch to retrieve your results, with fetch_style set to PDO::FETCH_ASSOC (some other values will also provide the same information). In this case, the result set will be array indexed by column name. You can access this information with foreach (array_expression as $key => $value)
See the documentation for additional information.

How to auto generate a text field based on a drop down box selection

I have a small form field that has as dropdown <name="product"> this list is generated by pulling data from a mysql table.
The mysql DB is setup as following:
Table Product:
Column: Product
Column: Product ID
Table Contact:
Column: Product ID
Column: Contact Name
Column: Contact name #2
Column: Contact Name #3
Column: Contact name #4
Based on what a user selects in the pulldown list, I want to query the database again to datafill 4 new text boxes:
Name1
Name2
Name3
Name4
Is there a quick and easy way to do this?
The intent of the form will also capture some other data and submit it to a separate database, which leads me into how to tie in two DB's.
Thanks.
There are many ways to do this. Here's one:
When preparing the page, query all the Contact row columns and put them into a JavaScript array on the page. There output could look something like this (there are plenty of correct ways to implement this):
<script language=JavaScript>
var contactInfo = new Array(
{prodID: 1, name1: 'aaaa', name2: 'bbbb', name3: 'cccc', name4: 'dddd'},
{prodID: 4, name1: 'eeee', name2: 'ffff', name3: 'gggg', name4: 'hhhh'},
...
{prodID: 90, name1: 'wwww', name2: 'xxxx', name3: 'yyyy', name4: 'zzzz'}
);
In the dropdown list's onchange, call a function to handle the productID selection:
<select name="ddlProductID" onchange="processProductChange(this);">
Make sure you have the textboxes defined. For this example I'll call them txtName1 through txtName4:
<input type=text name="txtName1">
...
<input type=text name="txtName1">
In the called function, get the dropdown list's value and locate it in the contactInfo array. That will lead you to the names, and you can pop them into the textboxes:
function processProductChange(prodDropdown) {
for (indx = 0; indx < contactInfo.length; ++indx) {
if (contactInfo[indx].prodID == prodDropdown.value {
// The product ID has been located in the array. Put its names
// in the txtName1 through txtName4 textboxes.
document.forms[0].txtName1.value = contactInfo[indx].name1;
document.forms[0].txtName2.value = contactInfo[indx].name2;
document.forms[0].txtName3.value = contactInfo[indx].name3;
document.forms[0].txtName4.value = contactInfo[indx].name4;
// all done, can get out
break;
}
}
}
Addendum: OP asked for more detail on this approach. This requires some PHP code, which I'm not that good at, but I know enough that I'll first give the obligatory warning about using the mysql PHP functions. Here goes...
The PHP mysql functions are deprecated. Please use PDO or mysqli instead.
Now back to the answer. As mentioned, my PHP isn't that good, but basically you want to format the {prodID: ... } lines of the script from step 1 while populating the dropdown list; that way you only need to scan the results once. It would go something like this (interspersed in the code the OP provided in the comment):
<?php
$jsArray = '';
while ($row = mysql_fetch_array($productlist)) {
$rowmod = strtr($row['ProductID']," ","_"); // change the spaces to underscore to work in URL line
if (jsArray) {
// comma between elements
jsArray .= ",";
}
jsArray .= "\n{prodID: {$row['ProductID']}, ";
jsArray .= "name1: \"{$row['Name1']}\", ";
jsArray .= "name2: \"{$row['Name2']}\", ";
jsArray .= "name3: \"{$row['Name3']}\", ";
jsArray .= "name4: \"{$row['Name4']}\"}";
echo "<option value='$rowmod'>$row[ProductElement]</option>";
}
?>
Then when you can safely place the JavaScript (say after the closing <form> tag, do this:
<? php
echo <<< endJS
<script language="JavaScript">
var contactInfo = new Array($jsArray);
NOTE: PASTE THE FUNCTION FROM STEP 4 HERE
</script>
endJS;
?>
Chances are there's an error or two in the code here, so some debugging will likely be needed.

writing xml into mysql in for each loop

I have pulled values from an xml file which i need to store. I now need to get this data into my mysql database. I have done a complex for each loop with multiple levels so I am wondering how I would go about putting this in to a MYSQL insert statement. Any help would be gratefully appreciated.
Example
<?php
$source = file_get_contents("test.xml");
$xml = simplexml_load_string($source);
$game = $xml->xpath("//market");
foreach ($game as $event)
{
if (strpos($event['name'], 'Match Betting') !== false)
{
mysql_query("INSERT INTO feed (feedid, homeid, homeodd, drawid, drawodd, awayid, awayodd)
VALUES ("echo $event['id'] .", ";
{
foreach ($event->children() as $prices)
{
echo $prices['id'] . ", ";
echo $prices['odds'];
}
}
")");
}
}
?>
The above really doesnt work and is a little stupid but I really cant think how to do this.
Help please :D
dont use foreach loop inside the mysql statement. instead use the sql in the foreach loop. try it and inform if it doesn't work.

Adding 2 drop lists to associated table

I am having an issue trying to add the records using 2 drop lists.
I have a table called Urls which holds the details of url. I have a table called category populates a drop list, I have another table called publishers which populates another drop list.
$query = 'INSERT INTO url_associations (url_id, url_category_id, approved, url_publisher_id) VALUES ';
foreach ($_POST['types'] as $v){
$query .= "($uid, $v, 'Y', $k), ";
}
$query = substr ($query, 0, -2); // Chop off the last comma and space.
$result = #mysql_query ($query); // Run the query.
if (mysql_affected_rows() == count($_POST['types'])) { // Query ran OK.
echo '<p><b>Thank you for your submission!</b></p>';
$_POST = array(); // Reset values.
} else { // If second query did not run OK.
The code above allows me to addd data using the categories drop list but when I try to add the url_publisher_id as 'posters' as $k I keep getting errors in my parsing. If anyone can understand what I am trying to achieve your help would be welcomed
If the value of your $k variable is anything other than an integer or float you'll get an error because it needs quotes around it when you're building the SQL INSERT statement:
$query .= "($uid, $v, 'Y', '$k'), ";
Note: There are some major security problems in your example. If you put user input from $_POST into your SQL without escaping it you're giving the user the ability to run whatever SQL commands they want to run on your database.
I have added an extra array foreach ($_POST[posters] as $k)
//so it reads
'foreach ($_POST[types] as $v)
foreach ($_POST[posters] as $k) {`
and it has executed perfectly.
Thanks for your help.
Sean