Compare 2 strings in PHP - php

I'm in trouble because i can't figured it out how to find my answer.
I'm creating a wordpress website and i have a search engine
I've created an option in my admin panel and code something to write in my option table, but my problem is now
firstly i grab my options from my database with
$mysynonymvalue = get_option( 'synonym-custom' );
I precise that it returne to me something like this ( mango, apple, banana)(this is an example of course)
My Url is something like this :
http://supserwebsite/wordpress/?sfid=2675&_sf_s=toto
Or this
http://superwebsite/wordpress/?sfid=2675&_sf_s=virtualisation cloud devops
so i've created a variable to catch the queries
$motsclefs3= $_GET['_sf_s'];
Now i want to compare the string $mysynonymvalueconvert with $motsclefs3 to find if it match so i write
if (strpos ($mysynonymvalue, $motsclefs3) ){
echo '<script >
$(document).ready(function(){
$(".vc-tabs-li:nth-child(2)").get(0).click();
});
</script>';
}
else{
echo '
<script >
$(document).ready(function(){
$(".vc-tabs-li").get(0).click();
});
</script>';
};
};
The solution seem to work correctly but i can't have the first result, it coompare indeed with all the results but not my first one.
And it doesn't work so fine because with only one letter it return a match ( for example 'a')
Any solution ?
Thanks

*provided url(s) are not accessible.
Solution:
Create a dictionary of option from db and then search the element which you are looking.

So far i move up a bit !So i came with this
I still have
$mysynonymvalue = get_option( 'synonym-custom' );
$mysynonymvalueconvert = preg_split('/[,]+/',$mysynonymvalue);
To grab my words from my database and to convert it into an array.
(the point of this is to get elements that were wrote by an user elsewhere on the admin panel of wordpress)
I also still have
$motsclefs3= $_GET['_sf_s'];
To grab my actual queries ( that will serv me to compare ). I precise that it return me a string. To be more specific, an URL like this (http://mywebsite/wordpress/?sfid=2675&_sf_s=examen) return me (in string) "examen".
Now my point is still to compare if
$motsclefs3;
is inside
$mysynonymvalueconvert
So i've created a "for" loop like this
for ($i = 0; $i <= count($mysynonymvalueconvert); $i++){
if(in_array($motsclefs3, $mysynonymvalueconvert)){
echo'yes';
break;
}
else{
echo 'no';
break;
};
};
But i'm still blocked, this return "yes" only if it match with the first element from
$mysynonymvalueconvert
So any ideas to help me ?
Thanks!

Related

Can you put multiple elements in an html <a> tag?

Is there any way to create a new a href that remembers all the submitted data earlier. I don't know how to say it properly so I will describe in the code:
The first button
Click me
After the user clicks it, he is redirected to the same page but with the new button :
Click me
And so on :
Click me
How do i create the n variable to be added and increased after the button is pressed ?
( I have a table displayed from a database by using the while command with mysqli_fetch_array($database); )
The table is created like (trivial ) :
$retrieve_items = mysql_query("SELECT * FROM items WHERE id > 0");
$col = 0;
echo '<table width=100% border= 1><tr>';
while($row = mysql_fetch_array( $retrieve_items )) {
$col ++;
echo '<td>'.$row['name_item'].'</td>';
if ($col % 5 == 0 )
{
echo '</tr><tr>';
}
}
echo '</tr></table>';
I recommend not to try managing numbered variable names. If there is no important reason to do so, it will make your logic unnecessarily complicated.
PHP understands array parameters in e.g. $_GET. They are passed from HTML with empty braces appended to the parameter name.
This is a little demo to illustrate this alternative approach:
<?php
// get the passed array or generate a new one
$n = isset($_GET['n']) ? (array) $_GET['n'] : [];
//ppend 2 random numbers
$n[] = rand(1,100);
$n[] = rand(1,100);
//output the link with GET parameters in query
?>
the link
<!-- or let PHP's built-in generate a propper query --><br>
the link
Be aware, that the second link generated by http_build_query contains indexes of the array, which are commonly based on 0.
in php, to access the current query String, you can use
$_SERVER['QUERY_STRING']
so you could so something like
Click me
or you could replace your previous value in the query string

Change GET parameter on PHP and use mod_rewrite

i'm very newbie trying to finish a job, so let me explain the issue here:
i have a chasback website, there are retailers on database, my links are :
a href="/view_retailer.php?rid=<?php echo $tops_row['retailer_id']; ?>"
The php page that show the content have:
if (isset($_GET['rid']) && is_numeric($_GET['rid']))
{
$retailer_id = (int)$_GET['rid'];
}
else
{
header ("Location: index.php");
exit();
}
That display on my URL: /view_retailer?rid=8
I want to change that to /view_retailer?rid=retailer-title
I can't figure why its not working, i have on my DB the columns retailer_id and title.
Then i need to change from /view_retailer?rid=retailer-title to /loja/retailer-title through mod_rewrite.
How can i reach there? thanks for helping me!
I can answer the first bit
a href="/view_retailer.php?rid=<?php echo $tops_row['retailer_id']; ?>"
Needs to be:
<a href="/view_retailer.php?rtitle=<?php echo $tops_row['retailer_title']; ?>"
And
if (isset($_GET['rtitle']) && is_string($_GET['rtitle']))
{
$retailer_title = (string)$_GET['rtitle'];
}
else
{
header ("Location: index.php");
exit();
}
You should also sanitise anything coming from GET/POST to make sure it is safe if you intent to query the database with it.
As for the mod_rewrite. In very rubbish at that so I would not be able to help with that.
How about using 3 tables in your DB?
retailer_id retailer_name and retailer_url_name
values (example)
43 The Awesome Supermarket and awesome-supermarket
Check $_GET['rid'] with a regex pattern to check for letters and the - character and match against retailer_url_name in the DB?
// check for letters and -
if (preg_match('/^[a-z\-]+$/', $_GET['rid']) {
// do stuff here
} else {
// invalid ID
}
In the retailers table add column named "slug" or something like that. Then you have to modify you query thus you are not looking for id but certain string (slug). Make sure that your slugs contains only signs proper for web addresses: no spaces, non-latin letters etc.
When it comes to code, it may look something like that:
if (!empty($_GET['title']))
{
$title = someSanitizeFunc($_GET['title']);
$retailer = db()->queryOne("SELECT id FROM retailers where slug = '".$title."');
}
It's just example, you have to adjust it to your cms or whatever you use.

php countering in javascript doesn't work

okay here is my code :
var co = 0;
var comp = '';
<?php $i = 0;?>
while (co < <?php echo $db->count_rows(); ?>)
{
if ((parseInt(value) >= <?php echo $mfr[$i] ?>) && (parseInt(value) <= <?php echo $mto[$i] ?>))
{
comp = 'T';
break;
}
co++;
<?php $i++; ?>
}
i'm still learning about this whole php and javascript thing, and i know there are many things that i still had to work to to improve my understanding to this both language. that's why i really need your help in this
i'm trying to get the while iteration to work so i can compare the variable from javascript with variable from php which took the value from database. the php variable ('$mfr' and '$mto'), as you can see, is an array. now i want it to look at every element of both and if it meets the condition then it will update the variable 'comp' and stop the whole while iteration
but the problem is the '$i' variable doesn't do the iteration thing. it runs only once so my '$mfr' and '$mto' value doesn't go anywhere. how can i fix this so i can compare the javascript value with the php '$mfr' and '$mto' value?
your help would be much appreciated, thank you :)
EDIT
well, it is actually a function of custom validation for jqgrid.
and i do know that php is a server-side and javascript is a client-side language theoretically, though i don't really know it is practically
what i'm actually trying to do is when a user input a value and submit it, the system will check whether the value that was entered are between value of 'fromid' and 'toid' column of a table in database
here is my full code of the function
function checkid(value)
{
var co = 0;
var comp = '';
<?php $i = 0;?>
while (co < <?php echo $db->count_rows(); ?>)
{
if ((parseInt(value) >= <?php echo $mfr[$i] ?>) && (parseInt(value) <= <?php echo $mto[$i] ?>))
{
comp = 'T';
break;
}
co++;
<?php echo $i++; ?>
}
if (comp != 'T')
{
return [true, "", ""];
}
else
{
return [false, "Value entered is already between a range. Please try again!", ""];
}
}
while this is how i got the '$mfr' and '$mto' variable
<?php
$db=new database($dbtype, $dbhost, $database, $dbuser, $dbpassword, $port, $dsn);
$db->query("select fromid, toid from CORE_ID");
$i = 0;
while($row = $db->get_row())
{
$mfr[$i] = $row[fromid];
$mto[$i] = $row[toid];
$i++;
}
?>
if theres any better way to do this, then please do tell me
Typically, PHP is for server side logic and JS is for client side logic. If you want to send a value from JS to be processed in PHP, you'll probably need to use something like AJAX, which jQuery makes pretty easy with jQuery.ajax().
Getting the client value to be processed is the difficult part. Once you can do that, rewriting your code logic in full PHP should not be difficult.
EDIT: If I'm misunderstanding where variable value comes from, please say so!
EDIT 2: It looks like you want to have client input compared to server side data. JS will not have access to your PHP variables unless they are specifically sent there. Likewise, you can send your JS value to the server for validation in the PHP.
In your case, you could use JSON to send send the JS your validation dates. Assuming you don't have too many dates, it will probably be faster than sending a value to the server and waiting for a response.
I found a good example of using JSON at another post. You can send an array like:
<?php
$xdata = array(
'foo' => 'bar',
'baz' => array('green','blue')
);
?>
<script type="text/javascript">
var xdata = <?php echo json_encode($xdata); ?>;
alert(xdata['foo']);
alert(xdata['baz'][0]);
// Dot notation can be used if key/name is simple:
alert(xdata.foo);
alert(xdata.baz[0]);
</script>
For your code, you could put $mfr and $mto into a single 2D array. Here is how your new JS might look, assuming xdata contains $mfr and $mto:
function checkid(value) {
var co = 0, comp = '', i = 0, nrows = xdata.mfr.length;
while (co < nrows) {
if ((parseInt(value) >= xdata.mfr[i]) && (parseInt(value) <= xdata.mto[i])) {
comp = 'T';
break;
}
co++;
i++;
}
if (comp != 'T') {
return [true, "", ""];
} else {
return [false, "Value entered is already between a range. Please try again!", ""];
}
}
You have a loop in your Javascript, not your PHP. So the PHP is only going to get executed once. You need to rethink your approach. Without knowing what the script is supposed to actually achieve it's difficult to provide working code, but you at least need to put the loop into the PHP instead of the Javascript.
Before I can answer you should understand what's going on exactly:
PHP is being executed on the server, then sends back the result (HTML and Javascript) to the client (the browser).
Javascript is being executed on the client side. So this only starts after PHP is completely done. For this reason you can't mix Javascript and PHP.
Check the source of the page, then you'll see exactly what the server returns (what HTML/Javascript PHP generates) and you'll get a better insight of what happens.
Now, if you understand this, you may be able to solve your own problem. I don't exactly know what you want to do, but I can advice you that if you need Javascript to check values from the database, you should generate Javascript using PHP that defines these values in the Javascript like for example this:
var my_js_var = <?=$my_php_var?>
var another_var = <?=$another_one?>
Now they are defined in Javascript and you can use them (and check them).
When you have a large database it can become inefficient to do it like this and you might want to look into a technology called AJAX, which allows Javascript to do a request to the server and get back data from a PHP script.
You would also want to do this if there's data involved you don't want to be publicly viewable (because everyone can look into the source of your page.

Only add item as needed in PHP array

I have bits of code I want to throw in to my site, and provisioned a space right after <body> using 'flairs' (divs) that sit outside the design. Here's the code:
//Add Flair Containers as needed
if($flairs>0){
echo "<!--Flair Graphics (if needed)-->\n";
while($fQty = --$flairs+1){ //-- subracts 1, +1 accounts for 1 being 0
$flair = array($flair1, $flair2, $flair3);
foreach($flair as $flairCode){
echo "<div id=\"flair-".$fQty++."\">".$flairCode."</div>\n";
};
};
};
It prints correctly, where content = $flair1, $flair2, and so on.
<div id="flair-1">Content1</div>
<div id="flair-2">Content2</div>
<div id="flair-3">Content3</div>
But if $flair2/$flair3 is empty, it still prints a div. How can I fix this?
Within your foreach loop you can check if the value is empty and continue (i.e. skip) to the next value if it is.
Like so:
if($flairs>0){
echo "<!--Flair Graphics (if needed)-->\n";
while($fQty = --$flairs+1){ //-- subracts 1, +1 accounts for 1 being 0
$flair = array($flair1, $flair2, $flair3);
foreach($flair as $flairCode){
if (empty($flairCode)) continue;
echo "<div id=\"flair-".$fQty++."\">".$flairCode."</div>\n";
};
};
};
I suspect that you could simply prepend if($flairCode) to your echo statement. That would make your inner loop:
foreach($flair as $flairCode){
if($flairCode) echo "<div id=\"flair-".$fQty++."\">".$flairCode."</div>\n";
};
Some points to note:
Since the $flair array will always be the same, construct it outside of the loop (this will let you evaluate the condition only once too.
Using $fQty++ is not enough to guarantee unique ID's, especially since every time it hits the while the value is reset. I suggest $fQty should not be part of the while condition and simply stay as an independent tally.
Stop using double-quotes. They're slow.

How Can I Move This <td> Tag To The Next Line?

I have a problem:
Here's a block of the code:
function draw()
{
$out_string="";
$out_string.=$this->script;
reset($this->fields);
$num_list_box=0;
while( $field = each($this->fields) )
{
if (isset($this->fields[$field[1]->field]->options))
{
if (preg_match("/<script type=\"text\/javascript\">/i",$this->fields[$field[1]->field]->options[0][1])&& $this->fields[$field[1]->field]->value!="")
{
if ($num_list_box==0) $out_string.= "<script type=\"text/javascript\">levels.forValue(\"".$field_prev[0]."\").setDefaultOptions(\"".$this->fields[$field[1]->field]->value."\");</script>\n";
else $out_string.= "<script type=\"text/javascript\">levels.forValue(\"".$field_prev[0]."\").forValue(\"".$field_prev[1]."\").setDefaultOptions(\"".$this->fields[$field[1]->field]->value."\");</script>\n";
$field_prev[]=$this->fields[$field[1]->field]->value;
$num_list_box++;
} else
{
$field_prev[0]=$this->fields[$field[1]->field]->value;
$num_list_box=0;
}
}
}
$out_string.=$this->draw_title();
$out_string.=$this->draw_header();
$out_string.= "<table class=\"forms\">\n";
$field=array_keys($this->fields);
reset($field);
$ind_first=true;
while( list($pos,$field_name) = each($field) )
{
if ($this->num_cols>0) {
if ($this->fields[$field_name]->col==1){
if ($ind_first) $ind_first=false;else $out_string.="</tr>";
$out_string.="<tr><td class=\"field_title\">";}
else $out_string.="<td class=\"field_title\">";
$out_string.= $this->fields[$field_name]->title."</td>";
$colspan="";
if ($this->num_cols>1) {
if ($this->fields[$field_name]->col==1 && array_key_exists($pos+1,$field) && $this->fields[$field[$pos+1]]->col==1)
$colspan="colspan=\"3\"";
}
$out_string.="<td class=\"field_value\" $colspan>";
$out_string.=$this->fields[$field_name]->draw()."</td>";
} else
{
if ($ind_first) $ind_first=false;else $out_string.="</tr>";
$out_string.="<tr><td class=\"field_value\">".$this->fields[$field_name]->title."<br />";
$out_string.=$this->fields[$field_name]->draw()."</td>";
}
}
$out_string.= "</tr></table>\n";
return $out_string;
}
This above block of code produces something like this:
I want it such that in the example provided that the word "Transaction" is above the text box.
Please help, the person that programmed this part is indisposed and we've got a deadline.
Thanks for the help.
P.S. The CSS class name for the text is: field_title and the one for the textbox is field_value
Thanks once more.
You will have to debug that code to find out when the label "Transaction" is getting inserted into that cludge of table code. Once you find where "Transaction" is inserted you can then create new logic to add another TR that colspans the table and place the label on that new row.
Good luck, looks like a headache.
Your code is apparently building a rather complex form based on some data ($fields property of the class). I guess some "field settings" (like col) describe how the form should look like.
So, your code is doing things that are neither described in your question nor in the code itself. Furthermore, we have no clue what the complete form currently looks like, so we can't even guess the intention of the code.
Your request, to let the description appear above the selection box(?) could be done probably throwing away half of the code, but that won't help you.
PS: Please check the FAQ - this site is for questions, not for finding people to do your (or elses) work. You should really have a programmer solve your problem directly having access to the whole page.

Categories