I'm using PHP/MySql and I'm trying to team users into pairs based on a skill that they have. I have an existing table for users, and an existing table for the teams.
For example, I executed a query which returned 6 members which needs to be paired up into a team.
SELECT * FROM users WHERE skill = 'Office'
users
id/name/skill
1/Bob/Office
2/Ted/Office
3/Tim/Office
4/Bill/Office
5/Shawn/Office
6/Gab/Office
These results must be then paired up, and the expected output should be:
teams
name/member
Office1/Bob
Office1/Ted
Office2/Tim
Office2/Bill
Office3/Shawn
Office3/Gab
Once 2 members are placed in a team, the team name should increment by one.
Any help will be greatly appreciated Thanks.
Edit: I tried this:
$results = mysql_query("SELECT * FROM users WHERE skill = 'Office'");
$numrows = mysql_num_rows($results); $name ="";
if($numrows!=0) {
while($row = mysql_fetch_assoc($results)) {
$name = $row['userName'];
}
}
//For incrementing the team name
$namectr=0;
for($ctr=0;$ctr<$results_num;$ctr++) {
if($ctr%2==0) {
$query = mysql_query("INSERT INTO teams VALUES ('Office$namectr','$name')");
$ctr++; if($ctr%2==1) {
$query = mysql_query("INSERT INTO teams VALUES (Office$namectr','$name')");
$namectr++;
}
}
}
why not try:
$result = mysql_query("SELECT * FROM users WHERE users.skill = 'office'");
$count = 0;
$sqlcount = 0;
$offcount = 1;
while ($source = mysql_fetch_array($result)) {
if ($count < 1) {
$office = $source['skill'] . $offcount;
$name = $source['name'];
$result[$sqlcount] = mysql_query("INSERT INTO teams ('name', 'member') VALUES ('$office', '$name')");
$sqlcount++;
} else if ($count >= 1) {
$offcount++;
$count = 0;
$office = $source['skill'] . $offcount;
$name = $source['name'];
$result[$sqlcount] = mysql_query("INSERT INTO teams ('name', 'member') VALUES ('$office', '$name')");
$sqlcount++;
} else {
echo "ERROR" . mysql_error();
}
}//end while
$sqlcount = 0;
while ($result[$sqlcount] != "") {
if ($source = $result) {
} else {
echo "ERROR! " . mysql_error();
}
}//end while
Couldn't you do your database query, then do something like the below:
$count=0;
$team=1;
$teams = array();
foreach($result as $output){
if($count % 2 == 0){
// if even number, reset count and increment position
$count=0;
$team++;
}
$teams[] = $output['skill']." ".$team." - ".$output['member'];
$count++;
}
Something like the above, but it is untested, but should work in theory.
Related
$a_forms = array("a_GG", "a_FF");
$sql = "SELECT name, field FROM categories WHERE enabled = '1' ";
$result = mysqli_query($con,$sql);
$Others = array();
while($row = mysqli_fetch_array($result)) {
$Other_names[] = $row['name'];
$Other_fields[] = $row['db_field'];
}
for ($i=0;$i<count($a_forms);$i++) {
if ($a_forms[$i] == "a_FF") {
$dforms_sql = "SELECT *
FROM a_FF
where id=".$id;
$dforms_result = mysqli_query($con,$dforms_sql);
while ($forms_row = mysqli_fetch_array($dforms_result)) {
for ($i=0; $i<count($Other_fields); $i++) {
echo "<tr><td colspan='3'>".$Other_names[$i]."</td></tr>";
}
}
} elseif ($a_forms[$i] == "a_GG") {
$dforms_sql = "SELECT *
FROM a_GG where id=".$id;
$dforms_result = mysqli_query($con,$dforms_sql);
while($forms_row = mysqli_fetch_array($dforms_result)) {
echo 'Other cool stuff';
}
}
} //END (first) For Loop
So, for some reason, if that second for loop, $Other_field is there it will only show the IF statement for a_FF. But if the array = a_FF and a_GG and the for loop for $other_field is NOT there it displays them both. So it's obviously that for loop that is breaking something, I have no idea what though. Anyone have any thoughts?
Please I've been trying to create a function that would query a DB, select from the table, and if the row count is not equal to 6, then a row from the table and repeat (or maybe duplicate) until the row count is equal to 6. I've search for this here in StackOverflow, but didn't get anything close. Please if you have a similar link to this, please post it here, and I'll give it a go.
Here's my code:
//List All active adverts
function showActiveAdverts()
{
$status = 1;
//Build final queries.
$query = mysql_query("SELECT * FROM table WHERE
status = '".mysql_real_escape_string($status)."' ORDER BY rand() LIMIT 6") or die(mysql_error());
$count = mysql_num_rows($query);
$row = mysql_fetch_assoc($query);
# My question here, check if the $count >= 1 && $count != 6, then do getDefaultBannner() and repeat it until it runs for 6 times.
if($count >= 1){
do{
$list[] = $row['id'];
}while($row = mysql_fetch_assoc($query));
return $list;
}
else{ return FALSE; }
}
Here's the code for getDefaultBannner()
function getDefaultBannner()
{
$status = 6;
$query = mysql_query("SELECT id FROM table WHERE status = '".mysql_real_escape_string($status)."' ")
or die(mysql_error());
$count = mysql_num_rows($query);
$row = mysql_fetch_assoc($query);
if($count >= 1){
do{
$list[] = $row['id'];
}while($row = mysql_fetch_assoc($query));
return $list;
}
else{ return FALSE; }
}
Thanks in advance!
You can rewrite your code as this
//List All active adverts
$query = mysql_query("SELECT * FROM table WHERE
status = '".mysql_real_escape_string($status)."' ORDER BY rand() LIMIT 6") or die(mysql_error());
$count = mysql_num_rows($query);
if($count >= 1 && $count != 6)
$list = getDefaultBannner();
else
$list = showActiveAdverts($query);
function showActiveAdverts($query)
{
$status = 1;
//Build final queries.
$row = mysql_fetch_assoc($query);
if($count >= 1){
do{
$list[] = $row['id'];
}while($row = mysql_fetch_assoc($query));
return $list;
}
else{ return FALSE; }
}
So I've got a dropdown that has a list of customers that you can select from. It uses a function (that someone else built) which works fine when there are 2 or more customers but dies when there it only one. When there's one customer, each item in the dropdown is the first character of each column for that one customer.
Here is the function:
function getCustomerBy($column = "",$value = "")
{
global $conn;
if ($value == '')
{
return(null);
}
$sel = "SELECT
customers.*,
customerStatus.code customerStatus
FROM customers,
customerStatus
WHERE customer_id
and customerStatus.id = customers.customerStatus_id and ". mysqli_real_escape_string($conn,$column) ."='". mysqli_real_escape_string($conn,$value) ."'";
// error_log($sel);
$run = mysqli_query($conn, $sel);
$check = mysqli_num_rows($run);
if ($check ==1)
{
$row = mysqli_fetch_assoc($run);
return($row);
}
elseif($check >1)
{
$rows = array();
while ($row = mysqli_fetch_assoc($run))
{
$rows[] = $row;
}
return($rows);
}
else
{
return(null);
}
}
I'm fairly certain that it's the ($check == 1) stuff but I can't work out the best way to re-do all of that to make it work without causing other errors (specifically "cannot modify header")
This is what's called up on the page with the dropdown:
$customers = getCustomerBy('users_user_id',$user['user_id']);
Also, here is the code for the dropdown:
<?
foreach ($customers as $customer)
{
$selected = '';
if (isset($gig['customers_customer_id']) && $customer['customer_id'] == $gig['customers_customer_id'])
{
$selected = ' selected ';
}
echo "\t<option value=\"".$customer['customer_id']."\" $selected>".$customer['customer_company_name']."</option>";
}
?>
The code that builds the dropdown is expecting an array of arrays, but instead when it's a single row you're passing it an array of strings. Treat both cases ($check > 0) the same.
function getCustomerBy($column = "",$value = "")
{
global $conn;
if ($value == '')
{
return(null);
}
$sel = "SELECT
customers.*,
customerStatus.code customerStatus
FROM customers,
customerStatus
WHERE customer_id
and customerStatus.id = customers.customerStatus_id and ". mysqli_real_escape_string($conn,$column) ."='". mysqli_real_escape_string($conn,$value) ."'";
// error_log($sel);
$run = mysqli_query($conn, $sel);
$check = mysqli_num_rows($run);
if($check > 0)
{
$rows = array();
while ($row = mysqli_fetch_assoc($run))
{
$rows[] = $row;
}
return($rows);
}
else
{
return(null);
}
}
I assume there's copy/paste errors in your query because it doesn't look right.
I don't know how the returning array is used by the rest of your code but you can try the following:
Change:
if ($check ==1) {
$row = mysqli_fetch_assoc($run);
return($row);
}
To this:
if ($check == 1) {
$rows = array();
$rows[] = mysqli_fetch_assoc($run);
return($rows);
}
Hi i am querying my db so that i can compare every two rows. ex 1 and 2, then 2 and 3, then 3 and 4. and so on and so forth. but it only compares the first two rows. any ideas? here is my code:
$result = mysql_query("SELECT *FROM attendance ORDER BY pid ASC") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// $response["nominees"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$prev_sid = $row["sid"];
$prev_pid = $row["pid"];
$row2 = mysql_fetch_array($result);
if($row2["pid"] == $prev_pid){
if(($row2["sid"] - $prev_sid) == 1){
$attended_elec = mysql_query("SELECT pid FROM election_attendance where election_id = '$election_id'");
if(mysql_num_rows($attended_elec) > 0){
$not_officer = mysql_query("SELECT usertype FROM users WHERE pid = '$prev_pid'");
if(mysql_result($not_officer, 0) == "member"){
// echo "PID" . $prev_pid;
// $nominee["pid"] = $row2["pid"];
$user_details = mysql_query("SELECT *FROM users WHERE pid = '$prev_pid'");
if(mysql_num_rows($user_details) > 0){
$response["nominees"] = array();
while ($row3 = mysql_fetch_array($user_details)) {
$nominee = array();
$nominee["pid"] = $row3["pid"];
$nominee["firstname"] = $row3["firstname"];
$nominee["lastname"] = $row3["lastname"];
$nominee["gender"] = $row3["gender"];
$nominee["contact"] = $row3["contact"];
$nominee["email"] = $row3["email"];
$nominee["address"] = $row3["address"];
$nominee["institution"] = $row3["institution"];
$nominee["points"] = $row3["points"];
$nominee["usertype"] = $row3["usertype"];
// push single product into final response array
array_push($response["nominees"], $nominee);
}
}
}
}
}
}
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "There is no candidate yet from the records.";
// echo no users JSON
echo json_encode($response);
}
thanks in advance, have a nice day
Theres a problem right at the while(), you're fetching the 1st row, and is correct.
Then, inside it you fetch the 2nd, which is what you intend, but when the iteration is repeating, the while will fetch the 3rd, and the inner the 4th, so you lost there the comparisson between 2nd and 3rd.
// fetch data from DB
$results = "...";
if (mysql_num_rows($result) < 1)
{
// no products found tell your users
return;
}
// lets make some variables to walk through the list
$previous = mysql_fetch_array($results);
$actual = null;
// and now lets walk through the list
while($actual = mysql_fetch_array($results))
{
// execute your logic here
// than at the end move the actual row to become the previous
$previous = $actual;
}
NOTICE you shouldn't use mysql_ * methods they're are deprecated. you can use the brother mysqli_ * or PDO
I would do something like this? But there is almost certainly a less resource intensive way to do it.
$x = 0;
$y = 1;
$total = mysql_num_rows(mysql_query("SELECT * FROM `the_place`");
while ($x < $total AND $y < total){
$query1 = "SELECT * FROM `the_place` LIMIT $x,1";
$query2 = "SELECT * FROM `the_place` LIMIT $y,1";
$row1 = mysql_fetch_array(mysql_query($query1);
$row2 = mysql_fetch_array(mysql_query($query2);
// Do comparison here
if ($row1 == $row2){
// etc
}
$x = $x++;
$y = $y++;
}
This is my table in my database. It should only contain one row.
I have this code, that checks if there is no data , if there is not.. The data is inserted, else it's updated. The problem is, that if i update only Brevet, the value of Baccalaureabt will disappear from my database. Any help?
Code:
if(isset($_POST['submit']))
{ $brevet = $_POST['Brevet'];
$baccalaureatbt = $_POST['Baccalaureatbt'];
$sql1="SELECT Brevet,Baccalaureatbt FROM university";
if ($result=mysqli_query($con,$sql1))
{
$rowcount=mysqli_num_rows($result);
}
if($rowcount==0)
{
$sql="INSERT INTO university(Brevet,Baccalaureatbt) VALUES('$brevet','$baccalaureatbt')";
$result = mysql_query($sql);
}
else
{
$sql2 = "UPDATE university SET Brevet = '$brevet' , Baccalaureatbt = '$baccalaureatbt'";
$result2 = mysql_query($sql2);
}
The issue is that you are setting both values, if however either $baccalaureatbt or $brevet is empty, it will be updated with a empty value, i.e the original value will be deleted.
There are multiple ways to avoid this, but one way to do it is like so:
$sql2 = "UPDATE university SET ";
if(!empty($brevet)){
$sql2 .= "Brevet = '$brevet'";
$first = 1;
}
if(!empty($baccalaureatbt)){
$sql2 .= isset($first) ? ", Baccalaureatbt = '$baccalaureatbt'" : "Baccalaureatbt = '$baccalaureatbt' " ;
}
$result2 = mysql_query($sql2);
To update the values dynamically, use the following code. Just add the values you want in the values array.
if(isset($_POST['submit']))
{
$brevet = $_POST['Brevet'];
$baccalaureatbt = $_POST['Baccalaureatbt'];
$sql1="SELECT Brevet,Baccalaureatbt FROM university";
$result=mysqli_query($con,$sql1);
if ($result)
{
$rowcount=mysqli_num_rows($result);
}
if($rowcount==0)
{
$sql="INSERT INTO university(Brevet,Baccalaureatbt) VALUES('$brevet','$baccalaureatbt')";
$result = mysql_query($sql);
}
else
{
$values = array("brevet","baccalaureatbt");
$sql2 = "UPDATE university ";
$n = 0;
foreach($_POST as $key => $val) {
if(in_array($key, $values)) {
$sql2 += ($n !== 0 ? ", " : 0);
$sql2 += "SET".$key." = ".$val;
$n++;
}
if($n > 0) {
$result2 = mysql_query($sql2);
}
}
}
}