select 1 Although have few users.. mysql - php

why $subadmin = 1 row only?
i have few users with "MaTeam = 8"
but its select 1 user only!
my code:
$query8 = mysql_query("SELECT * FROM users WHERE MaTeam='8';");
$subadmin = array();
while ($rowa = mysql_fetch_array($query8)) {
$subadmin=$rowa["username"];
}

Your while loop is overwriting the $subadmin value on every iteration. To append to your array you can use [] after the array variable name:
while ($rowa = mysql_fetch_array($query8)) {
$subadmin[] = $rowa["username"];
}
(Side note: Consider switching to the mysqli library since the older mysql library is deprecated.)

Replace
while ($rowa = mysql_fetch_array($query8)) {
$subadmin = $rowa["username"];
with:
while ($rowa = mysql_fetch_assoc($query8)) {
$subadmin[] = $rowa["username"];

Related

How to assign value to an array in while loop in php from mysqli result to make a counter to filter another while loop?

How to assign value to an array in while loop in php from mysqli result to make a counter to filter another while loop??
I want to assign something like this for my counter variable:
$counter = array("6:00 Am" => 0, "8:00 Am" => 0, "10:00 Am" => 0);
For this code:
//This is from transaction table
$stm2 = "SELECT tr_sched FROM transaction WHERE tr_date = CURRENT_DATE()";
$res2 = $conn->query($res2);
while($rows5 = $res2->fetch_assoc())
{
//Not working
$counter[] = array($rows5['tr_sched'] => 0)
}
So I can filter this another while loop if the schedule time is greater than to my limit variable, like this:
//This is from my schedule table
$stm = "SELECT sc_time FROM schedule GROUP BY sc_time";
$res = $conn->query($stm);
$counter = array();
while($row4 = $res4->fetch_assoc())
{
//Note working
if($counter[$row4['sc_time']] >= $limit/*=10*/)
{
echo "<option disabled="">" . $row4['sc_time'] . "</option>";
}
else
{
echo "<option>" . $row4['sc_time'] . "</option>";
}
}
The goal of all the codes above is to display all schedule time from schedule table as an option for select element and if the schedule time is already have a 10 records or greater than(limit variable) on my transaction table for today it will display as option but disable so it can't be selected by user.
I hope you get what I mean, I will try to keep active to answer if you have something to clarify about my question.
You don't need the while loop at all.
You can use array functions to populate the array with static values.
$stm2 = "SELECT tr_sched FROM transaction WHERE tr_date = CURRENT_DATE()";
$res2 = $conn->query($stm2);
// get values from a single column
$keys = array_column($res2->fetch_all(MYSQLI_ASSOC), 'tr_sched');
// create an array with all values as 0 and keys from $keys
$counter = array_fill_keys($keys, 0);
Of course, don't reset the array later on with $counter = array();
If you want to loop anyway, then you can use a simple foreach loop.
$stm2 = "SELECT tr_sched FROM transaction WHERE tr_date = CURRENT_DATE()";
$res2 = $conn->query($stm2);
foreach($res2 as $rows5) {
$counter[$rows5['tr_sched']] = 0;
}

How to save query in multidimesional array?

I have this script executing as a cron job everyday to update days remaining to pay invoices. I first query every row of my table and attempt to store the data in a multidimensional array but this seems to be storing everything I query in the first element of my array.
Here's my script:
<?php
include '../inc/dbinfo.inc';
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
error_log( "################################################# UpdateVendorInvoiceDays.php #################################################" );
$three = 3;
$fetchAllInvoices = "SELECT VENDORINVOICEID, VdrInvoiceReceived, PaymentDue, COUNT(*), DATEDIFF(PaymentDue, NOW()) FROM tblVendorInvoices WHERE VdrInvoiceStatusID != ?";
$getInvoices = $conn->prepare($fetchAllInvoices);
$getInvoices->bind_param("i", $three);
$getInvoices->execute();
$result = $getInvoices->get_result();
$rows = array();
$j = 0;
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]); //Only outputs one row
//UPDATE DAYS REMAINING IN EACH ENTRY THAT ISNT PAID
$updateDaysRemaining = "UPDATE tblVendorInvoices SET DaysRemaining = ? WHERE VENDORINVOICEID = ? AND VdrInvoiceStatusID ! = ?";
$setDays = $conn->prepare($updateDaysRemaining);
$k = 0; //incrementor
$numberOfEntries = $rows['COUNT(*)'];
for($k;$k<$numberOfEntries;$k++){
$setDays->bind_param("iii", $rows[$k]["DATEDIFF(PaymentDue, NOW())"],
$rows[$k]['VENDORINVOICEID'], $three);
if($setDays->execute()){
error_log('Cron success');
}else{
error_log('Cron fail');
}
}
?>
Currently the output from my first query is:
[[{"VENDORINVOICEID":88,"VdrInvoiceReceived":"2018-08-21","PaymentDue":"2018-07-27","COUNT(*)":2,"DATEDIFF(PaymentDue, NOW())":-25}]]
and my error log only gives me a notice for $rows['COUNT(*)'] being undefined (which makes sense)
I've looked at other answers here but they don't seem to have the same structure as I do.
EDIT: I also have 2 rows in my database but this only puts out one. I forgot to mention this.
There are a couple of simplifications to get all of the rows. Instead of...
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]);
You can just return all rows using fetch_all()...
$rows = $result->fetch_all (MYSQLI_ASSOC);
echo json_encode($rows);
Then encode the whole array and not just the one element - which is what $rows[0][0] was showing you.
As for you other problem - change in your select statement to
COUNT(*) as rowCount
and then you can use this alias for the field reference...
$rows['COUNT(*)']
becomes
$rows['rowCount']

MySQL sorting with PHP

I'm trying to accomplish the following situation:
$mysql_query = "
SELECT *
FROM st_users
WHERE
`user_comp_supervisor_id` = '$team_supervisor' AND
`user_exempt_from_goals` = '0'
ORDER BY 'calculate_progress_percent()' ASC
";
I know that I can't accomplish ordering by a function in a MySQL statement, but I'm trying to figure out how to take all the returned records, and then order them in order of highest to lowest from a php function result. Any ideas would be greatly appreciated; I've been trying to wrap my head around this for a few hours now... :-(
function diy_calc_progress_percent($user_id,$period_id,$period_week_number)
{
$this->user_id = $user_id;
$this->period_id = $period_id;
$this->period_week_number = $period_week_number;
if ($this->period_week_number == 1)
{
$this->week_id = mysql_result( mysql_query(" SELECT `period_week_one` FROM `st_comp_periods` WHERE `period_id` = '$this->period_id' "),0 );
}
else if ($this->period_week_number == 2)
{
$this->week_id = mysql_result( mysql_query(" SELECT `period_week_two` FROM `st_comp_periods` WHERE `period_id` = '$this->period_id' "),0 );
}
else
{
echo "Week number not valid.";
exit();
}
$this->week_start_date = mysql_result( mysql_query(" SELECT `week_start_date` FROM `st_comp_weeks` WHERE `week_id` = '$this->week_id' "),0 );
$this->week_end_date = mysql_result( mysql_query(" SELECT `week_end_date` FROM `st_comp_weeks` WHERE `week_id` = '$this->week_id' "),0 );
$this->user_department = $this->user_info($this->user_id,"user_comp_department_id");
$this->user_week_diy_goal = mysql_result( mysql_query(" SELECT `goal_diy_department` FROM `st_comp_department_goals` WHERE `goal_department_id` = '$this->user_department' AND `goal_week_id` = '$this->week_id' "),0 );
$this->calc_totals_result = mysql_query("SELECT SUM(record_total_diy_revenue) AS user_week_total FROM `st_entered_records` WHERE `record_user_id` = '$this->user_id' AND `record_date` BETWEEN '$this->week_start_date' AND '$this->week_end_date'");
$this->calc_totals_row = mysql_fetch_assoc($this->calc_totals_result);
$this->user_week_total = $this->calc_totals_row['user_week_total'];
$this->user_week_one_percent = ($this->user_week_total / $this->user_week_diy_goal) * 100;
$this->user_week_one_percent = number_format( (float)$this->user_week_one_percent, 2, '.', '' );
return $this->user_week_one_percent;
}
You probably will have to do some array juggling.
First get all your entries FROM st_users into a first array (mysql_query)
Then you could run through that array, and for each entry you do the calculate_progress_percent() and build up a second array in which you could add the additional info ("user_progress_percent").
After this you can sort the new array ba your new info ("user_progress_percent").
And here is some quick and dirty code-suggestions – code is however not tested… of course…:)
First:
$mysql_query = "SELECT * FROM st_users
WHERE `user_comp_supervisor_id`='$team_supervisor' AND
`user_exempt_from_goals` = '0'";
Then something like this:
$i = 0;
while($tmp = mysql_fetch_array($mysql_query)) {
$my_second_array[$i]['user_id'] = $tmp['user_id'];
$user_id = $my_second_array[$i]['user_id'];
diy_calc_progress_percent($user_id,$period_id,$period_week_number);
$my_second_array[$i]['user_result'] = $diy_calc_progress_percent_result;
$i++;
}
And then sorting that second array should be possible as described here:
Sort Multi-dimensional Array by Value
…hope this helps at some point…

Improve & Functionalize Queried Array

Need a little help, advise, or link to an example or useful tutorial so I can learn this. As I am very new to programming in general.
I have 11 Select boxes in a form named 'ore1' thru 'ore11' that send data up to $_POST.
This little block turns that into an array that is used in another function.
//function calculateValue($sellValue){ -- add when you figure it out
if(isset($_POST['submit'])){
$i = 11 //total number of select boxes
$pdquery = "SELECT * FROM ore
WHERE '".$_POST['ore1']."'
LIKE id";
$result = mysql_query($pdquery);
$oredata1 = array();
while ($row = mysql_fetch_row($result)) {
$oredata1 = $row; }
}
else {}
}
I'd like like to be able to use this one bit of code with all 11 Select boxes without having to copy it 11 times by getting
.$_POST['ore#']. //5th line
$oredata# = $row; //10th line
to replace # with the appropriate # depending on the select box it is used on.
Any tips?? Thanks in advance.
In your HTML:
<select name="ore[]">
...
</select>
<select name="ore[]">
...
</select>
In your PHP
if(isset($_POST['submit']) && isset($_POST['ore'])){
foreach($_POST['ore'] as $ore){
$ore = (int)$ore;
$pdquery = "SELECT * FROM ore WHERE id = $ore";
...
}
}
Also do not use mysql_* function since deprecation process has begun
for ($i = 1; $i <= 11; $i++) {
$ore = 'ore'.$i;
$pdquery = "SELECT * FROM ore WHERE '".$_POST[$ore]."' like id";
...
execute it in a for-loop - from 1 to 11. Then you can use the variable $i to access stuff.
// I assume that there is some MySQLi object called $mysqli already present. You'll have to create it if it does not
if(isset($_POST['submit'])){
$pdquery = 'SELECT * FROM ore WHERE id LIKE ?';
$oredata = array();
if($stmt = $mysqli->prepare($pdquery)) {
for($i = 1; $i < 12; $i++) {
$ore = 'ore' . $i;
if(empty($_POST[$ore])) {
continue;
}
$oreValue = (int)$_POST[$ore];
$stmt->bind_Param('i', $oreValue);
$stmt->execute();
$oredata[$i] = $stmt->get_result()->fetch_array(MYSQLI_ASSOC);
}
}
$stmt->close();
}
This does NOT take into consideration the fact that there might be more than just those eleven inputs. Using an array on HTML side would certainly be cleaner (And you'd just have to replace the for-loop with a foreach-loop and use the key instead of $ore)

SQLITE3 query doesn't return what I want it to within PHP

I open my sq3d fine, but when I try to do a SELECT on one of my tables it seems to not return the results I excpect. Here is the php code:
$buildingArray = array();
class MyDB extends SQLite3
{
function __construct()
{
$this->open('Database.s3db');
}
}
$db = new MyDB();
$query1 = "SELECT * FROM tbl_uploadData";
$result1 = $db->query($query1);
$u = $result1->fetchArray();
echo "<br/>Size of u: ".sizeOf($u)."<br/>";
for($i=0; $i<sizeOf($u); $i++){
echo "<br/>Items: ".$u[$i]."<br/>";
}
This is what is in my Database:
tbl_uploadData : b_id - 1,2,3,4 : where 1,2,3,4 are the items within the fields, b_id the field name and tbl_uploadData the table.
I expect to get 1, 2, 3 and 4 to return in the fetchArray()
All i get in return is:
Size of u: 2
Items: 1
Notice: Undefined offset: 1 in C:\xampp\htdocs\PHPexcel\Tests\StrategicExcel.php on line 72
Items:
Here is the solution, as spaced monkey mentioned, fetchArray() only returns one result at a time. So by adding a while loop and a couple of references to my b_id, it should work. I've modified my code to:
$databaseName = "Database.s3db";
$db2 = new SQLite3($databaseName);
$sql = "SELECT b_id FROM tbl_uploadData";
$result = $db2->query($sql);//->fetchArray(SQLITE3_ASSOC);
$row = array();
$i = 0;
while($res = $result->fetchArray(SQLITE3_ASSOC)){
if(!isset($res['b_id'])) continue;
$row[$i]['b_id'] = $res['b_id'];
$i++;
}
print_r($row);
Hope this helps if anyone comes across this problem in the future, TY
fetchArray() only gets 1 row at a time, you need to call it for every row. http://uk3.php.net/manual/en/function.sqlite-fetch-array.php
You should be able to:
while ( $u = $result1->fetchArray() ) {
echo "<br/>Items: ".$u['b_id']."<br/>";
}
I don't know why sizeof($u) is returning 2 though.

Categories