PHP and MySQL string comparison failing - php

Okay, so I'm having a pretty annoying little problem with my php code. Basically I pull two variables from two seperate sources. One's a cookie and the other is from a MySQL database.
$data = explode("|", $_COOKIE['login']);
$sql = "SELECT session_id FROM users WHERE username='user1'";
$result = $data->query($sql);
$row = $result->fetch_assoc();
$test1 = $data[0];
$test2 = $row['session_id'];
If($test1 == $test2) {
// Do some stuff
}
else {
// Don't do some stuff
}
The actual string is:
x6vkYu6Ep^lm(1Rdm)5Gj5Hj7ilL6FsDL88JC#n#iTyBUqYgJ48#9Ow%*2ZdGs1rA8bc)JoCD7dywcZgg7soV0D#!DpR^pjQwF#QpBt#HRKe$JEtQ*3LhFXsjmkzWNpt
The string is randomly generated before being stored from the following character set:
1234567890!##$%^&*()abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
for($i = 0; $i < 128; $i++) {
$string .= $char_set[rand(0, strlen($char_set)-1)];
}
$sql = "UPDATE users SET session_id='$string' WHERE user='user1'";
$data->query($sql);
setcookie('login', $string . "|" . $username);
If I just set the two variables equal to the above string and evaluate, it works out just fine. Also, if I echo both $data[0] and $row['session_id'] the entire string will display, and they look indentical.
The if() statement will work if I use basic strings, like a number, or basic word, so I'm guessing it's due to special characters, but I don't know where in the proccess it goes wrong. As I said, if I set two variables to that string value, it evaluates, but when I pull from MySQL and the cookie, despite that both strings look the same, it won't evaluate.
Any thoughts?

Related

how can i replace every single character with a "?" mark in a string with php

so for example i gave this string
sbbibs
with php i would like to change it to
??????
my query currently is this, i cant continute yet cus the ? marks
namespace modules\xenforums\sql;
trait create_row {
function create_row($types, $table, $column, $param, $conn) {
$param = "'" . implode ( "', '", $param ) . "'";
$placeholders = str_split($types);
$a = str_replace(); // this is where i want to make every type to ?
// posible value of $type, sssissb
$query = "INSERT INTO {$table} ({$column}) VALUES ({$placeholders})";
var_dump($a);
}
}
how could i do so?
im doing this because i made a php mysqli query builder and now i'm trying to replace the data types with ? to get the amount of given parameter
iv tried using str_replaces but that only does 1 specific
i also had the idea of doing str_replace for every char, but that's too tedious
iv also thought about just doing it for the current data types, but for other data base systems thats not all the same
When you want to make a string unreadable by replacing every character with a question mark you can just:
Get the length of your current string
And create a new string which puts the amount of characters in as a question mark by using a for loop.
the result would be something like that:
$input = "Test";
$output = "";
for ($i =0 ; $i < strlen(input) ; $i++) {
$output .= "?";
}
One line code for this:
str_pad('', strlen($string), '?');
Or better yet:
str_repeat('?', strlen($string));

possible limitation of implode function in PHP

I have the following code that is not returning as I expected. I was hoping the final result would be a string:
$organizers = array_unique($organizers); // this returns correctly
$organizers = implode(', ', $organizers); // this returns nothing
var_dump($organizers); // no data appears here
exit;
The array_unique() function is returning data correctly and I can see the array it returns. To start, the $organizers array is a simple 1-D array of strings that all have small lengths under 20 chars. I think the issue might be that $organizers is more than 10,000 indices long. Are there limitations on the length of an array that can be imploded? Are there work-arounds for that? I cannot find anything in the manual, but I have tested this code thoroughly and I believe the error must be on implode().
I dont' know if there is a limitation, but what comes to my mind is taht you are also transforming an array into a string. This shouldn't be the problem in PHP, but try calling it a different variable for the result of implode?
$organizers = array_unique($organizers); // this returns correctly
$organizers_string = implode(', ', $organizers); // this returns nothing
// This gives it a different space
Edit: And if for some reason implode() is still problematic.
$organizers = array_unique($organizers);
$neworganizers = "";
for($i = 0; $i < sizeof($organizers); $i++)
{
$neworganizers .= $organizers[$i];
if($i != sizeof($organizers) - 1)
{
$neworganizers .= ", ";
}
}
//$neworganizers is now the equivalent of what .implode() should return when called on $organizers
$organizers = array();
$organizers[0] = "value1";
$organizers[1] = "value2";
$organizers[2] = "value3";
$organizers[3] = "value3";
$organizers = array_unique($organizers); // strips out last index
$organizers = implode(', ', $organizers); // returns string of "value1, value2, value3"
echo $organizers;
This seemed to work on writecodeline.com/php/
I've also experienced issues with older php builds when I've tried to explode/implode by a string with special characters in it and they were encapsulated by single quotes. I know it sounds crazy, but the double quotes might be necessary on some servers.
Reference: personal experience doing work on older production servers.
I'd hate to think I'm stating the obvious, but doesn't implode only take a string as an argument? Maybe it should be something more like this...
$organizers = array_unique($organizers);
//I'm guessing what you wanted was an array of arrays?
$neworganizers = array();
for($i = 0; $i < sizeof($organizers); $i++)
{
$neworganizers[$i] = implode(", ", $organizers);
}
print_r($neworganizers);

Check a created string against database, and if found, create new string?

Pretty simple, however, I've yet to find a real straight and appropriate solution;
I've currently got my own function that creates a random string, by running two mt_rand() functions from 1 to maximum integers, then wrapping the results in two dechex() functions, and concatenating them into a single string.
I haven't done the stats on it, but, the chances of two of these strings being the same is pretty low.
However, I'll obviously need a backup solution which is why I want to perform a query against a database, and see if it exists as an entry, and if it does, re-invoke my own function to create a random string, query again, and loop until a non-existent string is found.
I've had a look at a ton of forum threads, and a few SO questions, but have yet to found a concise answer.
Any help would be greatly appreciated, thanks!
$int_affected = 0;
while(!$int_affected) {
/* Set $integer */
mysql_query("INSERT IGNORE INTO table (value) VALUES ({$integer})");
$int_affected = mysql_affected_rows();
}
Is this something you're looking for?
You need a recursive function. Something like:
function makeString() {
// Create our random string
$string = "";
$characters = array('a', 'b', 'c', 'd');
for ($i = 0; $i < 4; $i++) {
$string .= $characters[mt_rand(0, 4)];
}
$query = "SELECT COUNT(*)
FROM myTable
WHERE string = '{$string}'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if ($row['COUNT(*)'] > 0) { // if it already exists, do it again
$string = makeString();
}
return $string;
}
This isn't the most elegant solution, but it will work:
$result = queryForUnique();
$unique_string = your_described_function();
$how_many_times = 0;
while(in_array($unique_string, $result) !== false){
if($how_many_times > 10){
throw new Exception("Failed to find a unique string! Aborting!");
}
$unique_string = your_described_function();
$how_many_times++;
}
Where queryForUnique($string) is a wrapper for a SELECT statement
Edit:
Took the query out of the loop, it is bad practice to have a SELECT query in a loop.
Might want to review your control structures:
http://php.net/manual/en/language.control-structures.php

Add parts of a php mysql array together in little bunches? Leave out other parts of same array?

How can I change the code below so each part is added together in a little bunch instead of smushed together? If a little part that appears on the screen is 123, it should add 12+3 and display 15 instead of 123. I have tried sum_array and other things but it won't work to add PARTS with other PARTS in little bunches. I can only get it to display smushed together results how it is below, or add the wrong parts or the whole thing other ways.
$data = mysql_query('SELECT weight FROM my_table WHERE session_id = "' . session_id() . '"');
$params = array();
while ($row = mysql_fetch_assoc($data)) {
$params[] = $row['weight'];
}
$combinations=getCombinations($params);
function getCombinations($array)
{
$length=sizeof($array);
$combocount=pow(2,$length);
for ($i=1; $i<$combocount; $i++)
{
$binary = str_pad(decbin($i), $length, "0", STR_PAD_LEFT);
$combination='';
for($j=0;$j<$length;$j++)
{
if($binary[$j]=="1")
$combination.=$array[$j];
}
$combinationsarray[]=$combination;
echo $combination . "<br>";
}
return $combinationsarray;
}
It looks like
$combination.=$array[$j];
is your problem . in PHP is used for String Concatenation and not math. Because PHP is a loosely data typed language you are telling PHP to take the String value of $array[$j] and ".=" (append) it to $combination giving you the 12 .= 3 == "123" problem and not 15 like what you want. You should try += instead.
If I understand what you're trying to do, I think you want to use addition + instead of concatination . in the following line:
if($binary[$j]=="1")
$combination += $array[$j];

PHP - Compare exploded word with mysql varchar in PHP

How can I compare exploded word with mysql varchar in PHP?
This code produce what i want but it also give this error
veranderenwachtwoordjij
Fatal error: Call to a member function fetch_assoc() on a non-object......
$word = "Also, to be safe, change your password regularly... you don't have to be obsessive about it: every three hours or so should be enough. And because erring on the side of caution is always a good idea, fake your own suicide and change your identity at least once a year.";
$pieces = explode(" ", $word);
$x = 0;
while($x < word_count($word)) { // word count function returns int (51)
$aPiece = $pieces[$x]; // change $pieces[$x] to 'you' and then it works
$result = $conn->query("SELECT * FROM dict WHERE english='$aPiece'");
$z = 0;
while($z < $num_result) // $num_result returns amount of rows in database
{
$row = $result->fetch_assoc(); //error line is here
echo stripslashes($row['dutch']);
$z++;
}
$x++;
}
I guess the problem comes from the don't in your test sentence : you forgot to escape quotes with a function like mysql_real_escape_string.
For example :
$aPiece = mysql_real_escape_string($pieces[$x]);
$result = $conn->query("SELECT * FROM dict WHERE english='$aPiece'");
I think
$row = $result2->fetch_assoc();
should be
$row = $result->fetch_assoc();
since you don't seem to have a $result anywhere.
$result2 in $result2->fetch_assoc(); is not the correct variable, it should be
$result->fetch_assoc();
by the way you have to delete the punctuation marks in order to find the words in your database (I think) one of your first lines should (before the explode) be similar to this:
$words = strtr($words, ',.:!','');

Categories