I have an add post form to add new post. I have taken post title as post_url or slug. I want unique post_url.
Here is what I have done so far -
$post_name = $this->input->post('post_title');
function clean($post_name) {
$name = trim($post_name);
$post_name = str_replace(' ', '-', $name);
return preg_replace('/[^A-Za-z0-9\-]/', '', $post_name);
}
$post_url = clean($post_name);
$query = mysql_query("select post_url from sa_posts where post_url like '" . $post_url . "%'");
while ($r = mysql_fetch_assoc($query)) {
$slugs[] = $r['post_url'];
if (mysql_num_rows($query) !== 0 && in_array($post_url, $slugs)) {
$max = 0;
while (in_array(($post_url . '-' . ++$max), $slugs)) ;
$post_url .= '-' . $max;
}
}
echo "Slug " . $post_url;
I am getting output as -
post-url
post-url-1
post-url-1-1
post-url-1-1-1
But I want output as -
post-url
post-url-1
post-url-2
post-url-3
What is a problem in my code?
Please help me.
Thanks.
function UniqueSlugGenerator($p){
include("conn.php");
$RowCou=0;
$slug = preg_replace('/[^a-z0-9]/', '-', strtolower(trim(strip_tags($p))));
$qq = mysqli_query($conn,"select Slug from ser_posts where Slug like '$slug%'") or die(mysqli_error($conn));
$RowCou = mysqli_num_rows($qq);
return ($RowCou > 0) ? $slug.'-'.(++$RowCou) : $slug;
}
Change your code in the following way
$post_url = clean($post_name);
$post_url1 = $post_url;
$query = mysql_query("select post_url from sa_posts where post_url like '" . $post_url . "%'");
while ($r = mysql_fetch_assoc($query)) {
$slugs[] = $r['post_url'];
if (mysql_num_rows($query) !== 0 && in_array($post_url, $slugs)) {
$max = 0;
$post_url = $post_url1;
while (in_array(($post_url . '-' . ++$max), $slugs)) ;
$post_url .= '-' . $max;
}
}
echo "Slug " . $post_url;
Related
I need to give color to a specific cell in pdf which is generated from my MySQL database, How to set the color to the specific value?
I have no clue about giving color to the specific value, I there any way help me out?
my pdf generate page is:
$fdate = date('Y-m-d H:i:s', strtotime($fromdate));
$tdate = date('Y-m-d H:i:s', strtotime( $todate));
/*$channelsCol = Channels::find()
->select(['channel_name'])
->where('DeviceRefID != :id',['id' => 0 ])
->orderBy('channel_no')
->all();*/
$channelscol = \Yii::$app->db
->createCommand("select channel_name from channels where deviceRefID !=0")
->queryAll();
$pdfpages = $this->getNoOfPdfs(count($channelscol));
$noOfPages = count($pdfpages[0]);
$collist=[];
$selectlist=[];
for($i=0; $i < $noOfPages;$i++)
{
$collist[$i] = 'Select SQL_BUFFER_RESULT "LogDateTime ",';
$selectlist[$i] = 'select LogDateTime,';
}
$count =0;
$counter=1;
for($i=0;$i<$noOfPages;$i++)
{
for($j=$pdfpages[0][$i];$j<$pdfpages[1][$i];$j++)
{
$collist[$i] = $collist[$i] . '"'.$channelscol[$j-1]['channel_name'] .'",';
$selectlist[$i] = $selectlist[$i] . 'Channel'.$j.'Value,';
$count = $count + 1;
}
}
for($i=0;$i <$noOfPages ;$i++)
{
$collist[$i] = rtrim($collist[$i],",");
$selectlist[$i] = rtrim($selectlist[$i],",");
}
//$path ="/var/www/devicesadmin/yii-app/web/devicelog/devicelog" . date("Y-m-d-H-i-s").".csv";
$logfilename =[];
$logfailure="";
for($i=0;$i < $noOfPages; $i++)
{
$logfilename[$i] = $pdfpages[2][$i] . date("Y-m-d-H-i-s") . mt_rand() . ".csv";
//$path ='D:/Raffi/ProjectsPhp/DevicesAdminProject/yii-app/web/devicelog//' . $logfilename[$i];
$path = "/var/www/devicesadmin/yii-app/web/devicelog/" . $logfilename[$i];
$export =' INTO OUTFILE "' . $path . '" FIELDS TERMINATED BY "," ENCLOSED BY \'"\' LINES TERMINATED BY \'\\n\' FOR UPDATE';
$whereclause = "where LogDatetime between '" . $fdate . "' and '" .$tdate ."'";
$finalsql = $collist[$i] . ' Union all ' .$selectlist[$i] .' From devicelog '. $whereclause . $export;
try {
Yii::$app->db->createCommand($finalsql)->execute();
//file_put_contents("D:\my.txt", $this->getHTML($path, $header));
//echo html($this->getHTML($path, $header));
//exit();
$pdf=new \PDF('P','mm','Legal');
$pdf->AliasNbPages();
//$pdf=new \PDF('L','mm','Legal',130);
$pdf->AddPage();
$pdf->SetFont('helvetica','',10);
$pdf->WriteHTML($this->getHTML($path));
$logfilename[$i] = "dl" . $pdfpages[2][$i] . date("Y-m-d-H-i-s").".pdf";
//$filename = "D:/Raffi/ProjectsPhp/DevicesAdminProject\yii-app\web\devicelog" . $logfilename[$i];
$filename = "/var/www/devicesadmin/yii-app/web/devicelog/" . $logfilename[$i];
$pdf->Output('F',$filename);
unset($pdf);
} catch(Exception $e) {
}
}
If a pdf is generated, I need to give red color to the values which are above 50. But I can't get the values and give color.
I want to transform this PHP function.. that should return JSON data.
<?php
$query = 'SELECT * FROM `' . mix_player::table() . '` a';
if (isset($_GET['cat']) || isset($_GET['order']))
if (isset($_GET['cat'])) {
$query .= ' INNER JOIN `' . mix_player::table_cat_rel() . '` b '
. "ON (a.`id` = b.`idtrack`) WHERE `idcat` = '" . $wpdb->escape($_GET['cat']) . "'";
$random = $wpdb->get_var('SELECT `random`, `order` FROM `' . mix_player::table_categories() . "` WHERE `id` = '"
. $wpdb->escape($_GET['cat']) . "'");
if (!$random)
$order = $wpdb->get_var(NULL, 1);
}
if (isset($_GET['order']))
$order = $_GET['order'];
if ($order != '') {
if (isset($_GET['cat']))
$query .= ' AND ';
else
$query .= ' WHERE ';
$tracks = mix_player::order_list($query, $order);
}
} else {
$random = '0';
}
$query .= ' ORDER BY `id` ASC';
if (isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A))) {
// option "shuffle = true" not always working into mix. Do it our own way...
if ($random == 1) { // shuffle tracks?
list($usec, $sec) = explode(' ', microtime());
mt_srand((float) $sec + ((float) $usec * 100000));
$nrows = count($tracks);
for ($i = 0; $i < $nrows; $i++) {
$j = mt_rand(0, $nrows - 1); // pick j at random
$row = $tracks[$i]; // swap i, j
$tracks[$i] = $tracks[$j];
$tracks[$j] = $row;
}
}
foreach ($tracks as $row) {
$artist = (mix_player::entities($row['artist']));
echo ($artist);
$title = (mix_player::entities($row['title']));
echo ($title);
$url =(xspf_player::entities($row['url']));
echo ($url);
}
}
?>
to display like this json file :
{"title":"title", "artist":"artist","media":"url media.mp3","color":"#56B0E8" },
Can you help me?
Thanks in advance.
You can simply create an array and populate it with your desired values, then return it as JSON:
function tracks2json( $tracks )
{
$retval = array();
foreach( $tracks as $row )
{
$array = array();
$array['artist'] = mix_player::entities($row['artist']);
$array['title'] = mix_player::entities($row['title']);
$array['media'] = 'url '.xspf_player::entities($row['url']);
$array['color'] = '#56B0E8';
$retval[] = $array;
}
return json_encode( $retval );
}
if( isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A)) )
{
// Your MySQL routine here
$json = tracks2json( $tracks );
}
echo json_encode(array("title"=>$title,"artist"=>$artist,"url"=>$url));
I have the following small code which manipulate tweets data. I expect my loop to iterate 10 times. However, what happens is that it iterates only once and then exits, with no sign of any error relating to MySQL or otherwise.
$query = "select data from tweets where `screen_name` = 'username' limit 10";
$tweetsq = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
$tweets = mysqli_fetch_assoc($tweetsq);
$tweets_count = mysqli_num_rows($tweetsq);
echo $tweets_count . '<br />'; //See output
$count = 0;
foreach ($tweets as $raw_tweet) {
$tweet = json_decode($raw_tweet);
$tweet_id = $tweet->id_str;
$is_reply = (isset($tweet->in_reply_to_screen_name) && strlen($tweet->in_reply_to_screen_name) > 0) ? 1 : 0;
$is_retweet = (isset($tweet->retweeted_status) && $tweet->retweeted_status != '') ? 1 : 0;
$entity_holder = array();
$has_hashtag = $has_url = $has_mention = $has_media = 0;
foreach ($tweet->entities as $type => $entity) {
if (is_array($entity) && count($entity) < 1) {
//continue;
} else {
$entity = array_pop($entity);
switch ($type) {
case 'hashtags' : $has_hashtag = 1; break;
case 'urls' : $has_url = 1; break;
case 'user_mentions' : $has_mention = 1; break;
case 'media' : $has_media = 1; break;
default :
}
}
}
echo 'Updating recorde... <br />';
$query = "UPDATE tweets SET is_reply='" . $is_reply . "' , is_retweet='" . $is_retweet . "', has_hashtag='" . $has_hashtag . "', has_url='" . $has_url . "', has_mention='" . $has_mention . "', has_media='" . $has_media . "' WHERE tweet_id='" . $tweet_id . "'";
$result = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
var_dump($result); //See output
$count++;
echo '<br />';
}
echo $count;
Output:
10 //This is the value of $tweets_count
Updating recorde...
bool(true) //The result of the UPDATE query
1 //The value of $count at the end of script. It SHOULD be 10
mysqli_fetch_assoc fetches a single row as an associative array where the key is the column name and the value is the column value. The correct way to use it would be to iterate over the result set until the fetch returns NULL, indicating that there are no more rows to fetch:
while ($row = mysqli_fetch_assoc($tweetsq)) {
$raw_tweet = $row["data"];
$tweet = json_decode($raw_tweet);
$tweet_id = $tweet->id_str;
# etc...
I have a follow up question on something I got help with here the other day (No Table Three Column Category Layout).
The script is as follows:
$res = mysql_query($query);
$system->check_mysql($res, $query, __LINE__, __FILE__);
$parent_node = mysql_fetch_assoc($res);
$id = (isset($parent_node['cat_id'])) ? $parent_node['cat_id'] : $id;
$catalist = '';
if ($parent_node['left_id'] != 1)
{
$children = $catscontrol->get_children_list($parent_node['left_id'], $parent_node['right_id']);
$childarray = array($id);
foreach ($children as $k => $v)
{
$childarray[] = $v['cat_id'];
}
$catalist = '(';
$catalist .= implode(',', $childarray);
$catalist .= ')';
$all_items = false;
}
$NOW = time();
/*
specified category number
look into table - and if we don't have such category - redirect to full list
*/
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE cat_id = " . $id;
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$category = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)
{
// redirect to global categories list
header ('location: browse.php?id=0');
exit;
}
else
{
// Retrieve the translated category name
$par_id = $category['parent_id'];
$TPL_categories_string = '';
$crumbs = $catscontrol->get_bread_crumbs($category['left_id'], $category['right_id']);
for ($i = 0; $i < count($crumbs); $i++)
{
if ($crumbs[$i]['cat_id'] > 0)
{
if ($i > 0)
{
$TPL_categories_string .= ' > ';
}
$TPL_categories_string .= '' . $category_names[$crumbs[$i]['cat_id']] . '';
}
}
// get list of subcategories of this category
$subcat_count = 0;
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . $id . " ORDER BY cat_name";
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$need_to_continue = 1;
$cycle = 1;
$column = 1;
$TPL_main_value = '';
while ($row = mysql_fetch_array($result))
{
++$subcat_count;
if ($cycle == 1)
{
$TPL_main_value .= '<div class="col'.$column.'"><ul>' . "\n";
}
$sub_counter = $row['sub_counter'];
$cat_counter = $row['counter'];
if ($sub_counter != 0)
{
$count_string = ' (' . $sub_counter . ')';
}
else
{
if ($cat_counter != 0)
{
$count_string = ' (' . $cat_counter . ')';
}
else
{
$count_string = '';
}
}
if ($row['cat_colour'] != '')
{
$BG = 'bgcolor=' . $row['cat_colour'];
}
else
{
$BG = '';
}
// Retrieve the translated category name
$row['cat_name'] = $category_names[$row['cat_id']];
$catimage = (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '';
$TPL_main_value .= "\t" . '<li>' . $catimage . '' . $row['cat_name'] . $count_string . '</li>' . "\n";
++$cycle;
if ($cycle == 7) // <---- here
{
$cycle = 1;
$TPL_main_value .= '</ul></div>' . "\n";
++$column;
}
}
if ($cycle >= 2 && $cycle <= 6) // <---- here minus 1
{
while ($cycle < 7) // <---- and here
{
$TPL_main_value .= ' <p> </p>' . "\n";
++$cycle;
}
$TPL_main_value .= '</ul></div>'.$number.'
' . "\n";
}
I was needing to divide the resulting links into three columns to fit my html layout.
We accomplished this by changing the numbers in the code marked with "// <---- here".
Because the amount of links returned could be different each time, I am trying to figure out how to change those numbers on the fly. I tried using
$number_a = mysql_num_rows($result);
$number_b = $number_a / 3;
$number_b = ceil($number_b);
$number_c = $number_b - 1;
and then replacing the numbers with $number_b or $number_c but that doesn't work. Any ideas?
As mentioned before, you can use the mod (%) function to do that.
Basically what it does is to get the remainder after division. So, if you say 11 % 3, you will get 2 since that is the remainder after division. You can then make use of this to check when a number is divisible by 3 (the remainder will be zero), and insert an end </div> in your code.
Here is a simplified example on how to use it to insert a newline after every 3 columns:
$cycle = 1;
$arr = range (1, 20);
$len = sizeof ($arr);
for ( ; $cycle <= $len; $cycle++)
{
echo "{$arr[$cycle - 1]} ";
if ($cycle % 3 == 0)
{
echo "\n";
}
}
echo "\n\n";
i have a code to shorten multiple links but that code ( with an Optional Suffix ) the code is work from the second link only:
$url_to_shorten = $_POST[links];
$ownshuff = $_POST[shuff];
$theurls = explode("\n",$url_to_shorten);
foreach($theurls as $urlmulti){
shortcreate($urlmulti,$shuffss,$ownshuff);
}
here is an example :
my links are
http://www.123.com
http://www.1234.com
http://www.1235.com
and my Suffix is : ( Hello_Man ).
with the above code it prints
http://www.mysite.com/IUo
http://www.mysite.com/kOl-Hello_Man
http://www.mysite.com/Rww-Hello_Man
and it not print the Suffix for the first link.
the shortcreate function is :
function shortcreate($url_long, $Suffix, $ownshuf){
global $db;
$chars = $Suffix;
while (!shortisUnique($chars)) {
if ($ownshuf != "") {
$chars = shortgenerate_chars() . "-" . $ownshuf;
}
else {
$chars = shortgenerate_chars();
}
}
$url = $url_long;
$url = trim($url);
$url = mysql_real_escape_string($url);
if (!shortisThere($url)) {
$q = "INSERT INTO `shorturls` (url, unique_chars) VALUES ('" . $url . "', '" . $chars . "')";
//echo $q;
$r = $db->query($q);
if (mysql_affected_rows()):
$q = "SELECT * FROM `shorturls` WHERE `url`='" . $url . "'";
$r = $db->query($q);
$row = $db->fetch($r);
$the_url = SITE_URL . "" . $row[2];
echo "$the_url\n";
else:
$the_url = NULL;
return false;
endif;
}
else {
$q = "SELECT * FROM `shorturls` WHERE `url` = '" . $url . "'";
$r = mysql_query($q);
$row = mysql_fetch_row($r);
$the_url = SITE_URL . "" . $row[2];
echo "$the_url\n";
}
}
i need that code to work for all the links. any help
regards
I guess that the problem is in the next block of code:
$chars = $Suffix;
while (!shortisUnique($chars)) {
if ($ownshuf != "") {
$chars = shortgenerate_chars() . "-" . $ownshuf;
}
else {
$chars = shortgenerate_chars();
}
}
You give the $chars variable the value of the suffix and you check if it's unique (guess not because it's getting into the loop) and that condition of $ownshuf != "" returns false from some reason (consider to share with us what's that parameter's value), otherwise the output of $chars would return a string with "-".
REMINDER: Share with us what's that parameter's value