In case i need to replace table value with 500 rows contains random numbers. the problem is how to looping to get the ID 1 - 500, it is possible ?
<?php
$first = sprintf("%06d", mt_rand(1, 999999));
$second = sprintf("%06d", mt_rand(1, 999999));
$third = sprintf("%06d", mt_rand(1, 999999));
for($x = 1; $x <= 500; $x++) {
$sql = "UPDATE `random_num` SET
`rand_1` = '$first',
`rand_2` = '$second',
`rand_3` = '$third'
WHERE id = '$x';";
}
?>
whats wrong with your code?
just move the random number generation inside the for.. loop and u are done
<?php
function s_random()
{
return sprintf("%06d", mt_rand(1, 999999));
}
for($x = 1; $x <= 500; $x++) {
$sql = "UPDATE `random_num` SET
`rand_1` = '".s_random()."',
`rand_2` = '".s_random()."',
`rand_3` = '".s_random()."'
WHERE id = '".$x."'";
}
if you do it this way, that will be 500 calls to the DB and each row will have different random number
if you want the same random number in each row, just use the in keyword
"UPDATE `random_num` SET
`rand_1` = '".s_random()."',
`rand_2` = '".s_random()."',
`rand_3` = '".s_random()."'
WHERE id IN ('".implode(',',range(1,500))."'";
you can also create the query in one go
<?php
function s_random()
{
return sprintf("%06d", mt_rand(1, 999999));
}
$sql = "INSERT into random_num (id,rand_1,rand_2,rand_3) VALUES";
$val = [];
$i = 1; //begin ID
do{
$val[] = "($i, ".s_random().",".s_random().",".s_random().")";
$i++;
}while ($i < 500); //end ID
echo '<pre>';
$sql .= implode(',',$val);
$sql .= ' ON DUPLICATE KEY UPDATE rand_1 = VALUES(rand_1), rand_2 = VALUES(rand_2), rand_3 = VALUES(rand_3)';
echo ($sql);
Related
I have a problem: I can't make my script working with penalties, but I made it work with bonuses.
Start: two-dimensional array of users, each has id, name, start position and modificator (if modificator < 0 its bonus; if modificator > 0 its penalty).
How modificators work: for example, I have a queue of users Test1, Test2, Test3. If I give user Test3 bonus 1, he will switch places with user Test 2 and final queue will be Test1, Test3, Test2. If I give him bous 2, than he will be first at queue.
Penalties works the other way around. If I give user Test1 penalty 1, he will be second in a queue. If I give him penalty 3, he will be moved to the end of the queue.
This is my working code for bonuses:
<?
$new = array(); $orders = array();
$new[111]['position'] = 1; $new[111]['user'] = 'Test1'; $orders[1] = 111; $new[111]['shift'] = 0;
$new[222]['position'] = 2; $new[222]['user'] = 'Test2'; $orders[2] = 222; $new[222]['shift'] = 0;
$new[333]['position'] = 3; $new[333]['user'] = 'Test3'; $orders[3] = 333; $new[333]['shift'] = 0;
$new[444]['position'] = 4; $new[444]['user'] = 'Test4'; $orders[4] = 444; $new[444]['shift'] = 0;
$new[555]['position'] = 5; $new[555]['user'] = 'Test5'; $orders[5] = 555; $new[555]['shift'] = 0;
$new[666]['position'] = 6; $new[666]['user'] = 'Test6'; $orders[6] = 666; $new[666]['shift'] = 0;
$new[777]['position'] = 7; $new[777]['user'] = 'Test7'; $orders[7] = 777; $new[777]['shift'] = 0;
$new[888]['position'] = 8; $new[888]['user'] = 'Test8'; $orders[8] = 888; $new[888]['shift'] = 0;
//shift function
function bonus($start, $bonus)
{
global $new, $orders;
//for bonuses, shift to start, $bonus is negative number
if ($bonus < 0)
{
for ($i = $start; $i > ($start - abs($bonus)); $i--)
{
$order_id = intval($orders[$i]);
$prev = intval($orders[$i - 1]);
if ($prev != 0)
{
$temp = $new[$order_id]['position'];
$new[$order_id]['position'] = $new[$prev]['position'];
$new[$prev]['position'] = $temp;
$orders[$i] = $prev;
$orders[$i - 1] = $order_id;
}
}
}
//end for bonuses
}
// Now I set modificator (bonus negative, penalty positive)
$new[555]['shift'] = -2;
// sort by bonuses
$i = 1;
foreach($new as $value)
{
$order_id = $orders[$i];
bonus($new[$order_id]['position'], $new[$order_id]['shift']);
$i++;
}
// sort 2d array with field position
usort($new, function($a, $b){
return $a['position'] <=> $b['position'];
});
//DATA OUTPUT
$i = 1;
foreach($new as $value)
{
echo $i . '. ' . $value['user'] . ' ; shift: ' . $value['shift'];
echo '<br>';
$i++;
}
?>
At this code I set bonus with: $new[555]['shift'] = -2;
So, penalty will be like: $new[444]['shift'] = 3;
Code for penalties I think must be something like this:
//for penalty, shift to the end, $bonus positive number
if ($bonus > 0)
{
$total_new = count($new);
for ($i = $start; $i < ($start + $bonus); $i++)
{
$order_id = intval($orders[$i]);
$next = intval($orders[$i + 1]);
if ($next < $total_new)
{
$temp = $new[$order_id]['position'];
$new[$order_id]['position'] = $new[$next]['position'];
$new[$next]['position'] = $temp;
$orders[$i] = $next;
$orders[$i + 1] = $order_id;
}
}
}
//end code for penalty
Here is something wrong with $orders. I tried many different types of code all day long, including array enumeration in asc/desc order, but it didn't work correcty...
P.S. I know about array_multisort, but I dont need to sort, I need to switch elements with each other.
Again: bonus 2 means that user must switch places with previous number 2 times. Penalty 3 means that user must switch places with next user 3 times.
I created a dynamic table row provide as in http://bootsnipp.com/snippets/OeZkZ#comments
i am facing problem in inserting into database using loop.
the first row is taking fields as the its 0 var
{
1
}
$count = 1;
if(isset($_POST['byMonth']))
{
for( $i = 1; $i <= $count; $i++ )
{
$year = $_POST['year'.$i];
$month = $_POST['month'.$i];
$actual = $_POST['amount'.$i];
//$date = $_POST['entry'.$i];
echo $que = "insert INTO worker_by_month(uid,year,month,actual_amount,date) VALUES ('".$uid."','".$year."','".$month."','".$actual."','".$entry."')";
$mysqli->query($que);
$count = $_POST['items'];
}
}
this is what i have done.
I have 100000 records in a table. I need to make a query that reads 10 records and after that 10 more records continuously until the end of the table. For each of the 10 rows groups, I need to pick one random row. Is it possible to accomplish that using a MySQL query? I need some idea to do this. Can anybody help me?
I have tried to do a php loop but it doesn't work.
<?php
include_once ("connection.php");
$data = mysql_query("SELECT * FROM trying");
$result = array();
while ($data2 = mysql_fetch_array($data))
{
array_push($result, array('no'=> $data2['no'],
'source'=> $data2['source'],
'destination'=> $data2['destination']));
}
$e=0;
for ($a = 0; $a <= 49;)
{
for ($i = 0; $i <= 9; $i++,$a++) {
$rand = array();
$rand[$i] = $result[$a];
}
echo json_encode($rand[1]);
}
?>
Insted of this:
for ($a = 0; $a <= 49;)
{
for ($i = 0; $i <= 9; $i++,$a++) {
$rand = array();
$rand[$i] = $result[$a];
}
echo json_encode($rand[1]);
}
you can use this:
$rand = array();
$step = 10;
for ($min = 0; $min <= 49; $min = $min + $step)
{
$max = $min + $step;
$rand[] = $result[rand($min,$max)];
}
echo json_encode($rand);
Since you're echoing a json encoded array, I'm assuming you're calling this php file through an AJAX request, and you want subsequent requests for each 10 rows.
If this is the case, a solution to your problem could be this:
Define limit and offset as vars in your javascript
Pass limit and offset with the AJAX request
If the result of the AJAX request isn't empty, increment offset by limit (offset = offset + limit) to use in the next request
Receive limit and offset in the PHP file (use $_GET or $_POST, depends on the type of request)
Include limit and offset in the MySQL query ("SELECT * FROM trying LIMIT $offset, $limit")
Calculate a random number from 0 to 9 (rand(0, 9))
Fetch the nth (rand) row from the MySQL result (see solution below)
Your PHP file should look like this:
include_once ("connection.php");
$limit = mysql_real_escape_string($_GET['limit']); // If post use $_POST
$offset = mysql_real_escape_string($_GET['offset']); // If post use $_POST
$data = mysql_query("SELECT * FROM trying LIMIT $offset, $limit");
$rand = rand(0, 9);
$count = 0;
while($row= mysql_fetch_array($data)) {
if($rand == $count++) {
echo json_encode($row);
break;
}
}
Put the SQL statement in a loop and use the counter as a variable in the Limit:
$count = mysql_query("SELECT * FROM trying");
$total = round(mysql_num_rows($count) / 10);
for ($i=0;$i<$total;$i++) {
$data = mysql_query("SELECT * FROM trying LIMIT ".($i * 10).", 10");
$result = array();
while ($data2 = mysql_fetch_array($data))
{
array_push($result, array('no'=> $data2['no'],
'source'=> $data2['source'],
'destination'=> $data2['destination']));
}
}
$e=0;
for ($a = 0; $a <= 49;)
{
for ($i = 0; $i <= 9; $i++,$a++) {
$rand = array();
$rand[$i] = $result[$a];
}
echo json_encode($rand[1]);
}
?>
Try with the following:
<?php
include_once ("connection.php");
$query = "SELECT * FROM trying";
$count = 0;
while(true)
{
$data = mysql_query($query." LIMIT ".$count.",10");
$random = rand(1,10);
for($i=1;$i<=$random;$i++)
{
$row = mysql_fetch_array($data);
if($row === false)
{
break 2;
}
}
echo json_encode($row);
$count++;
}
?>
Try this :
<?php
set_time_limit(0);
include_once ("connection.php");
$per = 10;
$start = 0;
$total = 0;
$total_query = mysql_query("SELECT COUNT(*) AS total FROM trying");
if(mysql_num_rows($total_query) == 1) {
$row = mysql_fetch_assoc($total_query);
$total = $row['total'];
$offset = ($start * $per);
$results = array();
while($offset <= $total) {
$tmp = array();
$data_query = mysql_query("SELECT * FROM trying LIMIT ".$offset.",".$per);
while ($row = mysql_fetch_array($data_query)) {
array_push($tmp, array(
'no'=> $row['no'],
'source'=> $row['source'],
'destination'=> $row['destination'])
);
}
array_push($results,$tmp[rand(0,9)]);
unset($tmp);
$start++;
$offset = ($start * $per);
}
echo json_encode($results);
} else {
die("No records found.");
}
?>
Need to receive data of fields from $i raw of mysqli object.
$res = $mysqli->query("SELECT mood,count(mood) as number FROM em_mood GROUP by mood ORDER by mood ASC");
$obj = $res->fetch_object();
for ($i = 1; $i <= 10; $i++){
if ($i==$obj->mood[$i]) $mood_result .= "<div class='chart'>".$obj->mood[$i].$obj->number[$i]."</div>";
else $mood_result .= "<div class='chart'>empty</div>";
}
Explanation:
$obj->mood is equal from 1 to 10.
if $obj->mood is missing "2" for example, I need to exchange it with empty div.
In other words, what is the syntax of getting field [mood] value in lets say second raw? something like $obj[2][mood]?
Update:
Looks like it works like this:
for ($i = 1; $i <= 10; $i++){
$res = $mysqli->query("SELECT mood,count(mood) as number FROM em_mood WHERE date>=CURDATE()-INTERVAL 30 DAY and mood=".$i);
$obj = $res->fetch_object();
echo $obj->mood." - ".$obj->number."<br>";
}
Is there any way to make this more simple? To don`t make 10 mysqli queries?
$raw = [];
$sql = "SELECT mood,count(mood) as number FROM em_mood GROUP by mood";
$res = $mysqli->query($sql);
while ($obj = $res->fetch_object())
{
$raw[$obj->mood] = $obj->number;
}
now you will have your "raw" data all right
for ($i = 1; $i <= 10; $i++){
if (isset($raw[$i])) {
$mood_result .= "<div class='chart'>$i - $raw[$i]</div>";
} else {
$mood_result .= "<div class='chart'>empty</div>";
}
}
How can I select a random set of rows
The important bits:
I need to specify the number of random rows to select via a variable.
Say for instance the number of rows I want to select is 10, then it HAS TO select 10 DIFFERENT rows. I don't want it to pick out the same row a few times until it has 10.
The code below picks out 1 random row, how can I tailor this to the above spec?
<?php $rows = get_field('repeater_field_name');
$row_count = count($rows);
$i = rand(0, $row_count - 1);
echo $rows[$i]['sub_field_name']; ?>
<?php
$rows = get_field('repeater_field_name');
$row_count = count($rows);
$rand_rows = array();
for ($i = 0; $i < min($row_count, 10); $i++) {
// Find an index we haven't used already (FYI - this will not scale
// well for large $row_count...)
$r = rand(0, $row_count - 1);
while (array_search($r, $rand_rows) !== false) {
$r = rand(0, $row_count - 1);
}
$rand_rows[] = $r;
echo $rows[$r]['sub_field_name'];
}
?>
This is a better implementation:
<?
$rows_i_want = 10;
$rows = get_field('repeater_field_name');
// Pull out 10 random rows
$rand = array_rand($rows, min(count($rows), $rows_i_want));
// Shuffle the array
shuffle($rand);
foreach ($rand as $row) {
echo $rows[$row]['sub_field_name'];
}
?>
Simply loop through the random row process the number of random rows you want to get.
<?php
$rows_to_get=10;
$rows = get_field('repeater_field_name');
$row_count = count($rows);
$x=0
while($x<$rows_to_get){
echo $rows[rand(0, $row_count - 1)]['sub_field_name'];
$x++;
}
?>
You can give this a try
$rows = get_field('repeater_field_name');
var_dump(__myRand($rows, 10));
function __myRand($rows, $total = 1) {
$rowCount = count($rows);
$output = array();
$x = 0;
$i = mt_rand(0, $rowCount - 1);
while ( $x < $total ) {
if (array_key_exists($i, $output)) {
$i = mt_rand(0, $rowCount - 1);
} else {
$output[$i] = $rows[$i]['sub_field_name'];
$x ++;
}
}
return $output ;
}
A simple solution :
$rows = get_field('repeater_field_name');
$limit = 10;
// build new array
$data = array();
foreach ($rows as $r) { $data[] = $r['sub_field_name']; }
shuffle($data);
$data = array_slice($data, 0, min(count($data), $limit));
foreach ($data as $val) {
// do what you want
echo $val;
}