Trouble with PHP if else logic and variables - php

So, I have a couple of variables in PHP, and they are generated from different places. $new_ip comes from the following command:
$new_ip = file_get_contents('http://www.ipaddresscheck.comlu.com/ip.php');
And the $old_ip comes from:
$sql = mysql_query('SELECT * FROM ip ORDER BY id DESC LIMIT 1');
$row = mysql_fetch_array( $sql );
$old_ip = $row['current_ip'];
My problem is, I am getting incorrect results from:
if ($old = $new)
{
$different = '1';
}
else {
$different = '2';
}
echo $different;
I ALWAYS get 2, wether the IPs are the same or not; if I use '==' as the comparison, I ALWAYS get 1.
When I run the following code, I get the following output:
var_dump($old_ip);
var_dump($new_ip);
Output
string(15) "123.123.123.123" string(167) "184.6.216.163 "
Are the variables different types? If So, can I make them the same so I am only comparing the IP and not the type? If the IPs are the same I should get '1' and if they are different, I should get '2', right?

Your problem is lurking here:
string(15) "123.123.123.123" string(167) "184.6.216.163 "
^^^
The address retrieved from your database is coming along with 154 unwanted characters. trim() both strings and then do the comparison.
Oh - and you should really shorten the field that stores the IP address. 15 characters should do.

Code
if ($old = $new) // you are using assignment operator here
{
$different = '1';
}
Should be
if ($old == $new) //Equal to operator
{
$different = '1';
}
Also confirm the variable names are
$old and $new or $old_ip and $new_ip

Assignment ( = ): Assigns the value on the right to the variable on the left
Equality ( == ): Checks if the left and right values are equal
Identical ( === ): Checks if the left and right values are equal AND identical (same variable type)
Example:
$a = 1; // Sets the value of $a as the integer 1
$b = TRUE; // Sets the value of $b to the boolean TRUE
if ($a == $b){
echo 'a is equal to b.';
}
if ($a === $b){ // compare VALUE and data type: if $a(integer) === $b(boolean)
echo 'a is identical and equal to b.';
}
if ($a = $b){
echo '$b value to variable $a';
}
In your code i noticed a problem. A space is there in second IP address. so
string(15) "123.123.123.123" string(167) "184.6.216.163 "
^
Trim both IP address.
If not work, then convert it to other datatype and compare.(Just for debugging purpose. :))

OLD :
if ($old = $new){
$different = '1';
}
New Correct :
if ($old == $new){
$different = '1';
}
you are using (=) assignment operation in the place of comparison operation.

As far as I can see the behaviour is normal because you are using $old and $new both are unset.
$new_ip = file_get_contents('http://www.ipaddresscheck.comlu.com/ip.php');
$sql = mysql_query('SELECT * FROM ip ORDER BY id DESC LIMIT 1');
$row = mysql_fetch_array( $sql );
$old_ip = $row['current_ip'];
The next code will always give 2 because $new is unset. What you are doing here is assigning $old the value of $new and since $new is unset $old = $new will always be false.
if ($old = $new)
{
$different = '1';
} else {
$different = '2';
}
echo $different;
In the next example you are actually comparing $old and $new. Since both are unset the expression $old == $new will always be true.
if ($old == $new)
{
$different = '1';
} else {
$different = '2';
}
echo $different;
What you need to do is using the right vars and trim them.
// get new ip and trim white spaces
$new_ip = trim(file_get_contents('http://www.ipaddresscheck.comlu.com/ip.php'));
// get the old ip
$sql = mysql_query('SELECT * FROM ip ORDER BY id DESC LIMIT 1');
$row = mysql_fetch_array( $sql );
$old_ip = $row['current_ip'];
if ($old_ip == $new_ip)
{
$different = '1';
} else {
$different = '2';
}
echo $different;
I am not trimming white spaces on $old_ip because I guess that you will be using $new_ip to update your database and since $new_ip is already trimmed we can be sure that $old_ip has no white spaces.
You should always have php warnings enabled when coding!
It would have popped you a warning because you used unset vars.
PS : note that this code will only work as expected if file_get_contents() returns a IP with white spaces, the output could be different (error output, not able to detect ip correctly, ... etc)

Related

How to compare variable $p in a list with variables that came before it?

Alright, so this may seem like a strange question but I've got this list of variables, $r1-$r50, and I would like to compare all these variables to each other. However, I only want to look backwards in the list, so if I take a look at $r23 I do not want to compare it to $r24 and above. Is there a way to do this easily? I'm currently trying to use variable variables but I can't get them working. I have looked around but all I've found has to do with easily comparing one variable to many others, not to comparing to previous ones. Any ideas? Here's my code:
<?php
$r0 = " ";
$nr = 1;
$vnr = 1;
$concheck = "true"; // I use this to break out of my while loop, I guess I could use break; maybe but meh.
while ($nr < 50) {
$nrtemp = 0;
while ($concheck == "true") {
if ($r{$nr} == $r{$nrtemp}) {
echo "($r{$nr} == $r{$nrtemp})";
//remove variable;
$concheck = "false";
} elseif ($nrtemp >= 50) {
echo "($nrtemp >= 50)";
$v{$vnr} = $r{$nr};
++$vnr;
$concheck = "false";
} else {
echo "else";
++$nrtemp;
$concheck = "true";
};
};
++$nr;
};
?>
To further clarify:
All I basically want to do to is filter the list. For example:
$r1 = "a";
$r2 = "b";
$r3 = "c";
$r4 = "b";
$r5 = "e";
$r6 = "f";
But I don't want 2 variables specifying "b".
I want to end up with a list of variables without any doubles. And that's basically it.
Anybody?
I think easy is to maintain an array. Put all values to that array and apply array_unique() and you will get a list of unique/non-repeated value.
Ref: array_unique()

Selected 2 tables but outputs all from 1 and only 1 from second table - php mysql

here is my code:
<?php
global $liID, $liClass;
$liV = "SELECT * FROM css";
$li1 = mysqli_query($connect,$liV);
$li = mysqli_fetch_array($li1);
$liID = $li['liID'];
$liClass = $li['liClass'];
$post = "SELECT * FROM post ORDER BY id DESC LIMIT 5";
$post1 = mysqli_query($connect,$post);
$postV = mysqli_fetch_array($post1);
do {
printf("<a href='view.php?id=%s'><li id='%s' class='%s'><img src='%s'><div class='tip'><h5>%s</h5></div></li></a>",$postV['id'],$li['liID'],$li['liClass'],$postV['slimg'],$postV['title']);
}
while ($postV = mysqli_fetch_array($post1) && $li = mysqli_fetch_array($li1));
?>
result is that, i have data only from "css" exactly as i need,
but from "post" i have only one data.
You've got horribly constructed logic. Your while() condition is NOT doing what you expect, and is being parsed/executed as
while($postV = (fetch($post1) && ($li = fetch($li1)))) {
Note the positioning of the brackets. $postV is getting the result of the boolean && of your two fetch calls. As long as both return non-falseish values, $postV will simply become a boolean TRUE. e.g. it's the equivalent of:
$x = 'foo';
$y = 'bar';
$p = $x && $q = $y;
var_dump($p);
This will output a boolean true, not foo as you're expecting it to.
Try this instead:
while (($postV = mysqli_fetch_array($post1)) && ($li = mysqli_fetch_array($li1)));
^-----------------------------------^ ^------------------------------^
Note the indicated extra brackets.

Compare first letter string of previous value in row after foreach loop pdo

The code i am using, but doesnt give the proper result.
foreach ($dbo->query($sql) as $row) {
$a = "$row[Description_code]";
$aa = $a[0]; // first of string
$b = prev($a);
$bb = $b[0]; // first of string
echo "$aa";
if ($aa != $bb){
echo "<p></p>";
}
}
This isnt working like it should, results of $aa looks like AAABBCCCCDDEEFFFF etc
If A != A it should give page break, resulting in html
AAA
BB
CCCC
DD
EE
FFFF
Since you're unable to understand what I'm saying, an example:
php > $a = 'abcdefghijkl';
php > $aa = $a[0];
php > $b = prev($a);
PHP Warning: prev() expects parameter 1 to be array, string given in php shell code on line 1
php > $bb = $b[0];
php > echo "$a $aa $b $bb\n";
abcdefghijkl a
^^-- $a ^--$aa hey! where's $b & $bb ?????
As the warning above says, you CANNOT use prev() on a string, because it's NOT an array.
Your code should be:
$previous_char = '';
while($row = mysql_fetch_assoc($result)) {
$string = $row['Description of Code'];
$first_char = substr($string, 0, 1);
if ($first_char <> $previous_char) {
echo '<p></p>';
$previous_char = $first_char;
}
echo $first_char;
}
Your code, even if it written properly, could NEVER work, because you never consider the data from the PREVIOUS row of data fetched. You only consider the data from the CURRENT row. The first char of the current row will always match itself, so you never get a line break.

Filtering an array retrieved from MySQL after replacing strings

I've been having a lot of trouble getting this code to work and I was wondering if you guys could take a look at it and maybe see what I'm doing wrong.
Here is what I'm trying to do:
I have a URL which contains two variables $buildname, and $author.
These two variables are inserted into a query for Mysql to retrieve a unique row, where it then fetches an array of information for that row. For example, each row would contain information such as:
ID, Author, Buildname, Weapon, Mod1, Mod2 .. Mod 8, Polarity 1, Polarity 2.. Polarity 8, hidden.
I then want to check each value, and see if it is equal to a string such as
"No mod in this slot"
and replace it with
""
So that I can later use array_filter to get rid of that section of the array.
My problem(s) I'm encountering are the following
When I fetch the array, and perform a foreach loop which echos each element of the array, it is in duplicate. For example, if I perform
foreach($info_array as $string)
{
echo $string;
}
I get the results
66SteelyDanSteelyDanAcrid BabiesAcrid BabiesAcridAcridNo mod in this slotNo mod in this slotNo mod in this slotNo mod in this slotNo mod in this slotNo mod in this slot
Where the ID is 6, the author is SteelyDan, the buildname is Acrid Babies, the first mod is No mod in this slot... and so on.
Why is it duplicating like this?
Continuing...
My code to replace these values "n" (which would appear as a polarity value) and "No mod in this slot" (Which would appear as a mod value) is the following:
foreach($info_array as &$string)
{
if($string == "n")
{
str_replace("n","","n");
}
if($string == "No mod in this slot")
{
str_replace("No mod in this slot","","No mod in this slot");
}
}
I would then filter the array to get rid of any empty values.
However, this code isn't performing properly.
If I echo the array after I run the loop, all values are the same.
What the heck am I doing wrong here?? This is my full code:
foreach($info_array as $key => $string)
{
if($string == "n" || $string == "No mod in this slot")
{
unset($info_array[$key]);
}
}
$page_id = $info_array['id'];
$page_author = $info_array['author'];
$page_buildname = $info_array['buildname'];
$page_weapon = $info_array['weapon'];
$page_mod1 = $info_array['mod1'];
$page_mod2 = $info_array['mod2'];
$page_mod3 = $info_array['mod3'];
$page_mod4 = $info_array['mod4'];
$page_mod5 = $info_array['mod5'];
$page_mod6 = $info_array['mod6'];
$page_mod7 = $info_array['mod7'];
$page_mod8 = $info_array['mod8'];
$page_polarity1 = $info_array['polarity1'];
$page_polarity2 = $info_array['polarity2'];
$page_polarity3 = $info_array['polarity3'];
$page_polarity4 = $info_array['polarity4'];
$page_polarity5 = $info_array['polarity5'];
$page_polarity6 = $info_array['polarity6'];
$page_polarity7 = $info_array['polarity7'];
$page_polarity8 = $info_array['polarity8'];
$page_category = $info_array['category'];
$page_description = $info_array['description'];
$page_date = $info_array['date'];
$page_hidden = $info_array['hidden'];
//Check if the accessing user is the same as the page creator. If not, check if page is hidden. If page is hidden, redirect to index.php.
if($_SESSION['username'] != $page_author)
{
if($page_hidden == y)
{
header("Location: index.php");
}
}
//Retrieve Page Main Image
$page_main_image = convertImageMainPageWeapon($page_weapon);
//Set up mod and polarity associative arrays
$mod_array = array(
"image_mod1" => "$page_mod1",
"image_mod2" => "$page_mod2",
"image_mod3" => "$page_mod3",
"image_mod4" => "$page_mod4",
"image_mod5" => "$page_mod5",
"image_mod6" => "$page_mod6",
"image_mod7" => "$page_mod7",
"image_mod8" => "$page_mod8"
);
$polarity_array = array(
"image_polarity1" => "$page_polarity1",
"image_polarity2" => "$page_polarity2",
"image_polarity3" => "$page_polarity3",
"image_polarity4" => "$page_polarity4",
"image_polarity5" => "$page_polarity5",
"image_polarity6" => "$page_polarity6",
"image_polarity7" => "$page_polarity7",
"image_polarity8" => "$page_polarity8"
);
foreach($mod_array as &$string)
{
if($string != "")
{
$string = convertImageMod($string);
}
}
foreach($polarity_array as &$string)
{
if($string != "")
{
$string = convertImagePolarity($string);
}
}
EDIT: Code fixed. The variables are now 'unset' but I receive "undefined index errors"
Thanks!
Instead of putting empty values into your array and then later using array_filter, why not just remove the array elements:
foreach($info_array as $key => $string)
{
if($string == "n" || $string == "No mod in this slot")
{
unset($info_array[$key]);
}
}
Try this
foreach($info_array as &$string)
{
if($string == "n")
{
$string = str_replace("n", "", $string);
}
if($string == "No mod in this slot")
{
$string = str_replace("No mod in this slot", "", $string);
}
}
[edit]removed quotes surrounding $string in str_replace, added variable assignment, skimmed too much originally and didn't notice this wasn't already done.

This php string joining is driving me crazy!

I want to prepend a "0" in front of a $_POST
$currency = $_POST['Currency']; // lets say 900
$currency = "0".$currency;
echo $currency;
It should have returned 0900 but it returns 900.
Any ideas?
EDIT
This is the full function
function validate(){
$ref = $this->input->post('Ref');
$shop = $this->input->post('Shop');
$amount = $this->input->post('Amount')*1000;
//$currency = $this->input->post('Currency');
//$currency = $_POST['Currency']; // lets say 900
//$currency = "0".$currency;
$currency = str_pad($_POST['Currency'],4,'0',STR_PAD_LEFT);
$query = $this->db->query("SELECT * FROM shop_validation WHERE merchant_ref = '$ref' ");
if($query->num_rows() > 0) {
$row = $query->row_array();
$posts = "";
foreach ($_POST as $name => $value) {
$posts .= $name." / ".$value;
}
$this->db->query("INSERT INTO transactions (shop,amount,currency,posts) VALUES ('$shop','$amount','$currency','$posts')");
if($row['merchant_ref'] != $ref)
{
echo "[NOTOK]";
return;
}
if($row['merchant_id'] != $shop)
{
echo "[NOTOK]";
return;
}
if(trim($row['amount']) != $amount)
{
echo "[NOTOK]";
return;
}
if($row['currency_code'] != $currency)
{
echo "[NOTOK]";
return;
}
echo "[OK]";
}
}
EDIT
This script run on Codeigniter framework
If what you want is to ensure that the input has a set number of digits, with leading zeros, I wrote a tip some time ago that does exactly that:
<?php
$variable = sprintf("%04d",$_POST['Currency']);
?>
This, will echo leading zeros until the $variable is 4 characters long. Here are some examples:
If $_POST['Currency'] has a value of
'3' it would echo '0003'
If $_POST['Currency'] has a value of
'103' it would echo '0103'
If $_POST['Currency'] has a value of
'3103' it would echo '3103'
Which is good even if the amount of characters is longer than 4 (in your case) since it would simply ignore the function and not add anything in front of it. Hope it helped :)
You might want to use the PHP's str_pad() function like that
$currency = str_pad($_POST['currency'],4,'0',STR_PAD_LEFT)
See php manual for details
Your problem is auto-casting, where a variable can be a string or a number value and php guesses which one you cant. Your currency variable is being used as a string when you do string contatenation on it with the dot operator, but then when you echo it it assumes it to be an integer and throws you the integer value. You could echo (string)$currency or use the str_pad() or printf() function to get more useful output values.
EDIT: The code in the question actually works as expected for me. You must be simplifying the example and your actual output function is something other than what you present here, because in that code the auto typecasting stuff works fine.

Categories