different value of variable while inserting - php

I want to generate a pair of random numbers 1234567890-9876543210 (10 digits each)
I made this code. It works fine it generates a pair of random numbers BUT if I try to insert it into database I get same results multiple times. Let's say I get 1234567890 more than once. If I echo the insert statement I get different results but when I want to query it into database I get same results.
$numbers = array(0,1,2,3,4,5,6,7,8,9);
srand(time());
$f = fopen('sql0.txt', 'w');
for($i=0;$i<100000;$i++)
{
$r = NULL;
$r2 = NULL;
for($x=0;$x<10;$x++)
{
$n = rand(0,9);
$r .= $numbers[$n];
}
for($x=0;$x<10;$x++)
{
$n1 = rand(0,9);
$r2 .= $numbers[$n1];
}
echo("INSERT INTO ci_codes VALUES (NULL, '$r', '$r2', '0')<br>");
}

Do you need the INSERT expression inside your loop? That might cause the trouble.
As others have mentioned, it is better to just generate the numbers once with the php function, then run your MySql Query.
$r = mt_rand(0, 10000000);
$r2 = mt_rand(0, 10000000);
echo("INSERT INTO ci_codes VALUES (NULL, '$r', '$r2', '0'");

Related

php only first digit in mySQL

I am trying to output randomly generated values via "echo" command and write them to a database. The "echo" output is no problem, but in the mySQL table only the first digit of the generated number is given. In theory there should be displayed five digits. https://i.stack.imgur.com/1KPGi.png
if ($submitbutton){
$length = 5;
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz##$&*";
$size = strlen( $chars );
echo "Key: ";
for( $i = 0; $i < $length; $i++ ) {
$str= $chars[ rand( 0, $size - 1 ) ];
echo $str;
$sql = "INSERT INTO regkey (regkey) VALUES (?)";
$stmt = mysqli_prepare($link, $sql);
$str1 = $str;
mysqli_stmt_bind_param($stmt, "s", $str1);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
}
If I try to enter another predefined value via php, this works without problems.
This is nothing to do with your database.
In your for loop, you overwrite $str with a single character every time the loop runs. I guess you intended to append to it instead using .=. (N.B. This logical flaw is masked by the fact you echo within the loop, so on screen you see what looks like a single string but is in fact 5 separate strings right next to each other.)
You then also run the INSERT the same number of times, so you get 5 separate entries, one for each digit (although since you close the connection within the loop and then don't re-open it, it's hard to see how that is actually succeeding - I'd guess the 2nd query fails and you either didn't mention the error or have suppressed all error reporting so you didn't see it).
It was little unclear, but I think you wanted to generate one 5-digit string and write it all to the same row in the database? If so, then do it like this:
if ($submitbutton){
$length = 5;
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz##$&*";
$size = strlen( $chars );
echo "Key: ";
$str = "";
for( $i = 0; $i < $length; $i++ ) {
$str .= $chars[ rand( 0, $size - 1 ) ]; //append not overwrite
}
//after the loop has finished, do the echo and insert once only
echo $str;
$sql = "INSERT INTO regkey (regkey) VALUES (?)";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, "s", $str);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
N.B. As suggested in the comments, you could also replace the for loop entirely with
$str = substr(str_shuffle($chars), 0, $length);
which will do the same job for you using existing PHP functions.

PHP replace dash with 0 from array when inserting to mySQL

I'm inserting/updating a mysql table from json URL, but some of the values in $points contain a dash and I want to amend to a zero (or null would be fine) when updating so that I can have the column set to INT.
I know how to simply replace all - to 0 in mysql but stuck when it comes to trying to do as part of update from a json URL. My code is:
for ($i = 0; $i < $length; $i++) {
$sus = $array['formguide'][$i]['SUSPENSION'];
$wpoints = $array['formguide'][$i]['WEEKPOINTS'];
$tcode = $array['formguide'][$i]['TEAMCODE'];
$val = $array['formguide'][$i]['VALUE'];
$points = $array['formguide'][$i]['POINTS'];
$pname = $array['formguide'][$i]['PLAYERNAME'];
$tname = $array['formguide'][$i]['TEAMNAME'];
$sixwpoints = $array['formguide'][$i]['SIXWEEKPOINTS'];
$injury = $array['formguide'][$i]['INJURY'];
$playerid = $array['formguide'][$i]['PLAYERID'];
$pos = $array['formguide'][$i]['POS'];
//insert or update values into mysql
$sql = "INSERT INTO formguide (suspension, weekpoints, teamcode,
value, points, playername, teamname,
sixweekpoints, injury, playerid, pos)
VALUES ('$sus', '$wpoints', '$tcode','$val','$points','$pname','$tname',
'$sixwpoints','$injury','$playerid','$pos')
ON DUPLICATE KEY UPDATE suspension='$sus', weekpoints='$wpoints',
teamcode='$tcode', value='$val', points='$points', playername='$pname',
teamname='$tname', sixweekpoints='$sixwpoints', injury='$injury',
playerid='$playerid', pos='$pos'";
I tried REPLACE() on points within the UPDATE() section i.e.:
...points=REPLACE('$points','-','0'), playername='$pname', ...
however that didn't work.
Any ideas how I can do this, or is there an alternative to have the points column as INT and accept a dash?
Thanks
REPLACE is for modifying values coming from SQL, whereas you want to modify a value coming from PHP.
Use str_replace instead.
$points = str_replace('-', '0', $points);
First, you need to escape or cast all values to avoid SQL injection vulnerabilities. Since you did not post your table schema, I'm guessing the types. mysqli_real_escape_string() is for strings, (int) and (float) for numbers of the respective type.
Doing that, your original problem is solved automatically, as PHP returns 0, if you cast '-' to integer.
Second, your query is a usecase for a proper use of REPLACE, which works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
for ($i = 0; $i < $length; $i++)
{
$sus = mysqli_real_escape_string($link, $array['formguide'][$i]['SUSPENSION']);
$wpoints = (int) $array['formguide'][$i]['WEEKPOINTS'];
$tcode = mysqli_real_escape_string($link, $array['formguide'][$i]['TEAMCODE']);
$val = (float) $array['formguide'][$i]['VALUE'];
$points = (int) $array['formguide'][$i]['POINTS'];
$pname = mysqli_real_escape_string($link, $array['formguide'][$i]['PLAYERNAME']);
$tname = mysqli_real_escape_string($link, $array['formguide'][$i]['TEAMNAME']);
$sixwpoints = (int) $array['formguide'][$i]['SIXWEEKPOINTS'];
$injury = mysqli_real_escape_string($link, $array['formguide'][$i]['INJURY']);
$playerid = (int) $array['formguide'][$i]['PLAYERID'];
$pos = (int) $array['formguide'][$i]['POS'];
// Insert or update values into mysql
$sql = "REPLACE INTO formguide SET
suspension='$sus',
weekpoints=$wpoints,
teamcode='$tcode',
value=$val,
points=$points,
playername='$pname',
teamname='$tname',
sixweekpoints=$sixwpoints,
injury='$injury',
playerid=$playerid,
pos=$pos
";
// ...
}

PHP mysqli insert only works once

I've got a script that I needed to change since the data which is going to be inserted into the db got too big to do it at once. So I created a loop, that splits up the array in blocks of 6000 rows and then inserts it.
I don't know exactly if the data is to big for the server to process at once or if it's too big to upload, but atm I got both steps split up in these 6000s blocks.
Code:
for ($j = 0; $j <= ceil($alength / 6000); $j++){
$array = array_slice($arraysource, $j * 6000, 5999);
$sql = "INSERT INTO Ranking (rank, name, score, kd, wins, kills, deaths, shots, time, spree) VALUES ";
foreach($array as $a=>$value){
//transforming code for array
$ra = $array[$a][0];
$na = str_replace(",", ",", $array[$a][1]);
$na = str_replace("\", "\\\\", $na);
$na = str_replace("'", "\'", $na);
$sc = $array[$a][2];
$kd = $array[$a][3];
$wi = $array[$a][4];
$ki = $array[$a][5];
$de = $array[$a][6];
$sh = $array[$a][7];
$ti = $array[$a][8];
$sp = $array[$a][9];
$sql .= "('$ra',' $na ','$sc','$kd','$wi','$ki','$de','$sh','$ti','$sp'),";
}
$sql = substr($sql, 0, -1);
$conn->query($sql);
}
$conn->close();
Right now it only inserts the first 5999 rows, but not more as if it only executed the loop once. No error messages..
Don't know if this'll necessarily help, but what about using array_chunk, array_walk, and checking error codes (if any)? Something like this:
function create_query(&$value, $key) {
//returns query statements; destructive though.
$value[1] = str_replace(",", ",", $value[1]);
$value[1] = str_replace("\", "\\\\", $value[1]);
$value[1] = str_replace("'", "\'", $value[1]);
$queryvalues = implode("','",$value);
$value = "INSERT INTO Ranking (rank, name, score, kd, wins, kills, deaths, shots, time, spree) VALUES ('".$queryvalues."');";
}
$array = array_chunk($arraysource, 6000);
foreach($array as $key=>$value){
array_walk($value,'create_query');
if (!$conn->query($value)) {
printf("Errorcode: %d\n", $conn->errno);
}
}
$conn->close();
Secondly, have you considered using mysqli::multi_query? It'll do more queries at once, but you'll have to check the max allowed packet size (max_allowed_packet).
Another tip would be to check out the response from the query, which your code doesn't include.
Thanks for the tips but I figured it out. Didn't think about this ^^
it was the first line after the for loop that i didnt include in my question:
array_unshift($array[$a], $a + 1);
this adds an additional value infront of each user, the "rank". But the numbers would repeat after one loop finishes and it can't import users with the same rank.
now it works:
array_unshift($array[$a], $a + 1 + $j * 5999);

Random repeats similar strings, even after changing seed

How can I get this random string generator to create random strings. I keep getting repeats. The arrays generally consist of between 0 - 10 things, but still it is getting the same number of beds and baths on the repeats, I know that statistically it is messed up.
How can I elminate repeats?
for ($i = 0; $i <= 1000000; $i++) {
srand($i);
$price = rand(20000, 1000000);
$bed = rand(0, 20);
$bath = rand(0, 7);
$addressnum = rand(100, 10000);
$address = (int) preg_replace('/\D/', '', $addressnum) . " lol st";
$province = $f_contents[rand(0, count($f_contents) - 1)];
$postedby = 3;
$description = $de_contents[rand(0,count($de_contents) - 1)];
$status = "Unsold";
$type = $status_a[array_rand($status_a)];
$category = $category_type[array_rand($category_type)];
$size = rand(100,100000);
$builtin = rand(1850, 2013);
$queryString = "INSERT INTO listings
(PRICE, ADDRESS, PROVINCE, DESCRIPTION, STATUS, TYPE, CATEGORY, SIZE, BUILTIN, BED, BATH, POSTED_BY) VALUES
($price, '$address', '$province', '$description', '$status', '$type', '$category', $size, $builtin, $bed, $bath, $postedby)";
echo $queryString . "<br>";
$query = $db -> query($queryString);
}
Stop using rand(). Using mt_rand() instead should solve this problem.
I've come across problems several times with rand() and repeated values. I have to admit that in those cases I never really took the time to check why rand() seems so wonky.
Take srand() outside the loop. srand() should be called ONCE, and only once, in your program. Thereafter, rand() will produce random results. If you call srand() repeatedly, you're not getting random numbers at all, you're getting a hash value of the seeds you call it with.
Sure, switching to mt_rand() will give you even higher-quality random numbers, but that wasn't the problem with your code.

Function generating Unique Random Values Array

As Mysql rand() is time consuming I am using alternate way using Mysql max() and PHP. I wrote this code for fetching random product_id's:
function RandomUniqueArray($min,$max,$limit){
$random_array = array();
if(isset($limit) && is_numeric($limit)){
for($i=0;$i<$limit;){
$rand_val = mt_rand($min, $max);
if(!in_array($rand_val, $random_array)){
$random_array[] = $rand_val;
$i++;
}
}
}
return $random_array;
}
This works fine as I want each time it gives different result set with different unique values but it takes 6.232 micro seconds.
Ohter I got by Google is:
$random_array = array_rand(array_fill($min,$max, true),$limit);
with takes only 0.101 microseconds but its result set is repeated means. Unique values array is fine but whole set is repeated. Why is it so???
I called both of these by one by one as
$random_array = RandomUniqueArray(1,64000,4);
And
$random_array = array_rand(array_fill(1,64000, true),4);
Thank you.
I made a script,that only takes ̣̣̣+- 4.5E-6.
Try it.
function randomValue($min,$max,$limit)
{
$array = Array();
$MAX = mt_rand($min,$max);
for($i = 0;$i < $limit;$i++)
{
$array[$i] = mt_rand($min,$MAX);
while( is_array($array[$i],$array) ) //To check if exist, if. Make new.
{
$array[$i] = mt_rand($min,$MAX);
}
}
return $array;
}

Categories