I want to assign same quantity of work by each worker available in php.
This is my array of available worker:
if (!isset($array_worker)){
$array_worker = array();
}
$stmt = $dbh->prepare("SELECT username
FROM group_members
WHERE grp_id = :grp_id
AND statut > 0
AND specification != 2");
$stmt->bindValue(':grp_id', $grp_id);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $key => $value){
if (!in_array($value['username'], $array_worker)){
array_push($array_worker, $value['username']);
}
}
This array_worker return 2 entries
That is what I have try
$n = 0;
for ($i = 0; $i < count_worknotdone($grp_id); $i++) {
if ($n >= count($array_worker)){
$n = 0;
}
$stmt = $dbh->prepare("UPDATE work
SET worker = :worker
WHERE grp_id = :grp_id
AND worker IS NULL");
$stmt->bindValue(':worker ', $array_worker[$n]);
$stmt->bindValue(':grp_id', $grp_id);
$stmt->execute();
$n++;
}
but that assign only the first worker for each work..
What I want for example if we have 2 workers available and 4 work not done
We assign 2 work for each workers.
Thanks you
if (!isset($array_worker)){
$array_worker = array();
}
if (!isset($array_id)){
$array_id = array();
}
$stmt = $dbh->prepare("SELECT username FROM group_members WHERE grp_id = :grp_id AND statut > 0 AND specification != 2");
$stmt->bindValue(':grp_id', $grp_id);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $key => $value){
if (!in_array($value['username'], $array_worker)){
array_push($array_worker, $value['username']);
}
}
$stmt = $dbh->prepare("SELECT id FROM work WHERE grp_id = :grp_id AND statut < 1 AND worker IS NULL");
$stmt->bindValue(':grp_id', $grp_id);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $key => $value){
if (!in_array($value['id'], $array_id)){
array_push($array_id, $value['id']);
}
}
$n = 0;
for ($i = 0; $i < count($array_id); $i++) {
if ($n >= count($array_worker)){
$n = 0;
}
$stmt = $dbh->prepare("UPDATE work SET worker = :worker WHERE id = :id AND grp_id = :grp_id AND worker IS NULL");
$stmt->bindValue(':id', $array_id[$i]);
$stmt->bindValue(':worker', $array_worker[$n]);
$stmt->bindValue(':grp_id', $grp_id);
$stmt->execute();
$n++;
}
I have done what I want by doing that, that for sure can be improve but its working..
Related
I need to get about 70.000 lines from database and I want to get batch by batch but like I did I get only some lines :
$sql = "SELECT COUNT(*) as num FROM ".self::TABLE_NAME;
$stmt = Db::get()->prepare($sql);
$stmt->execute();
$results = $stmt->fetch();
$batches = $results['num'] / 1000;
$limit = 0;
for ($i = 0; $i <= $batches; $i++) {
$offset = $i * 1000;
$sql = "SELECT * FROM ".self::TABLE_NAME." LIMIT $limit,$offset";
$stmt = Db::get()->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
foreach ($results as $result) {
echo $result['supplierName'].PHP_EOL;
}
$limit+=1000;
}
Have you an idea ? Thx in advance.
I have 2 Columns in mysql. valami2 and playerID in table players_extra.
I will the following:
give 3000 coppers for the first row in valami2, then 2500 coppers for the second(then each row -500 coppers until the 5th place)....after the 5th place give 500 until the 10th place. for the CORRECT payerID.
$aseco->console('>> Updating `hetimostfin` counts for all Players...');
$hetimostfin = array();
$line = 0;
$coppers = 3000;
$query = "
SELECT
`playerID`,
COUNT(`valami2`) AS `Count`
FROM `players_extra`
GROUP BY `playerID`;
";
$res2 = mysql_query($query);
if ($res2) {
if (mysql_num_rows($res2) > 0) {
while ($row = mysql_fetch_object($res2)) {
$hetimostfin[$row->playerID] = $row->Count;
}
foreach ($hetimostfin as $id => $count) {
$res2 = mysql_query("
UPDATE `players_extra`
SET `valami2` =(`valami2`+'".$coppers."')
WHERE `playerID` = ". $id ."
");
$line ++;
$coppers=($coppers-500);
if ($line >= 6) {
$coppers=500;
}
if ($line == 10){
break;
}
}
}
}
Try PDO. It's a much better and safer way of interacting with databases for PHP. http://php.net/manual/en/pdo.connections.php
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$hetimostfin = array();
$coppers = 3000;
$line = 0;
$query = <<<SQL
SELECT
playerID,
COUNT(valami2) AS `count`
FROM players_extra
GROUP BY playerID;
SQL;
foreach($dbh->query($query, PDO::FETCH_ASSOC) as $row) {
$hetimostfin[[$row['playerID']] = $row['count'];
// execute update statement
$line++;
}
How can I get a count of the number of affected rows when I'm deleting multiple rows in PDO? This is the technique I'm using to delete multiple rows:
$selected = $_POST['checkbox'];
$N = count($selected);
for ($i = 0; $i < $N; $i++) {
$result = $dbh->prepare('DELETE FROM users WHERE id= :id');
$result->bindParam(':id', $selected[$i], PDO::PARAM_INT);
$result->execute();
}
I tried this, but it always returned 1:
$deleted = $result->rowCount();
if ($deleted) {
echo $deleted.' was deleted.';
}
You're running a loop, so each call is deleting 1; you need to add a counter.
So add:
$deleted += $result->rowCount();
inside the loop
and then outside:
if ($deleted) {
echo $deleted.' was deleted.';
}
If the id field is unique, then that statement could affect at most 1 row. However you are preparing a new statement and executing it in a loop. You should try adding up how many you delete.
$deleted = 0;
for ($i = 0; $i < $N; $i++) {
$result = $dbh->prepare('DELETE FROM users WHERE id= :id');
$result->bindParam(':id', $selected[$i], PDO::PARAM_INT);
$result->execute();
$deleted = $deleted + $result->rowCount();
}
echo $deleted.' was deleted.';
Here's a way to do it in 1 delete instead of running multiple deletes.
This way rowCount() will show the actual results deleted.
$selected = $_POST['checkbox'];
$placeholder = array();
$values = array();
foreach ($selected as $id) {
$placeholder[] = ":".$id;
$values[":".$id] = $id;
}
$sql = "Delete FROM users WHERE id IN (".implode(', ',$placeholder).") ";
$result = $dbh->prepare($sql);
$result->execute($values);
$deleted = $result->rowCount();
if ($deleted>0) {
echo $deleted.' was deleted.';
}
I am getting Fatal error: Cannot pass parameter 3 by reference in line# 4
please suggest me solution I want the binding part dynamic.
$values = array($username,$password);
$query = "select * from users where email_id = ? and password = ?"
$this->con = new mysqli('localhost', 'username', 'password','dbname');
$stmt = $this->con->prepare($query);
$count = 0;
for ($i = 0; $i < count($values); $i++) {
$stmt->bind_param(++$count,$values[$i], PDO::PARAM_STR,12);
}
if ($stmt->execute()) {
while ($row = $this->stmt->fetch()) {
$data[] = $row;
}
return $data;
} else {
return null;
}
use bindValue()
$stmt->bindValue(++$count,$values[$i], PDO::PARAM_STR,12);
After being stuck trying to get a grip of how this works, i've decided to ask for some hints to how I can do this.
Let me start by saying I have next to no experience with anything like this. I've just gathered some logic by looking at the code and i'm almost done with my project, except for this issue that i've come by.
This is the original code (which i am still using another place in the code, this appears to be working just fine).
function showCart() {
global $db;
$cart = $_SESSION['cart'];
if ($cart) {
$items = explode(',',$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$output[] = '<form action="kurv.php?action=update" method="post" id="cart">';
$output[] = '<table>';
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM varetabel WHERE varenr = '.$id;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$output[] = '<tr>';
$output[] = '<td>Slet</td>';
$output[] = '<td>'.$varenavn.'</td>';
$output[] = '<td>DKK '.$pris.'</td>';
$output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
$output[] = '<td>DKK '.($pris * $qty).'</td>';
$total += $pris * $qty;
$output[] = '</tr>';
$_SESSION['items'] = $contents; // Antal forskellige varer.
$_SESSION['qty'] = $qty;
}
$output[] = '</table>';
$output[] = '<p>Pris total: <strong>DKK '.$total.'</strong></p>';
$output[] = '<div><button type="submit">Opdatér kurv</button></div>';
$output[] = '</form>';
} else {
$output[] = '<p>Kurven er tom.</p>';
}
return join('',$output);
}
global $db is connecting to the DB and such, no biggie, and then there is this function from an include:
function fetch () {
if ( $row=mysql_fetch_array($this->query,MYSQL_ASSOC) ) {
return $row;
} else if ( $this->size() > 0 ) {
mysql_data_seek($this->query,0);
return false;
} else {
return false;
}
}
Now, im trying to use the same method to take the arrays from this code and put them into my database with this code:
session_start();
global $db;
$items = $_SESSION['items'];
$cart = $_SESSION['cart'];
$qty = $_SESSION['qty'];
if(isset($_SESSION['email'])) { // IF LOGGED IN
$sql = mysql_query("SELECT * FROM antalstabel ORDER BY ordrenr DESC LIMIT 1") or die(mysql_error());
$row = mysql_fetch_assoc($sql);
$maxordrenr = $row['ordrenr'];
$nextnumber = $maxordrenr + 1;
$antal = count($items); // COUNTS DIFFERENT ITEMS IN CART.
$maxplusantal = $maxordrenr + $antal;
$varenrplaceholder = 0;
for ($i = $maxordrenr; $i <= $maxplusantal; $i++) {
$sql = mysql_query("INSERT INTO antalstabel (ordrenr, varenr) VALUES ('$nextnumber','$varenrplaceholder')") or die(mysql_error());
$nextnumber--;
$varenrplaceholder++;
}
$varenrplaceholder = 0;
if ($cart) {
$items = explode(',',$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
foreach ($contents as $id=>$qty) {
$sql = 'UPDATE antalstabel SET varenr = '.$id.' and antal = '.$qty.' WHERE ordrenr = '.$nextnumber.' and varenr = '.$varenrplaceholder.'';
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$varenrplaceholder++;
}
}
But it does not appear to be working properly, the code does run, but it does not update the tabel with the values of the arrays.
Am i completely wrong or can anyone help me with this issue, i know it is a lot to ask.
my own code creates X rows with the same ID depending on how many different items there is in the cart, I am trying to update those existing rows that i've just created with the values i presume is still in the arrays of the showCart() function.
Thank you in advance
$sql = 'SELECT * FROM varetabel WHERE varenr = '.$id;
$result = $db->query($sql);
You aren't checking the success/failure status returned by query(). Most of the MySQL functions return false if there's an error, for example a misspelled table name or an invalid expression in the WHERE clause.
I don't know what $id is, but you should inspect the $sql string to see if it works (copy & paste it into a mysql client session to test it).
And you should always check that $result is not false. See http://php.net/mysql_error
there is error at your code line
foreach ($contents as $id=>$qty) {
$sql = 'UPDATE antalstabel SET varenr = '.$id.',antal = '.$qty.' WHERE ordrenr = '.$nextnumber.' and varenr = '.$varenrplaceholder.'';
$varenrplaceholder++;
}
$select_query='SELECT * FROM varetabel WHERE varenr = '.$id;
$result = $db->query($select_query);
$row = $result->fetch();
extract($row);
You appear to be creating a lot of dummy records, then going through an updating them. I would expect you to have just needed to do the insert, but wondering if this is something to do with the fetch you do after the update.
However the main thing that I suspect stops you query working is that you count the number of $items before you have set $items to the exploded $cart.
I have done the following, using assumed names for the methods in your db class
<?php
session_start();
global $db;
$items = $_SESSION['items'];
$cart = $_SESSION['cart'];
$qty = $_SESSION['qty'];
if(isset($_SESSION['email']))
{ // IF LOGGED IN
if ($cart)
{
$sql = "SELECT MAX(ordrenr) AS ordrenr FROM antalstabel";
$result = $db->query($sql) or die($db->error());
if ($row = $result->fetch())
{
$maxordrenr = $row['ordrenr'];
$nextnumber = $maxordrenr + 1;
$items = explode(',',$cart);
$antal = count($items); // COUNTS DIFFERENT ITEMS IN CART.
$maxplusantal = $maxordrenr + $antal;
$varenrplaceholder = 0;
for ($i = $maxordrenr; $i <= $maxplusantal; $i++)
{
$sql = "INSERT INTO antalstabel (ordrenr, varenr) VALUES ('$nextnumber','$varenrplaceholder')";
$db->query($sql) or die($db->error());
$varenrplaceholder++;
}
$varenrplaceholder = 0;
$contents = array();
foreach ($items as $item)
{
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
foreach ($contents as $id=>$qty)
{
$sql = "UPDATE antalstabel SET varenr = $id and antal = $qty WHERE ordrenr = $nextnumber and varenr = $varenrplaceholder";
$result = $db->query($sql) or die($db->error());
$row = $result->fetch();
extract($row);
$varenrplaceholder++;
}
}
}
}
?>