i want that against each numbers, its call_count and duration are saved in single array.. this is my table:
Number Call_count duration
03455919448 4 14
03215350700 2 35
i want somethng like this:
foreach($number as $number1)
{
$data=array($row['call_count']<3,$row['duration']<20,1)
}
basically i want against each number its count and duration are checked for some values and if they meet the condition, display output 1... actually i can do it with simple if-else but as i have to train my dataset for neural network implementaion so all rows must be in one array? can anyone please help me out?
Maybe I don't understand quite well your code, but:
foreach($number as $number1)
$number1 is never used in your foreach :
$data=array($row['call_count']<3,$row['duration']<20,1)
So I guess $number1 is $row.
Second, it would help me if you provide the SQL Statement you are using now.
You could do a query like:
select Number, if(Call_count<3, if(duration<20, 1, 0), 0) as checked from tablename;
This gives you only the number, and 1 if both conditions are met, and 0 otherwise.
After that, in php do a loop (presented in plain mysql* funcions)
$data = array();
while ($row = mysql_fetch_assoc($result)) { // row will be an array with Number and checked as items
$data[] = $row;
}
// at this point you will have all rows in one array, with number and corresponding 1/0 in each item
Related
I have a query that returns 2 arrays they can have anywhere from 0 to 5 results for each array. i need to take the results of the array and use them to run a second query where the columns in the where statment are assigned by the array
here is the base code
$result = $conn->query("SELECT UsedQty,NewQty FROM Legend where Name like '$Use%'");
while($row = $result->fetch_assoc()) {
$UsedQty[$g]=$row['UsedQty'];
$NewQty[$g]=$row['NewQty'];
$g++;
}
$result = $conn->query("select * from remainder where po = '$po' and
(($UsedQty[0]>0 or $UsedQty[1]>0 or $UsedQty[2]>0) or
($NewQty[0]>0 or $NewQty[1]>0 or $NewQty[2]>0)) limit $cnt,1");
and as long as there are values for all of the variable is works, but if there are only 1 or 2 (or 0) values for the array it will not work
i have also tried
$result = $conn->query("select * from remainder where po = '$po' and
($UsedQty[$g]>0) limit $cnt,1");
it has to be done in a single query as the variable $cnt is keeping track of records and order---closed system so security injections are not an issue
Pad the arrays with the desired number of elements before executing the query. Something like this might do the trick:
while ($g < [desired_count]) {
array_push($UsedQty,0);
array_push($NewQty,0);
$g++;
}
The [desired_count] should be set to the number of elements that will be tested in the WHERE clause.
It is not apparent how the query will return 0-5 rows, (based on "2 arrays [that] can have anywhere from 0 to 5 results for each array"). The query will return 1 array; the while loop creates 2 arrays. Perhaps this ($UsedQty[0]>0 or $UsedQty[1]>0 or $UsedQty[2]>0) is a typing shortcut and the intention is to test 5 values? In that case [desired_count] will be 5.
I'm having some trouble solving a nested loop. I have a form that sends a series of data to the mysql database. I use a while function and it works correctly. But now I have an checkbox option for each entry, and that's my problem.
The checkbox should be sent to another table, with the id, the series ID and a checkbox per row.
But all I can do is make the answer from the first series repeat through the others.
This is what I want:
Lance 1
Checkbox 1
checkbox 3
checkbox 4
Lance 2
checkbox 2
checkbox 3
Lance 3
checkbox 1
checkbox 2
checkbox 3
This is what I get
Lance 1
Checkbox 1
checkbox 3
checkbox 4
Lance 2
Checkbox 1
checkbox 3
checkbox 4
Lance 3
Checkbox 1
checkbox 3
checkbox 4
My loop code so far:
$i=0;
$elements = count($lance);
while ($i < $elementss) {
$query = "INSERT INTO
mapa_bordo_lance
(id_mb, lance, data_lance, lat, lon, anzol, isca, hora_lan, hora_rec, ave_capt, mm_uso)
VALUES
('$id_mb', '$lance[$i]', '$data_lance[$i]', '$lat[$i]', '$lon[$i]', '$anzol[$i]', '$isca[$i]', '$hora_lan[$i]', '$hora_rec[$i]',
'$ave_capt[$i]', '$mm_uso[$i]')";
$result = mysql_query($query, $link);
$y = 0;
$elementss2 = count($checkbox);
while ( $y < $elements2) {
$query = "INSERT INTO mapa_bordo_mm (id_mb, lance, mm)
VALUES ('$id_mb', '$lance[$y]', '$medida_metiga[$y]')";
$result = mysql_query($query, $link);
$y++;
}
$i++;
}
About the Checkboxes
According to the information presented in your question, comments, and pasted snippets, I have the feeling that you are getting the same Checkbox values for each Lance because in this code:
$y = 0;
$elementss2 = count($checkbox);
while ( $y < $elements2) {
$query = "INSERT INTO mapa_bordo_mm (id_mb, lance, mm)
VALUES ('$id_mb', '$lance[$y]', '$medida_metiga[$y]')";
$result = mysql_query($query, $link);
$y++;
}
it appears that the $medida_metiga[$y] part is only calling the same $medida_metiga (and its array items...) rather than calling the next $medida_metiga0 and $medida_metiga1 parts in your example array (given in this link.)
You may need to find a way to concatenate your $medida_metiga array/key with a number (like 0, 1, ... etc.) kind of like this:$medida_metiga[$y.$some_number_here] in order to find the matching checkboxes. But you may also want to rethink the naming for the $medida_metiga, $medida_metiga0, $medida_metiga1 approach.
For example, instead of:
$medida_metiga
What if you began with:
$medida_metiga0
This would allow you to more easily iterate through the array/keys without having to check if this item has a number at the end or not.
About the SQL
When you have a chance, it would probably be a good idea to check out how to use prepared statements in PHP if for no other reason than to prevent SQL injection. This other answer may give you some tips on getting started with prepared statements.
About the Looping
While while loops can technically work for your purposes, it might be worth using either for or foreach loops in this case, as those sorts of loops can help keep code clean and improve code readability. It might be worth taking a look at this other answer for tips on selecting loops for different applications.
About the Variable Naming
You may have already seen this, but do make sure that your variable names ($elements or $elementss?) match:
$elements = count($lance);
while ($i < $elementss) { ... }
// ...
$elementss2 = count($checkbox);
while ( $y < $elements2) {
I have a query like this:
$sql = "SELECT * FROM doctors WHERE city ='$city' LIMIT 10 ";
$result = $db->query($sql);
And I show the result like this :
while($row = $result->fetch_object()){
echo $row->city;
}
The Problem :
Mysql , will search through my database to find 10 rows which their city field is similar to $city.
so far it is OK;
But I want to know what is the exact row_number of the last result , which mysql selected and I echoed it ?
( I mean , consider with that query , Mysql selected 10 rows in my database
where row number are:
FIRST = 1
Second = 5
Third = 6
Forth = 7
Fifth = 40
Sixth = 41
Seventh = 42
Eitghth = 100
Ninth = 110
AND **last one = 111**
OK?
I want to know where is place of this "last one"????
)
MySQL databases do not have "row numbers". Rows in the database do not have an inherent order and thereby no "row number". If you select 10 rows from the database, then the last row's "number" is 10. If each row has a field with a primary id, then use that field as its "absolute row number".
You could let the loop run and track values. When the loop ends, you will have the last value. Like so:
while($row = $result->fetch_object()){
echo $row->city;
$last_city = $row->city;
}
/* use $last_city; */
To get the row number in the Original Table of the last resultant (here, tenth) row, you could save the data from the tenth row and then, do the following:
1. Read whole table
2. Loop through the records, checking them against the saved data
3. Break loop as soon as data found.
Like So:
while($row = $result->fetch_object()){
echo $row->city;
$last_row = $row;
}
Now, rerun the query without filters:
$sql = "SELECT * FROM doctors";
$result = $db->query($sql);
$rowNumber = 0;
while($row = $result->fetch_object()) {
if($row == $last_row) break;
$rowNumber++;
}
/* use $rowNumber */
Hope this helps.
What you can do is $last = $row->id; (or whatever field you want) inside your while loop - it will keep getting reassigned with the end result being that it contains the value of the last row.
You could do something like this:
$rowIndex = 0;
$rowCount = mysqli_num_rows($result);
You'd be starting a counter at zero and detecting the total number of records retrieved.
Then, as you step through the records, you could increment your counter.
while ( $row = $result->fetch_object() ) {
$rowIndex++;
[other code]
}
Inside the While Loop, you could check to see whether the rowIndex is equal to the rowCount, as in...
if ($rowIndex == $rowCount) {
[your code]
}
I know this is a year+ late, but I completely why Andy was asking his question. I frequently need to know this information. For instance, let's say you're using PHP to echo results in a nice HTML format. Obviously, you wouldn't need to know the record result index in the case of simply starting and ending a div, because you could start the div before the loop, and close it at the end. However, knowing where you are in the result set might affect some styling decisions (e.g., adding particular classes to the first and/or last rows).
I had one case in which I used a GROUP BY query and inserted each set of records into its own tabbed card. A user could click the tabs to display each set. I wanted to know when I was building the last tab, so that I could designate it as being selected (i.e., the one with the focus). The tab was already built by the time the loop ended, so I needed to know while inside of the loop (which was more efficient than using JavaScript to change the tab's properties after the fact).
i m dealing with 2 tables.I just want to know whether there is something code that helps me fetching rows for multiple times without writing same query for that many times:
Example:
while($row1=mysqli_fetch_array($result1)) {
while($row2=mysqli_fetch_array($result2)){
//checking for some condition
}
}
In above code unlike array we cant reset a variable outside the inner loop as follows
while($row1=mysqli_fetch_array($result1)) {
$number=0;//so that v can start from first row
while($row2=mysqli_fetch_array($result2)){
//checking for some condition
}
}
I m totally aware that rows and array are different,So i m asking if there is FOR loop we can use on rows?? like:
while($row1=mysqli_fetch_array($result1)) {
for(...){
//so dat it will xecute no.of whileloops*no.of for loops.
}
}
if not clear ask for more.
Your suggestions are much obliged.
Edit:
table: Year
1999
2000
2002
2004
2000
$result=mysqli_query($con,"select distinct Year from table_name");
dataset=mysqli_fetch_array($result)..
If I got it right, you want to match all the results of the first query against all the results of the second query.
In that case, you should first gather all the results of both queries in two PHP arrays (of arrays) and then work with these variables, like so:
$list1=array();
while ($row=mysqli_fetch_array($result1)) $list1[] = $row;
$list2=array();
while ($row=mysqli_fetch_array($result2)) $list2[] = $row;
foreach ($list1 as $row1)
foreach ($list2 as $row2)
{
match_against ($row1, $row2);
}
Note that it looks very much like an SQL JOIN done in PHP.
Why not, as long as the number of results stay within reasonable bounds.
But if it's not the case (i.e. $list1 or $list2 could contain hundreds of elements), be aware that your code will very likely be a lot less efficient than what a DB engine can do.
That's why you might want to consider replacing this code with an SQL query.
Try this (if i understood ):
while( list($row1,$row2) = array(mysqli_fetch_array($result1),mysqli_fetch_array($result2)) ){
// check condition
}
$dataSet1 = mysqli_fetch_all($result1);
$dataSet2 = mysqli_fetch_all($result2);
foreach($dataSet1 AS $row1){
foreach($dataSet2 AS $row2){
}
}
Something like this might work?
I'm trying hard to wrap my head around what I'm doing here, but having some difficulty... Any help or direction would be greatly appreciated.
So I have some values in a table I've extracted according to an array (brilliantly named $array) I've predefined. This is how I did it:
foreach ($array as $value) {
$query = "SELECT * FROM b_table WHERE levelname='$value'";
$result = runquery($query);
$num = mysql_numrows($result);
$i=0;
while ($i < 1) {
$evochance=#mysql_result($result,$i,"evochance"); // These values are integers that will add up to 100. So in one example, $evochance would be 60, 15 and 25 if there were 3 values for the 3 $value that were returned.
$i++;
}
Now I can't figure out where to go from here. $evochance represent percentage chances that are linked to each $value.
Say the the favourable 60% one is selected via some function, it will then insert the $value it's linked with into a different table.
I know it won't help, but the most I came up with was:
if (mt_rand(1,100)<$evochance) {
$valid = "True";
}
else {
$valid = "False";
}
echo "$value chance: $evochance ($valid)<br />\n"; // Added just to see the output.
Well this is obviously not what I'm looking for. And I can't really have a dynamic amount of percentages with this method. Plus, this sometimes outputs a False on both and other times a True on both.
So, I'm an amateur learning the ropes and I've had a go at it. Any direction is welcome.
Thanks =)
**Edit 3 (cleaned up):
#cdburgess I'm sorry for my weak explanations; I'm in the process of trying to grasp this too. Hope you can make sense of it.
Example of what's in my array: $array = array('one', 'two', 'three')
Well let's say there are 3 values in $array like above (Though it won't always be 3 every time this script is run). I'm grabbing all records from a table that contain those values in a specific field (called 'levelname'). Since those values are unique to each record, it will only ever pull as many records as there are values. Now each record in that table has a field called evochance. Within that field is a single number between 1 and 100. The 3 records that I queried earlier (Within a foreach ()) will have evochance numbers that sum up to 100. The function I need decides which record I will use based on the 'evochance' number it contains. If it's 99, then I want that to be used 99% of the time this script is run.
HOWEVER... I don't want a simple weighted chance function for a single number. I want it to select which percentage = true out of n percentages (when n = the number of values in the array). This way, the percentage that returns as true will relate to the levelname so that I can select it (Or at least that's what I'm trying to do).
Also, for clarification: The record that's selected will contain unique information in one of its fields (This is one of the unique values from $array that I queried the table with earlier). I then want to UPDATE another table (a_table) with that value.
So you see, the only thing I can't wrap my head around is the percentage chance selection function... It's quite complicated to me, and I might be going about it in a really round-about way, so if there's an alternative way, I'd surely give it a try.
To the answer I've received: I'm giving that a go now and seeing what I can do. Thanks for your input =)**
I think I understand what you are asking. If I understand correctly, the "percentage chance" is how often the record should be selected. In order to determine that, you must actually track when a record is selected by incrementing a value each time the record is used. There is nothing "random" about what you are doing, so a mt_rand() or rand() function is not in order.
Here is what I suggest, if I understood correctly. I will simplify the code for readability:
<?php
$value = 'one'; // this can be turned into an array and looped through
$query1 = "SELECT sum(times_chosen) FROM `b_table` WHERE `levelname` = '$value'";
$count = /* result from $query1 */
$count = $count + 1; // increment the value for this selection
// get the list of items by order of percentage chance highest to lowest
$query2 = "SELECT id, percentage_chance, times_chosen, name FROM `b_table` WHERE `levelname` = '$value' ORDER BY percentage_chance DESC";
$records = /* results from query 2 */
// percentage_chance INT (.01 to 1) 10% to 100%
foreach($records as $row) {
if(ceil($row['percentage_chance'] * $count) > $row['times_chosen']) {
// chose this record to use and increment times_chosen
$selected_record = $row['name'];
$update_query = "UPDATE `b_table` SET times_chosen = times_chosen + 1 WHERE id = $row['id']";
/* run query against DB */
// exit foreach (stop processing records because the selection is made)
break 1;
}
}
// check here to make sure a record was selected, if not, then take record 1 and use it but
// don't forget to increment times_chosen
?>
This should explain itself, but in a nutshell, you are telling the routine to order the database records by the percentage chance highest chance first. Then, if percentage chance is greater than total, skip it and go to the next record.
UPDATE: So, given this set of records:
$records = array(
1 => array(
'id' => 1001, 'percentage_chance' => .67, 'name' => 'Function A', 'times_chosen' => 0,
),
2 => array(
'id' => 1002, 'percentage_chance' => .21, 'name' => 'Function A', 'times_chosen' => 0,
),
3 => array(
'id' => 1003, 'percentage_chance' => .12, 'name' => 'Function A', 'times_chosen' => 0,
)
);
Record 1 will be chosen 67% of the time, record 2 21% of the time, and record 3 12% of the time.
$sum = 0;
$choice = mt_rand(1,100);
foreach ($array as $item) {
$sum += chance($item); // The weight of choosing this item
if ($sum >= $choice) {
// This is the item we have selected
}
}
If I read you right, you want to select one of the items from the array, with some probability of each one being chosen. This method will do that. Make sure the probabilities sum to 100.