PHP and Mysql to much adding data - php

i'm generating random team array.All players are stored in DB without team. I need to assign 20 players from database to a team and get their info into array. I wrote the code, but somehow code assigns 60 players instead of 20 in database. Where did I went wrong?
$Team = array();
$i=0;
while($i < 20)
{
$rand = rand(1,100);
$sql = $con->query("SELECT * FROM players where id='$rand'");
if($sql->num_rows > 0)
{
$data = $sql->fetch_array();
if($data['teamid'] == NULL)
{
$con->query("UPDATE players SET teamid='$teamid' WHERE id='$rand'");
$Team [$i]['name'] = $data['name'];
$Team [$i]['surfname'] = $data['surfname'];
$Team [$i]['rating'] = $data['rating'];
$Team [$i]['position'] = $data['position'];
$i++;
}
}
}

There's a simpler way to do this (forgive me if my SQL or PHP is not exactly correct, it's been a while).
// Generate 20 unique random numbers between 1 and 100
// see https://stackoverflow.com/a/5612704/910328
$randomPlayerIds = range(1, 100);
shuffle($randomPlayerIds);
$randomPlayerIds = array_slice($randomPlayerIds, 0, 20);
// In your query, get 20 records where id is in the list of random numbers AND
// teamid is null, and set results to the team array.
$players = $con->query(
"select * from players where id in $randomPlayerIds and teamid is null"
);
$team = $players->fetch_assoc();
// Update your database.
$teamid = ???; // wherever you're getting this value from
$con->query("UPDATE players SET teamid='$teamid' WHERE id in $randomPlayerIds");

Try this. This assigns 20 people to a team.
$Team = array();
for($i=0;$i<20;$i++)
{
$rand = rand(1,100);
$sql = $con->query("SELECT * FROM players where id='$rand'");
if($sql->num_rows > 0)
{
$data = $sql->fetch_array();
if($data['teamid'] == NULL)
{
$con->query("UPDATE players SET teamid='$teamid' WHERE id='$rand'");
$Team [$i]['name'] = $data['name'];
$Team [$i]['surfname'] = $data['surfname'];
$Team [$i]['rating'] = $data['rating'];
$Team [$i]['position'] = $data['position'];
}
}
}

Related

database query, compare each two rows but getting only first two 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++;
}

automatically get all sql table values

I have a query which returns a row with over 20 values
TableTest
Country
User
Name
...
...
If I want to create an object in PHP for each value in the table how can I do that?
I currently do like this.
$generalValues = new stdClass();
$IdQuery = $this->m_queryFactory->getIdFromBuild($id, $pc);
$result = odbc_exec($this->m_connection, $IdQuery);
$no_results = odbc_num_rows($result);
for ($i = 0; $i < $no_results; $i++) {
$Id = trim(odbc_result($result, "Id"));
$query = $this->m_queryFactory->getQuery($Id);
$result = odbc_exec($this->m_connection, $query);
if (odbc_num_rows($result) > 0) {
odbc_fetch_row($result);
$generalValues->Country = odbc_result($result, "country");
$generalValues->Name = odbc_result($result, "name");
$generalValues->User = odbc_result($result, "user");
...
...
}
}
But how can I do it for every value in the table row whitout having to specify every table column value?
Thanks in advance.
$result = odbc_exec($this->m_connection, $query);
$generalValues = odbc_fetch_object($result);
http://php.net/manual/en/function.odbc-fetch-object.php

Error on How to SUM up all the rows of a column by Query and PHP.

Here I am trying to add all the columns up from one table echo out the result.
I have a table with Points that have been recorded by user, every points gets added I would like to add it up and print it out as result for the users score.
I am getting an error where the SUM Query is run. and the result is 0.
Here is the PHP:
<?php
// see if the form has been completed
include_once("php_includes/check_login_status.php");
//include_once("php_includes/db_conx.php");
// Initialize any variables that the page might echo
$username = "";
$weight = "";
$weighthist = "";
$id = "";
if(isset($_GET["u"])){
$username = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
}
$sql = "SELECT users.*, weighthistory.* FROM users JOIN weighthistory USING(id)";
$user_query = mysqli_query($db_conx, $sql);
// check if the user exists in the database
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$id = $row ["id"];
$username = $row ["username"];
$weight = $row["weight"];
$weighthist = $row["weighthist"];
$point_hist = $row["point_hist"];
}
// this is to calculate points score
$calweight = $weight - $weighthist;
$points = $calweight * 10;
$result = mysql_query('SELECT SUM (point_hist) AS value_sum FROM points_history');
$row = mysql_fetch_assoc($result);
$sum = $row['value_sum'];
?>
THIS IS THE HTML:
<div><b>Point Hist: </b> <?php echo $sum; ?> </div>
<input id="point_hist" type="hidden" name="point_hist" value="<?php echo $sum; ?>" readonly/>
</html>
I managed to figure it out, thanks for the tips here is the final result of my query etc...
$res = mysqli_query($db_conx,'SELECT sum(point_hist) FROM points_history');
if (FALSE === $res) die("Select sum failed: ".mysqli_error);
$row = mysqli_fetch_row($res);
$sum = $row[0];

Why won't this loop variable increment?

I'm trying to write code that will count the number of users returned by a sqlite query and then split a 'bill' between those users, but for some reason my counter won't increment and I am getting a division by zero error. My code is here:
<?php
session_start();
require 'database.php';
$db = new Database();
$name = $_POST['name'];
$amount = $_POST['amount'];
$due = $_POST['due'];
$gid = $_GET['gid'];
$uid = $_SESSION['id'];
$count = 0;
$users = $db->query("select * from members where(gid='$gid');");
while($data = $users->fetchArray()) {
$count++;
}
$amount = $amount / $count;
while($data = $users->fetchArray()) {
if($data['uid'] == $uid) {
continue;
} else {
$temp = $data['uid'];
$db->exec("insert into bills values(NULL,'$gid','$uid','$temp','$amount','$due','false','$name');");
}
}
header('Location:grouppage.php?gid='.$gid.'');
?>
Anyone have any ideas on how to fix this?
Regardless of the loop not seeming to work, you can't have two while(... fetchArray()) loops without something resetting the internal pointer.
In this case, however, you don't need that:
$users = $db->query("select * from members where(gid='$gid')");
$count = $users->numRows();
if( $count == 0) die("No users found!");
$amount /= $count;
while($data = $users->fetchArray()) {
...
}
You don't handle case, when select doesn't return any record.
Just look at your code:
$users = $db->query("select * from members where(gid='$gid');");
while($data = $users->fetchArray()) {
$count++;
}
No data selected -- no while-body
executed, $count not incremented and left zero, with "divide by zero" error in following line as consequence.
$amount = $amount / $count;

Store query results in a different table in PHP/MySql

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.

Categories