I have a URL string of images divided by "|" and I would like a php function that reading the string separate the images and divide them with "," to use a wordpress gallery component
http://xxxxxxxx/xxxxxxx/wp-content/uploads/2018/02/large-IMG_5367.jpg|http://xxxxxxxx/xxxxxxx/wp-content/uploads/2018/02/large-IMG_5376.jpg|http://xxxxxxxx/xxxxxxx/wp-content/uploads/2018/02/large-IMG_6324.jpg
I tried to create a php shortcode called get id from string
/* ---------------------------------------------------------------------------
* Shortcode | get_id_from_string
* --------------------------------------------------------------------------- */
add_shortcode('get_id_from_string', 'function_get_id_from_string');
function function_get_id_from_string($atts) {
global $wpdb;
$return_value = '';
$url_array = explode('|', $atts['urls']);
foreach ($url_array as &$url) {
$return_value .= $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $url))[0] . ',';
}
return rtrim($return_value, ',');
}
But it does not work, has anyone already done something like that?
Thanks in advance
Try below cod,
If URL found in database it will return ID and add in $return_value variable.
add_shortcode('get_id_from_string', 'function_get_id_from_string');
function function_get_id_from_string($atts)
{
global $wpdb;
//$imagestr = "http://xxxxxxxx/xxxxxxx/wp-content/uploads/2018/02/large-IMG_5367.jpg|http://xxxxxxxx/xxxxxxx/wp-content/uploads/2018/02/large-IMG_5376.jpg|http://xxxxxxxx/xxxxxxx/wp-content/uploads/2018/02/large-IMG_6324.jpg";
$imagestr = $atts['urls'];
$url_array = explode("|", $imagestr);
$return_value = [];
foreach ($url_array as $url) {
$query = $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s'", $url);
$result = $wpdb->get_col($wpdb->prepare($query, $url), ARRAY_A);
if (!empty($result))
$return_value[] = $result[0];
}
$images_ids = implode(",", $return_value);
return ($images_ids);
}
Related
I have a table in MySQL with approx. 20 million rows.
id | word_eng | word_indic
I have to translate the english word (word_eng) into indian language (word_indic) using google translate api.
I have written PHP code which spawns multiple curl requests and fetches data from API and updates it into the table. But this process is quite slow, about 100 to 200 words per second.
I am using RollingCurl for multi curl.
Whats the best way to make it as fast as possible?
Below is my code. I am running this as a cron job.
<?php
include_once('db.php');
include_once('functions.php');
include_once('rolling-curl-master/RollingCurl.php');
$table = $argv[1];
$q = "SELECT * from $table where word_indic is null limit 500000";
$result = $conn->query($q); $n = 0;
$urls = array();
while ($row = $result->fetch_assoc())
{
$id = $row['id'];
$word = rawurlencode(getName($row['name_eng']));
//getName is a simple function which does some trimming and cleaning up of string
$url = 'https://www.google.com/inputtools/request?text='.rawurlencode($word).'&ime=transliteration_en_te&id='.rawurlencode($id);
array_push($urls, $url);
}
//print_r($urls);
unset($url);
$rc = new RollingCurl("request_callback");
// the window size determines how many simultaneous requests to allow.
$rc->window_size = 300;
foreach ($urls as $url)
{
// add each request to the RollingCurl object
$request = new RollingCurlRequest($url);
$rc->add($request);
}
$rc->execute();
function request_callback($response, $info)
{
// parse the page title out of the returned HTML
if (preg_match("~<title>(.*?)</title>~i", $response, $out)) {
$title = $out[1];
}
//echo "<b>$title</b><br />";
//print_r($info);
$parts = parse_url($info['url']);
parse_str($parts['query'], $query);
$id = $query['id'];
$text = $query['text'];
//echo "<hr>";
$trans = json_decode($response)[1][0][1][0];
global $conn; global $table; global $urls; global $n;
if ($trans != '' and !preg_match('/[a-z]/', $trans))
{
$conn->query("update $table set word_indic='$trans' where id='$id'"); $n++;
}
}
?>
I have a sql request to do with a php array to find all the occurrences of a search bar.
I can't get this done. This is my code :
$texte = $_POST['texte'];
$texte = explode(" ", $texte);
$query_parts = array();
//Proximité
foreach ($texte as $value) {
$value = "%".$value."%";
}
$sql = "SELECT * FROM PROXIMITE WHERE titrefr LIKE ':texte'";
$req = $bd->requete_obj($sql, array('texte'=>$texte));
while($select = $req->fetch()){
error_log('Test');
}
Your foreach-loop does not actually modify the variables, because they are passed by Value - meaning a copy.
to modify them, you have to pass them by reference:
foreach ($texte as &$value) {
$value = "%".$value."%";
}
that way, the actual values in your array are being manipulated.
secondly: you can not give your database an array as parameter. instead, you could loop through the array. if you implement that in your first loop, you don't even have to use references anymore:
$sql = "SELECT * FROM PROXIMITE WHERE titrefr LIKE :texte";
foreach ($texte as $value) {
$value = "%".$value."%";
$req = $bd->requete_obj($sql, array('texte'=>$value));
while($select = $req->fetch()){
error_log('Test');
}
}
I have a problem where some variables are probably (I can't know for sure) not inserted into the final statement. Here is my example:
Works:
public static function findByPageAndFieldContains($recordsPerPage, $page, $field, $searchterm) {
$query = CouchbaseN1qlQuery::fromString('SELECT * FROM `public_portal` WHERE `collection`=$collection AND TOSTRING('.$field.') LIKE "%'.$searchterm.'%" ORDER BY `_id` limit $limit offset $offset');
$query->options['$collection'] = static::COLLECTION_NAME;
//$query->options['$field'] = $field;
$query->options['$limit'] = $recordsPerPage;
$query->options['$offset'] = $recordsPerPage*($page-1);
//$query->options['$searchterm'] = $searchterm;
$result = DB::getDB()->query($query);
var_dump($query);
var_dump($result);
$objects = array();
foreach($result as $row) {
$object = new static($row->{"public_portal"});
$object->setId($row->{"public_portal"}->{"_id"});
$objects[] = $object;
}
//var_dump($objects);
return $objects;
return $result;
}
Debug Output:
debug01
Does not work:
public static function findByPageAndFieldContains($recordsPerPage, $page, $field, $searchterm) {
$query = CouchbaseN1qlQuery::fromString('SELECT * FROM `public_portal` WHERE `collection`=$collection AND TOSTRING($field) LIKE "%$searchterm%" ORDER BY `_id` limit $limit offset $offset');
$query->options['$collection'] = static::COLLECTION_NAME;
$query->options['$field'] = $field;
$query->options['$limit'] = $recordsPerPage;
$query->options['$offset'] = $recordsPerPage*($page-1);
$query->options['$searchterm'] = $searchterm;
$result = DB::getDB()->query($query);
var_dump($query);
var_dump($result);
$objects = array();
foreach($result as $row) {
$object = new static($row->{"public_portal"});
$object->setId($row->{"public_portal"}->{"_id"});
$objects[] = $object;
}
//var_dump($objects);
return $objects;
return $result;
}
Debug output:
debug02
Basically the second example returns no result, while the first one works just fine.
Any idea why?
You are not using N1QL parameters correctly. You must decide if you are evaluating your parameters in PHP or in N1QL.
The field name cannot be a N1QL parameter, so you evaluate it in PHP:
TOSTRING('.$field.') LIKE ...
The search term should be a N1QL parameter, so you add wildcards in PHP and then pass it to N1QL as a parameter:
$searchterm = '%'.$searchterm.'%'
TOSTRING('.$field.') LIKE $searchterm ...
Hi I currently have this code that retrieves the tags from each Image in the Database. The tags are seperated by commas. I place each set of tags on the end of the array. Now I want to create an array of the tags retrieved but merge any duplications.
function get_tags()
{
$tag_array = array();
$query = mysql_query("
SELECT tags
FROM gallery_image
");
while($row = mysql_fetch_assoc($query))
{
$tags = $row['tags'];
$tag_array[] = $tags;
}
echo $tag_array[0] . '<br>' . $tag_array[1] . '<br>' .$tag_array[2];
}
You question is not very clear but array_unique may be what you need?
function get_tags()
{
$query = mysql_query('SELECT tags '.
'FROM gallery_image');
$tag_array = array();
while($row = mysql_fetch_assoc($query))
$tag_array = array_merge($tag_array, explode(',', $row['tags']));
return array_unique($tag_array);
}
You probably want something like this:
$tags = array(
'one,two',
'one,three',
);
$result = array_unique(array_reduce($tags,
function($curr, $el) {
return array_merge($curr, explode(',', $el));
},
array()));
See it in action.
What this does is process each result row (which I assume looks like "tag1,tag2") in turn with array_reduce, splitting the tags out with explode and collecting them into an intermediate array which has just one tag per element. Then the duplicate tags are filtered out with array_unique to produce the end result.
Try this:
$unique_tags = array();
foreach ($tag_array as $value) {
$unique_tags = array_merge($unique_tags, explode(",", $value);
}
$unique_tags = array_unique($unique_tags);
function createPath($id, $category_tbl, $path) {
$s = "SELECT * FROM ".$category_tbl." WHERE ID = $id";
$r = mysql_query($s);
$row = mysql_fetch_array($r);
if($row['PARENT_ID'] == 0) {
$path .=$row['TITLE'].'-';
}
else {
$path .='-'.$row['TITLE'];
createPath($row['PARENT_ID'],$category_tbl, $path);
}
return $path;
}
It is a recursive function that must generate breadcrumbs. I cannot get it to work properly, it only returns the last TITLE.
the sql table is something like ID, TITLE, PARENT_ID
a PARENT_ID = 0 means the category has no parent,
for any other PARENT_ID, go to that ID, get it's title and add it to the $path variable
I need help to make this work. Alternatives are also welcomed.
Try something like this:
function createPath($id, $category_tbl) {
$s = "SELECT * FROM ".$category_tbl." WHERE ID = $id";
$r = mysql_query($s);
$row = mysql_fetch_array($r);
if($row['PARENT_ID'] == 0) {
return $row['TITLE'];
} else {
return createPath($row['PARENT_ID'],$category_tbl).'-'.$row['TITLE'];
}
}
Looks like you either need to use the value returned by createPath or have $path passed by reference, &$path. One or the other, but not part of each.