Why won't this loop variable increment? - php

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;

Related

PHP and Mysql to much adding data

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'];
}
}
}

PHP if statements being ignored

I'm new to PHP and SQL. I'm trying to make a rule so that it will only show certain information for certain pages. The code I'm using is
include 'dbh-login.php';
$id = $_GET['id'];
$i = 1;
while ($i != 100) {
$sql = "SELECT * FROM ui_off WHERE id='$i'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if ($row['link'] = $id) {
echo $row['title']."<br>";
}
$i++;
}
The if statement seems to have no effect on weather the script echoes the title or not.
You are missing == assignment. Here is the working code.
$id = $_GET['id'];
$i = 1;
while ($i != 100) {
$sql = "SELECT * FROM ui_off WHERE id='$i'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if ($row['link'] == $id) {
echo $row['title']."<br>";
}
$i++;
}
Your code does not make any sense.
You are using a while loop and looping in it 100 times just to check if 1 row have the given id.
Why don't you search directly for the id? Your code will be cleaner and you will free some memory on the server by deducting 100 queries each time the page is opened.
$id = $_GET['id'];
$sql = "SELECT * FROM ui_off WHERE id!='100' AND link='$id'" ;
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if ($row['link'] != '') {
echo $row['title']."<br>";
}

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++;
}

Return multiple rows with mysqli

I am in the process of learning mysqli and I am trying to query a databases and return multiple rows. I understand that a loop has to be used to return multiple rows but I have no idea how I would implement this into my code. Some help in doing this would be greatly appreciated.
$query2 = mysqli_query($con,"SELECT * FROM journeys WHERE id = $id");
$count = mysqli_num_rows($query2);
if ($count == 0) {
$journeys = 'You have no future journeys.';
} else {
while ( $row = mysqli_fetch_assoc($query2) ) {
$from = $row ['origin'];
$to = $row ['destination'];
$date = $row ['date'];
$hour = $row ['hour'];
$minute = $row ['minute'];
$journeyid = $row ['journeyid'];
try this code
<?php
$con= mysqli_connect('localhost', 'root', '', 'your data base name');
$query2 = mysqli_query($con,"SELECT * FROM journeys where id=$id");
$count = mysqli_num_rows($query2);
if ($count == 0) {
$journeys = 'You have no future journeys.';
echo $journeys;
} else {
while ( $row = mysqli_fetch_assoc($query2) ) {
$from = $row ['origin'];
$to = $row ['destination'];
$date = $row ['date'];
$hour = $row ['our'];
$minute = $row ['minute'];
$journeyid =$row ['journeyid'];
echo $from.'<br>';
}
}
have a look at this line echo $from; this will display what ever you have in the origin column in your database, if you want to display destination, use this as well echo $to;
means what ever you want to display do it like this echo $variableName; it will display the result;
before you display the result it will only store it, but will not display it,
have a look i change your this line of code as well
its your code
if ($count == 0) {
$journeys = 'You have no future journeys.';
echo $journeys;// i added this line
i added one line, because what you are saying here that if $count is equal to zero, than $journeys='you have no future journeys'; but you are not using echo you have to use echo to display the result.
if you still have some confusion ask again, and try to google as well
$query2 = mysqli_query($con,"SELECT * FROM journeys WHERE id = $id");
$row = mysql_fetch_array($query2);
$count = count($row);
if(intval($count)>0)
{
for($i = 0; $i<$count; $i++)
{
$from[$i] = $row[$i]['origin'];
-------------------------------
----------------------
}
}

Do-while loop hangs the connection to website

I am trying to use do-while loop to check if a value exists in database,
function check($a) {
$query = "SELECT * FROM `table` WHERE code = '$a'";
$result = mysql_query($query);
$nm = mysql_num_rows($result);
if ($nm > 0) {
return true;
} else {
return false;
}
}
function randomnumber() {
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 10) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
$number = randomnumber();
do { $number = randomnumber(); } while (!check($number));
That codes somehow hangs the connection to website. After i execute this page, strangely it cannot connects to website until i restart the browser.
What may cause this ?
your query is never evaluating to true, so the loop is infinite. As long as it's not pulling back any rows where code = 'yourRandomNumber', then you will be looping indefinitely.
If you want to simply select a random 'code' from your database this code will be much more efficient than what you've got.
$query = 'SELECT DISTINCT code FROM `table`';
$result = mysql_query($query);
$my_arr = array();
while($row = $mysql_fetch_assoc($result)) {
$my_arr[] = $row['code']
}
$random_key = $my_arr[array_rand($my_arr)];
Re-reading your question and comments I'm less and less sure what your code originally set out to accomplish, if you could be a bit more clear on your objective here we could probably give you some advice on how to accomplish your goal more efficiently.
Edit:
This code will retrieve all of the codes already used in your table, calculate the difference from the possible codes, and then return one random unused code. No loop required. [well one loop, but it's a short one]
$psbl_codes = str_split("abcdefghijkmnopqrstuvwxyz023456789");
$query = 'SELECT DISTINCT code FROM `table`';
$result = mysql_query($query);
$used_codes = array();
while($row = $mysql_fetch_assoc($result)) {
$used_codes[] = $row['code']
}
$unused_codes = array_diff($psbl_codes, $used_codes);
echo "random unused code: " . $unused_codes[array_rand($unused_codes)];

Categories