I am attempting to create a function which will tell me what free numbers are available to use, I have a function which returns the numbers which have already been taken in an array.
I wish to check the returned array with existing elements against a blank array, and if the number is not in the array then push/add it to the empty array to allow me to return an array of available numbers/tickets.
I have tried some examples on here and looked upon PHP documentation on some items trying array_intersect, in_array etc.
I believe the best way to add the free numbers to the empty array is using array_push which has not been implemented into the example code as of yet.
Available numbers function so far:
function freeNumbers($drawID){
$minTickets = 1;
$maxTickets = totalTickets($drawID);
$takenNumbers = takenNumbers($drawID);
$freeNumbers = array();
for($i = 1; $i<$maxTickets; $i++){
$x = $i-1;
foreach($takenNumbers as $v){
if(in_array($v, $freeNumbers)){
echo "Element is in array";
break;
} else {
echo $v . "is taken";
}
}
}
//return $freeNumbers;
}
Taken numbers function
function takenNumbers($drawID){
$connect = new mysqli("localhost", "root", "", "dream");
$stmt = $connect->prepare("SELECT * FROM transaction WHERE DrawID = ?");
$stmt->bind_param("i", $drawID);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows == 0) exit("No rows");
$tickets = array();
while($row = $result->fetch_assoc()){
$id = $row['ID'];
$tickets[] = $row['TicketNumber'];
}
return $tickets;
}
Max tickets is just counting from a database transaction table to count already assigned numbers.
In this current iteration of the project, I am receiving the following "1 is taken" for each loop.
Thanks in advance, I have attempted to explain what I am attempting to do in best terms possible. But if I haven't been able to describe something please reply so I can explain it further.
Instead of checking on each array item, you could get the the difference values between all of the ticket numbers and the taken ticket numbers array using array_diff() :
function freeNumbers($drawID){
$minTickets = 1;
$maxTickets = totalTickets($drawID);
$takenNumbers = takenNumbers($drawID);
$freeNumbers = array();
$allTickets = range(1, $maxTickets);
$freeNumbers = array_values(array_diff($allTickets, $takenNumbers));
//return $freeNumbers;
}
Edit : added array_values() to reset the array index returned from the array_diff() function.
Edit : Or if you prefer to use the array_push() function, you could do it like :
for($i = 1; $i<$maxTickets; $i++){
if(!in_array($i, $takenNumbers)){
array_push($freeNumbers, $i);
}
}
Related
I have a mysql table with questions IDs (q_ID) and answers (a_answer). I want to use this data to populate some html later in the doc. Some of the data is separated by '|' and I want to use switch to filter. I am having trouble accessing the data by key. It works within while loop, but I need it outside.
$getData="SELECT a_answer, q_ID FROM answers ";
$result = mysqli_query($connected, $getData);
while($row = mysqli_fetch_assoc($result))
{
$arAnswer = explode('|', $row['a_answer']);
//catagorize by number of values
$arrayCount = count($arAnswer);
switch ($arrayCount)
{
case 1: //short data, no separators
//make array for ID and answer
$q = $row['q_ID'];
$a = $arAnswer[0];
$x = array($q=>$a);
break;
}; //END switch
}; //END while
Later in the doc, echo does not return value/$a for $q:
echo $x[1]
Thanks,
It looks like the problem is that you are re-setting $x every time through the loop. The following would likely be a better solution:
$getData="SELECT a_answer, q_ID FROM answers ";
$result = mysqli_query($connected, $getData);
$x = array(); // Added this.
while($row = mysqli_fetch_assoc($result))
{
$arAnswer = explode('|', $row['a_answer']);
$arrayCount = count($arAnswer);
switch ($arrayCount)
{
case 1:
$q = $row['q_ID'];
$a = $arAnswer[0];
$x[] = array($q=>$a); // Add [] after $x to push array($q=>$a)
// onto the end of the $x array.
// You can also use array_push, but
// the technique here is quicker.
break;
};
};
Edit: To create a one-dimensional array, do the following:
$x[$q] = $a;
You need to do that in the while loop and still declare the $x array before the while loop.
I have an MSSQL query where it SELECTS all rows that meet a specific criteria. In PHP I want to fetch that array, but then I want to convert it into one array per row. So if my query returns 3 rows, I want to have 3 unique arrays that I can work with.
I'm not sure how to go about this. Any help would be greatly appreciated!
Thanks, Nathan
EDIT:
$query = "SELECT * FROM applicants WHERE applicants.user_id ='{$_SESSION['user_id']}'";
$query_select = mssql_query($query , $connection);
if (mssql_num_rows($query_select) == 2){
$message = '2 students created successfully';
}
$i = 0;
while($row = mssql_fetch_array($query_select)) {
$student.$i['child_fname'][$i] = $row['child_fname'];
$student.$i['child_lname'][$i] = $row['child_lname'];
$i++;
}
$query_array1 = $student0;
$query_array2 = $student1;
You will notice from the code above that I am expecting two rows to be returned. Now, I want to take those two rows and create two arrays from the results. I tried using the solution that was give below. Perhaps my syntax is incorrect or I didn't understand how to properly implement his solution. But any help would be greatly appreciated.
$query = mssql_query('SELECT * FROM mytable');
$result = array();
if (mssql_num_rows($query)) {
while ($row = mssql_fetch_assoc($query)) {
$result[] = $row;
}
}
mssql_free_result($query);
Now you can work with array like you want:
print_r($result[0]); //first row
print_r($result[1]); //second row
...
$i=0;
while( $row = mysql_fetch_array(query){
$field1['Namefield1'][$i] = $row['Namefield1'];
$field2['Namefield2'][$i] = $row['Namefield2'];
$field3['Namefield3'][$i] = $row['Namefield3'];
$i++;
}
or if you preffer an bidimensional array:
$i=0;
while( $row = mysql_fetch_array(query){
$result['Namefield1'][$i] = $row['Namefield1'];
$result['Namefield2'][$i] = $row['Namefield2'];
$result['Namefield3'][$i] = $row['Namefield3'];
$i++
}
I have a MySQL table with reports. Fetching my reports is used by function:
function fillItByRoute($lat){
global $db;
$array = array(array());
$result = $db->query("SELECT * FROM reports WHERE latitude LIKE '$lat%' ORDER BY datetime_view");
while ($row = $db->fetch_array($result)){
$array[$int][1] = "Desc";
$array[$int][2] = $row['latitude'];
}
return $array;
}
which creates an multidimensional array.
[latitudes in MySQL are stored like 25.33236645, 23.2665666 etc...]
I have a different array:
$array_lat = array(25.5,23.1,45.2);
So, I would like to know if it is possible to get through array values of $array_lat with checking the match with values from multidimensional array created by function fillItByRoute() and storing values of function fillItByRoute() in new array?
One more time, shortly:
There are different values in $array_lat;
I want to check function fillItByRoute() with input of $array_lat
Results, which suit have to be stored in new array.
The new array should be with values (using values of my $array_lat): 25.5666332, 25.511433, 23.1233, 23.11444, 23.1, 45.269...etc, could be even hundreds of items.
Is it possible to do something like that?
Thank you very much!
I think you want something like this. It iterates through your array_lat and compares it to a value from SQL. I'm not entirely sure what you want to do with the comparison but you should put it in the if statement from the second function. If you want a new array it looks like you understand how to create those but let me know if this is too ambiguous.
function fillItByRoute($lat){
global $db;
$array = array(array());
$result = $db->query("SELECT * FROM reports WHERE latitude LIKE '$lat%' ORDER BY datetime_view");
while ($row = $db->fetch_array($result)){
$array[$int][1] = "Desc";
$array[$int][2] = $row['latitude'];
}
return $array;
function compareArrToSql($array_lat){
for($curr_lat = 0; $curr_lat<count($array_lat); $curr_lat++){
$sql_val = fillItByRoute($array_lat[$curr_lat]);
if($array_lat[$curr_lat]==$sql_val){
}
}
}
If my assumption about what you meant is correct, this is what you are after:
function fillItByRoute($lat){
global $db;
$array = array(array());
$result = $db->query("SELECT * FROM reports WHERE latitude LIKE '$lat%' ORDER BY datetime_view");
while ($row = $db->fetch_array($result)){
$latitude = number_format((float)$row['latitude'], 2, '.', '');
if (in_array($latitude,$lat)) {
$array[$int][1] = "Desc";
$array[$int][2] = $row['latitude'];
}
}
return $array;
}
I am a little late to the game and am trying to transition to PDO from mysql_* while trying to tackle a current challenge. I have an interface where I capture box number values within an array and that array is stored in another array by line item (for clarity purposes these are nested arrays).
My main purpose is to take the box numbers for a particular line item and run a mysql select query to return the number of units in that given set of boxes. If the qty in the boxes is not the quantity the user thinks there are I want it to throw an error.
Currently my challenge is I'm getting an empty result set. I believe this to be due to my array of box numbers not being properly passed to the PDO select statement. Any thoughts or guidance would be much appreciated.
Here is what I have so far:
$Boxes = $_POST['Boxes']; //this includes box numbers within an array for each line item of a form
$e = 0;
while($e<$num1){
$units = 0;
$r = 0;
$SO_Line_Item=mysql_result($result1,$e,"SO_Line_Item");
foreach ($Boxes[$e] as $a => $b) // the purpose of this loop is to take the values from Boxes and store it in $zzz which I hope to use in my Select statement below.
{
$zzz[] = $Boxes[$e][$r];
$r++;
}
//end inner foreach
$BNs= implode(',', $zzz);
$db = new PDO('mysql:host=XXXXXX ;dbname=XXXXXX', $dbuser,$dbpass);
$stmt = $db->prepare("SELECT Box_Num,Timestamp,SN,Assy_Status FROM Current_Box WHERE Box_Num IN(' . $BNs . ')");
$stmt->execute($zzz);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($results); // this shows up as an empty array
}
$e++;
}
This got it done. Thanks to Marc B for his thoughts:
$e = 0;
while($e<$num1){
$units = 0;
$r = 0;
$SO_Line_Item=mysql_result($result1,$e,"SO_Line_Item");
foreach ($Boxes[$e] as $a => $b)
{
$zzz[] = $Boxes[$e][$r];
$ce = count($Boxes[$e]);
$r++;
}
//end inner foreach
$products = implode(',', array_fill(0,$ce, '?'));
$db = new PDO('mysql:host=192.168.1.197 ;dbname=Tracking', $dbuser,$dbpass);
$stmt = $db->prepare("SELECT Box_Num,Timestamp,E3_SN,Assy_Status FROM Current_Box WHERE Box_Num IN( $products )");
$stmt->execute($zzz);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
unset($zzz);
$e++;
}
I'm new in php and got stuck doing a loop.
I have the following:
an array containing 0 or not named $receivers.
another array containing total of receivers which is a number, named $totalreceivers.
a function querying a table with the id, returning 0 or number, named status().
I want to loop through each status() of the receivers and show the sum at the end. I couldn't get it.
Any help will be appreciated. Thanks in advance.
Here is what I tried:
for ($i = 0; $i < $totalreceivers; $i++)
{
$status = status($receivers[$i]);
foreach ($totalreceivers as $value)
$status = status($receivers[$i]);
echo "the sum of receiver having status different than 0 is";
echo count($status);
}
function status($id)
{
global $dbhost;
global $dbuser;
global $dbpass;
global $dbname;
global $d1;
$q2 = mysql_query("select * from user where id ='$id' AND subscription_end_date IS NULL", $d1);
while($row2 = mysql_fetch_array($q2))
$rowservice = $row2['value'];
return $rowservice;
}
A couple things in your code don't really make sense. First, you're trying to iterate through $totalreceivers twice, one loop being nested in the other. I doubt that's what you want so you should get rid of one of them. And your first loop has a bad expression: to iterate through $totalreceivers in your first for loop, you need to have your testing expression go against the number of elements in the array and not the array itself (can use count()): for ($i = 0; $i < count($totalreceivers); $i++).
Second, you're resetting the value of $status each time you call status() in your loop. To add to it, use the += operator: $status += status($receivers[$i]);
Third, you're doing the same in status() function with $rowservice; resetting it each iteration of that while loop. Either set it once, or sum it up.
You can simplify this task by letting MySQL do more of the work for you.
You have an array $receivers which presumably contains id's for subscribers to (receivers of) something. (I may use receiver and subscriber interchangeably.)
The status() function retrieves from the database the value for each receiver where the subscription_end_date is null. I am going to assume that there is only one row per subscriber because you only return the last result via the variable $rowservice.
It's unclear from your code if you want a count of receivers with a value other than 0, or if you want a sum of all non-zero values. The question then is:
Do you want to know how many subscribers have nonzero values? or,
Do you want to know the sum of all values for subscribers with nonzero values?
Fortunately both of these can be easily found:
How many receivers have non-zero values?
$allreceivers = implode(',', $receivers);
$query = "SELECT COUNT(id) AS total_receivers
FROM user
WHERE subscription_end_date IS NULL
AND value != 0
AND id IN ($allreceivers);";
$result = mysql_query($query, $d1);
$row = mysql_fetch_array($result);
$total_receivers = $row['total_receivers'];
echo "The number of receivers having status (value) other than 0 is $total_receivers";
What is the sum of all receiver values?
$allreceivers = implode(',', $receivers);
$query = "SELECT SUM(value) AS receiver_value_sum
FROM user
WHERE subscription_end_date IS NULL
AND id IN ($allreceivers);";
$result = mysql_query($query, $d1);
$row = mysql_fetch_array($result);
$receiver_value_sum = $row['receiver_value_sum'];
echo "The sum of receiver values is $receiver_value_sum";
At first glance, it looks like you are just overwriting "$status" on each iteration. Before the loop starts, set $status to an empty array and then add to it on each iteration. For example:
$status = array();
foreach ( $totalreceivers as $value)
{
$status[] = status($receivers[$i]);
}
echo count($status);
I will try to outline some possible problems with your code below:
for ($i = 0; $i < $totalreceivers; $i++) { //This open bracket has no end bracket
/*I assume total receivers is the number of receivers; if that is the case, it shouldn't be an array, but merely a value.*/
$status = status($receivers[$i]);
/*I think you should define the status function before you call it; also, if you are just calling the status function for each value of $receivers, why don't you just do a foreach($receivers as $value) loop, like you did below with $totalreceivers. */
foreach ( $totalreceivers as $value)
/*I'm not sure what $totalreceivers is. You said its an array containing total number of receivers; again, I would think this would be a single value, and not an array*/
{
$status = status($receivers[$i]);
/*looks like you're calling the status function again*/
}
echo "the sum of receiver having status different thant 0 is"; echo count($status);
/* $status at this point would count the value from row2 for the last value in $receivers, and not a count of array values. Perhaps you could do $status[] = status($receivers[$i]), and then count($status) to save each value to an array, then count the elements. */
function status($id){
global $dbhost;
global $dbuser;
global $dbpass;
global $dbname;
/* The values above aren't used in the function; you may want to connect to the database outside of the function, before the foreach loop. */
global $d1 ;
$q2 = mysql_query("select * from user where id ='$id' AND subscription_end_date IS NULL",$d1);
while($row2 = mysql_fetch_array($q2)){
$rowservice = $row2['value'];
}
return $rowservice;
}
/*the rest looks good*/