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
Related
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?
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);
I would like to perform regex to return true/false if the input 5 digit from input matching data in database, no need to cater of the sequence, but need the exact numbers.
Eg: In database I have 12345
When I key in a 5 digit value into search, I want to find out whether it is matching the each number inside the 12345.
If I key in 34152- it should return true
If I key in 14325- it should return true
If I key in 65432- it should return false
If I key in 11234- it should return false
Eg: In database I have 44512
If I key in 21454- it should return true
If I key in 21455- it should return false
How to do this using php with regex
This is a way avoiding regex
<?php
function cmpkey($a,$b){
$aa = str_split($a); sort($aa);
$bb = str_split($b); sort($bb);
return ( implode("",$aa) == implode("",$bb));
}
?>
Well, it's not going to be a trivial regex, I can tell you that. You could do something like this:
$chars = count_chars($input, 1);
$numbers = array();
foreach ($chars as $char => $frequency) {
if (is_numeric(chr($char))) {
$numbers[chr($char)] = $frequency;
}
}
// that converts "11234" into array(1 => 2, 2 => 1, 3 => 1, 4 => 1)
Now, since MySQL doesn't support assertions in regex, you'll need to do this in multiple regexes:
$where = array();
foreach ($numbers AS $num => $count) {
$not = "[^$num]";
$regex = "^";
for ($i = 0; $i < $count; $i++) {
$regex .= "$not*$num";
}
$regex .= "$not*";
$where[] = "numberField REGEXP '$regex'";
}
$where = '((' . implode(') AND (', $where).'))';
That'll produce:
(
(numberField REGEXP '^[^1]*1[^1]*1[^1]*$')
AND
(numberField REGEXP '^[^2]*2[^2]*$')
AND
(numberField REGEXP '^[^3]*3[^3]*$')
AND
(numberField REGEXP '^[^4]*4[^4]*$')
)
That should do it for you.
It's not pretty, but it should take care of all of the possible permutations for you, assuming that your stored data format is consistent...
But, depending on your needs, you should try to pull it out and process it in PHP. In which case the regex would be far simpler:
^(?=.*1.*1})(?=.*2)(?=.*3)(?=.*4)\d{5}$
Or, you could also pre-sort the number before you insert it. So instead of inserting 14231, you'd insert 11234. That way, you always know the sequence is ordered properly, so you just need to do numberField = '11234' instead of that gigantic beast above...
Try using
^(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5).{5}$
This will get much more complicated, when you have duplicate numbers.
You really should not do this with regex. =)
$categories = array("google","adobe","microsoft","exoot","yahoo");
$sql='google,exoot,adobe';//from mysql_query
$categs = explode(",",$sql);
for($x=0;$x<count($categs);$x++){
for($y=0;$y<count($categories);$y++){
if($categs[$x] == $categories[$y]){
$str .= $y.",";
}
}
}
echo str; // 0,3,1,
Will this code will affect page render time? Can I do it using any other fast methods?
Thanks in advance.
$str = implode(',', array_keys(array_intersect($categories, $categs)));
You can use array_intersect() to find the common items and then use implode() to construct a comma-separated list:
Str = implode(',', array_intersect($categories, $categs)) . ',';
Unless you're dealing with a large number of items (thousands) it won't affect page speed. The one issue is that this intersection is O(n2). Putting the values into keys could speed it up considerably as that changes lookup time from O(n) to near O(1) making the whole operation O(n).
yes it will since you are looping in a loop.
Best thing is to check with in array:
$categories = array("google","adobe","microsoft","exoot","yahoo");
$sql='google,exoot,adobe';//from mysql_query
$categs = explode(",",$sql);
$str = array();
foreach($categs as $id => $categs_check)
{
if(in_array($categs_check, $categories))
{
//its better to put it into a array and explode it on a later point if you need it with comma.
$str[] = $id;
}
}
I'm not completely sure what you are trying to do but it should be something like the above
I don't think that str_replace is a faster method than all the array functions but another possible solution is:
$categories = array("google","adobe","microsoft","exoot","yahoo");
$sql='google,exoot,adobe';//from mysql_query
foreach($categories as $i=> $c) {
$sql = str_replace($c, $i, $sql);
}
$arrCategories = array("google","adobe","microsoft","exoot","yahoo");
$sql='google,exoot,adobe';//from mysql_query
$arrCategs = explode(",",$sql);
$arrAns = array();
for($i = 0, $intCnt = count($arrCategs); $i <= $intCnt; $i++) {
if(in_array($arrCategs[$i],$arrCategories)) {
$arrAns[$arrCategs[$i]] = array_search($arrCategs[$i], $arrCategories);
}
}
print "<pre>";
print_r($arrAns);
print "</pre>";
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, ',.:!','');