Joining a string with input fields = one value - php

how can I get this result as a value of LUC-1701-000005 field I made ..
I get the current value from one field ($value = $_POST['wpuef_options']['c26'];), but I want to make it easier for customers to not enter those LUCs ... than just numbers..
current code looks like this ..
for($I=0; $I<= 5; $I++){
if($I == 0){
$value = $_POST['wpuef_options']['c26'];
}
else if($I == 1){
$value = $_POST['wpuef_options']['c30'];
}
else if($I == 2){
$value = $_POST['wpuef_options']['c34'];
}
else if($I == 3){
$value = $_POST['wpuef_options']['c44'];
}
else if($I == 4){
$value = $_POST['wpuef_options']['c50'];
}
this is something I need ..but this is not correct ..
$value = "LUC-" + $_POST['wpuef_options']['c26'] + "-" + $_POST['wpuef_options']['c23'];

Try this:
$value = "LUC-" . $_POST['wpuef_options']['c26'] . "-" . $_POST['wpuef_options']['c23'];
You are using + for concatenation, which is wrong, in PHP it is just . .

Related

Use PHP while loop to create advance filter

I have a problem and that is I want to create a link on a website like people can click the link to show certain products only depending on percentage. like for example, i have a column in my database with discount percentage and it will show min discount and max discount. assuming we have min and max discount. $min=12 and $max=94; and I want to put them in links to show only products with certain discounts only like filtering. below is the example of the link.
<a href="#">12% to 20%</a
21% to 30%
31% to 40% and so on until it reaches
81% to 90% and the last will be
91% to 94%
smallest and largest numbers will be coming from a column from database and they can change frequently. i came up with solution and its working fine but my code is too long and its like I took to many steps which could be done in few lines of code. I have pasted my working code below but I am sure this can be reduced to few lines of code.
$catsql25 = "SELECT MAX(down_percentage) as largest FROM hot_deals";
$catquery25 = mysqli_query($conn, $catsql25);
while ($row25 = mysqli_fetch_array($catquery25, MYSQLI_ASSOC)){
$largest_number = $row25['largest'];
}
$catsql26 = "SELECT MIN(down_percentage) as smallest FROM hot_deals";
$catquery26 = mysqli_query($conn, $catsql26);
while ($row26 = mysqli_fetch_array($catquery26, MYSQLI_ASSOC)){
$smallest_number = $row26['smallest'];
}
$array_tens = array(10,20,30,40,50,60,70,80,90,100);
foreach ($array_tens as $value){
if(($value - $smallest_number <= 10) && ($value - $smallest_number > 0)){
echo '<a href="/exp.php?fst='.$smallest_number.'&lst='.$value.'"><div class="lfmen2">';
echo $smallest_number." to ".$value."</div></a>";
$next_num = $value + 1;
$next_ten = 9;
$stop_num = floor($largest_number / 10);
$stop_num2 = $stop_num * 10;
//echo $stop_num2.'<br>';
$num_rounds = $stop_num2 - $value;
$num_rounds2 = $num_rounds / 10;
//echo $num_rounds2;
for ($i = 1; $i <= $num_rounds2; $i++){
$end_num = $next_num + $next_ten;
echo '<a href="/exp.php?fst='.$next_num.'&lst='.$end_num.'"><div class="lfmen2">';
echo $next_num;
echo " to ";
echo $end_num;
echo "</div></a>";
$next_num += 10;
$end_num += 10;
}
}
}
foreach ($array_tens as $value2){
if(($largest_number - $value2 < 10) && ($largest_number - $value2 > 0)){
$lsst = $value2 + 1;
if($lsst != $largest_number){
echo '<div class="lfmen2">'.$lsst." to ".$largest_number."</div>";
}
elseif($lsst == $largest_number){
echo '<div class="lfmen2">'.$largest_number.'</div>';
}
}
}
I know its all mess but..
Thanks.
First thing you could do is only one SQL Query :
$catsql = "SELECT MAX(down_percentage) as largest, MIN(down_percentage) as smallest FROM hot_deals";
And then you'll need only one loop :
$catquery = mysqli_query($conn, $catsql);
while ($row = mysqli_fetch_array($catquery, MYSQLI_ASSOC)){
$largest_number = $row['largest'];
$smallest_number = $row['smalest'];
}
After that, you could make only one foreach loop. The two "if" conditions could be in the same loop :
foreach ($array_tens as $value) {
if (($value - $smallest_number <= 10) && ($value - $smallest_number > 0)) {
echo '<a href="/exp.php?fst='.$smallest_number.'&lst='.$value.'"><div class="lfmen2">';
echo $smallest_number." to ".$value."</div></a>";
$next_num = $value + 1;
$next_ten = 9;
$stop_num = floor($largest_number / 10);
$stop_num2 = $stop_num * 10;
//echo $stop_num2.'<br>';
$num_rounds = $stop_num2 - $value;
$num_rounds2 = $num_rounds / 10;
//echo $num_rounds2;
for ($i = 1; $i <= $num_rounds2; $i++) {
$end_num = $next_num + $next_ten;
echo '<a href="/exp.php?fst='.$next_num.'&lst='.$end_num.'"><div class="lfmen2">';
echo $next_num;
echo " to ";
echo $end_num;
echo "</div></a>";
$next_num += 10;
$end_num += 10;
}
}
if (($largest_number - $value < 10) && ($largest_number - $value > 0)) {
$lsst = $value + 1;
if ($lsst != $largest_number) {
echo '<div class="lfmen2">'.$lsst." to ".$largest_number."</div>";
} elseif ($lsst == $largest_number) {
echo '<div class="lfmen2">'.$largest_number.'</div>';
}
}
}
To make it more readable, you could also comment your code to know what do what.
This and a good indentation and you're right.
Hope it helps.

For loop variable, confused about single and double quotes

I'd like to make the following code a for loop to make everything read better, but I can't seem to get the quotes right and end up with a blank page
if ($_POST['week'])
{
$week = $_POST['week'];
}
//or check for a value submitted by the week menu
elseif ($_POST["user_week1"] == "week1") {
$week = "1";
}
elseif ($_POST["user_week2"] == "week2") {
$week = "2";
}
else if ($_POST["user_week3"] == "week3") {
$week = "3";
}
else if ($_POST["user_week4"] == "week4") {
$week = "4";
}
else if ($_POST["user_week5"] == "week5") {
$week = "5";
}
else if ($_POST["user_week6"] == "week6") {
$week = "6";
}
else {
$week = "1";
}
I tried to do:
if ($_POST['week'])
{
$week = $_POST['week'];
}
for ($i = 1; $i<7; $i++)
{
else if ($_POST["user_week'.$i.'"] == "week'.$i.'") {
$week = $i;
}
}
else {
$week = "1";
}
But that didn't work out too well, I tried using double quotes instead of single around the variables, plus '" and "' to no avail.
Can anyone help with this, or point me towards a good resource on single and double quotes for variables?
Are you all igrnoring the fact that the else if mustn`t be there!?
What you should do is the following
$week = "1";
if ($_POST['week']) {
$week = $_POST['week'];
} else {
for ($i = 1; $i < 7; $i++) {
if ($_POST["user_week" . $i] == "week" . $i) {
$week = $i;
break;
}
}
}
elseif ($_POST['user_week' . $i] == 'week' . $i)
above correction should work

How can I "limit" the page numbers of a forum/blog in PHP

I'm trying to fix something with which I'm not familiar with and don't know how to proceed. The forum on which I'm working is suppose to show under "TOP 50" only the most commented topics (2 pages by 25 topics) but it shows all topics (by 25) without any limitation of the pages. I need only the first 2 pages - but don't know how to get rid of the others?
I'm even not sure that the below code is the responsible one but please have a look and give me a hint if you see any solution.
This is the code:
{
public function __construct()
{
parent::__construct();
}
public function get_forum()
{
if ($_GET['l'] && ($_GET['l'] == 'leng' || $_GET['l'] == 'lrus' || $_GET['l'] == 'lde' || $_GET['l'] == 'ltr'))
$l = substr($_GET['l'], 1);
else
$l = 'eng';
(isset($_GET['num'])) ? $page = intval($_GET['num']) : $page = 1;
$id_user = intval($_SESSION['user_id']);
$lang = language::getLang();
if ($_GET['el']) {
switch ($_GET['el']) {
case 'categories':
return $this->getCategories($l);
break;
case 'top':
$top_lang = $_GET['ln'];
$c = $this->db->selectAssoc($this->db->Select('*', 'forum_categories ,forum_thems', "`forum_categories`.`lang` = '" . $l
. "' AND `forum_thems`.`id_categories` = `forum_categories`.`id`"));
$total_pages = count($c) / 25;
$p = "<div class=\"pageCounter_box\">Pages:";
if (empty($_GET['p'])) {
$_GET['p'] = 1;
}
for($i=1; $i<$total_pages+1; $i++){
if ($i == $_GET['p']) {
$class = 'class="active_page"';
}
$p .= "<a href=\"$top_lang/smoke/{$_GET['l']}/top?p=$i\" $class>$i</a>";
}
$p .= "</div>";
return $this->getTop($l) . $p;
break;
I think you could do a check in there of If ($total_pages > 2) { $total_pages = 2};
$c = $this->db->selectAssoc(
$this->db->Select('*', 'forum_categories ,forum_thems', "`forum_categories`.
`lang` = '" . $l. "' AND `forum_thems`.
`id_categories` = `forum_categories`.`id`"));
$total_pages = count($c) / 25;
if ($total_pages >2) { //limit to two pages
$total_pages = 2;
}
$p = "<div class=\"pageCounter_box\">Pages:";
if (empty($_GET['p'])) {
$_GET['p'] = 1;
}
"thanks a lot - great help! Do you further see why both pages might show active (page counter shows both active) when showing page 1? Page 2 is fine, there only Page 2 shows active..."
The $class variable is staying set, you need to have an else that sets the class to an empty string
for($i=1; $i<$total_pages+1; $i++){
if ($i == $_GET['p']) {
$class = 'class="active_page"';
} else {
$class = '';
}
$p .= "<a href=\"$top_lang/smoke/{$_GET['l']}/top?p=$i\" $class>$i</a>";
}

Feature like FB's "X, Y and Z other people like this"

I'm trying to implement something like facebook's like widget which says something like:
You, Name1, Name2 and 20 other people like this
I fetched all my data to be able to display this HTML, but I can't seem to find the right algo to form the HTML string.
My main problem is that I don't know when to put the and string or the , (comma) string. If I just had to put names, it would work, but the problem is that the You string always has to be first.
I'm going to paste my code here and the output I'm getting for some special cases (it's PHP).
$current_user = 0;
$html = "";
$count = count($result);
$key = 0;
foreach($result as $liked){
if($key + 1 > $limit)
break;
if($liked->uid == $user->uid){
$current_user = 1;
continue;
}
$html .= "<a href='".$liked->href."'>".$liked->name."</a>";
if($key < $count - 2)
$html .= ", ";
elseif($key == $count - 2 && $key + 1 != $limit)
$html .= " and ";
$key++;
}
if($current_user){
$userHtml = "You";
if($count > 2)
$userHtml .= ", ";
elseif($count > 1)
$userHtml .= " and ";
$html = $userHtml.$html;
}
$html = "♥ by ".$html;
if($count > $limit){
$difference = $count - $limit;
$html .= " and ".$difference." ".format_plural($difference,"other","others");
}
return $html;
And in the special case where the current user is the last one to like this, it will show:
♥ by You, admin, edu2004eu and
Notice the and word doesn't have anything after it, because You should have been after it, but I put it at the beginning. Any help? I just need the logic, not the actual code.
You can try something like this:
$likedBy = array('admin', 'eduard', 'jeremy', 'someoneelse');
// check if I like it and if so move me to the front
if (in_array($currentUsername, $likedBy)) {
$me = array_search($currentUsername, $likedBy);
unset($likedBy[$me]);
array_unshift($likedBy, 'You');
}
// remove anything after the limit
$extra = array_splice($likedBy, 3);
// the comma list
$html = implode(', ', $likedBy);
// any extras? if so, add them here, if not rewrite the list so
// it's "You, Eduard and admin"
if (!empty($extra)) {
$html .= ' and '.count($extra);
} else {
$lastguy = array_splice($likedBy, 1);
$html = implode(', ', $likedBy).' and '.$lastguy;
}
$html .= ' like this';
Eduard,
You can fix this simply by putting $key++; at the top of the loop and taking out all the places where you have $key + 1 in the loop.
I think what's happening is that $key + 1 is assuming that there is a current user.
This line would also not display the current user if they are not in the first $limit number of entries
if($key + 1 > $limit)
break;
You can fix this by putting this after the code that looks for the current user.
In Java (I know, but its what I had running) it would look something like:
List<String> users = Arrays.asList("Brian","Tom","Jack","John");
int key = 0;
String html = "";
String currentUser = "Brian";
int limit = 3;
boolean foundCurrentUser = false;
for (String user : users) {
key ++;
if (currentUser == user) {
foundCurrentUser = true;
continue;
}
if (key > limit) {
continue;
}
html += user;
if (key < users.size() - 1) {
html += ",";
} else if (key == users.size() - 1 && key != limit) {
html += " and ";
}
}
if (foundCurrentUser) {
String userHTML = "You";
if (key > 2) {
userHTML += ", ";
} else if (key == 1) {
userHTML += " and ";
}
html = userHTML + html;
}
html = "Likeed by " + html;
if (users.size() > limit ) {
html += " and 3 other people";
}
System.out.println(html);

How to reliably find similar strings to that typed in

I have an interface where a user will enter the name of a company. It then compares what they typed to current entries in the database, and if something similar is found it presents them with options (in case they misspelled) or they can click a button which confirms what they typed is definitely new and unique.
The problem I am having is that it is not very accurate and often brings up dozens of "similar" matches that aren't that similar at all!
Here is what I have now, the first large function I didn't make and I am not clear on what exactly it does. Is there are much simpler way to acheive what I want?
// Compares strings and determines how similar they are based on a nth letter split comparison.
function cmp_by_optionNumber($b, $a) {
if ($a["score"] == $b["score"]) return 0;
if ($a["score"] > $b["score"]) return 1;
return -1;
}
function string_compare($str_a, $str_b)
{
$length = strlen($str_a);
$length_b = strlen($str_b);
$i = 0;
$segmentcount = 0;
$segmentsinfo = array();
$segment = '';
while ($i < $length)
{
$char = substr($str_a, $i, 1);
if (strpos($str_b, $char) !== FALSE)
{
$segment = $segment.$char;
if (strpos($str_b, $segment) !== FALSE)
{
$segmentpos_a = $i - strlen($segment) + 1;
$segmentpos_b = strpos($str_b, $segment);
$positiondiff = abs($segmentpos_a - $segmentpos_b);
$posfactor = ($length - $positiondiff) / $length_b; // <-- ?
$lengthfactor = strlen($segment)/$length;
$segmentsinfo[$segmentcount] = array( 'segment' => $segment, 'score' => ($posfactor * $lengthfactor));
}
else
{
$segment = '';
$i--;
$segmentcount++;
}
}
else
{
$segment = '';
$segmentcount++;
}
$i++;
}
// PHP 5.3 lambda in array_map
$totalscore = array_sum(array_map(function($v) { return $v['score']; }, $segmentsinfo));
return $totalscore;
}
$q = $_POST['stringA'] ;
$qLengthMin = strlen($q) - 5 ; // Part of search calibration. Smaller number = stricter.
$qLengthMax = strlen($q) + 2 ; // not in use.
$main = array() ;
include("pdoconnect.php") ;
$result = $dbh->query("SELECT id, name FROM entity_details WHERE
name LIKE '{$q[0]}%'
AND CHAR_LENGTH(name) >= '$qLengthMin'
#LIMIT 50") ; // The first letter MUST be correct. This assumption makes checker faster and reduces irrelivant results.
$x = 0 ;
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$percent = string_compare(strtolower($q), strtolower(rawurldecode($row['name']))) ;
if($percent == 1) {
//echo 1 ;// 1 signifies an exact match on a company already in our DB.
echo $row['id'] ;
exit() ;
}
elseif($percent >= 0.6) { // Part of search calibration. Higher deci number = stricter.
$x++ ;
$main[$x]['name'] = rawurldecode($row['name']) ;
$main[$x]['score'] = round($percent, 2) * 100;
//array_push($overs, urldecode($row['name']) . " ($percent)<br />") ;
}
}
usort($main, "cmp_by_optionNumber") ;
$z = 0 ;
echo '<div style="overflow-y:scroll;height:175px;width:460px;">' ;
foreach($main as $c) {
if($c['score'] > 100) $c['score'] = 100 ;
if(count($main) > 1) {
echo '<div id="anysuggested' . $z . '" class="hoverdiv" onclick="selectAuto(' . "'score$z'" . ');">' ;
}
else echo '<div id="anysuggested' . $z . '" class="hoverdiv" style="color:#009444;" onclick="selectAuto(' . "'score$z'" . ');">' ;
echo '<span id="autoscore' . $z . '">' . $c['name'] . '</span></div>' ;
$z++ ;
}
echo '</div>' ;
Comparing strings is a huge topic and there are many ways to do it. One very common algorithm is called the Levenshtein difference. This is a native implementation in PHP but none in MySQL. There is however an implementation here that you could use.
You need aproximate/fuzzy string matching.
Read more about
http://php.net/manual/en/function.levenshtein.php, http://www.slideshare.net/kyleburton/fuzzy-string-matching
The best way would be to use some index based search engine like SOLR http://lucene.apache.org/solr/.

Categories