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.
Related
I've got two tables; one a list of location names, another a list of companies, a field of which stores potentially multiple locations that the company operates in:
id LocationName
1 Aberdeen
2 Dundee
3 Edinburgh
4 Glasgow
idCompany CompanyName Locations
1 CompanyA 1, 2, 3, 4
2 CompanyB 2, 4
3 CompanyC 1
For each company's details page, I want to list the locations in which they operate, displaying the name of each. Eg. for Company B:
Dundee
Glasgow
etc.
Coming from a VB background, I'd just loop through each dataset and compare each to find the matches, but this is in PHP and I can't get it to work:
// Query for specific firm
$sqlCompany= "SELECT * FROM company_details WHERE CompanyID='".$CompanyID."';";
$rstCompany= mysqli_query($conn, $sqlCompany);
$row = mysqli_fetch_assoc($rstCompany);
// Query list of Locations
$sqlLocationNames= "SELECT * FROM Locations ORDER BY LocationName ASC;";
$rstLocationNames= mysqli_query($conn, $sqlLocationNames);
// Explode the field of locations into an array:
$LocationArray = $row["Locations"];
$LocationArray = explode (",", $LocationArray);
for ($i = 0; $i < count($LocationArray); $i++) {
while ($rowLocationNames = mysqli_fetch_assoc($rstLocationNames)) {
if ($LocationArray[$i]==$rowLocationNames["idLocation"]) {
echo $rowLocationNames["LocationName"]."<br />";
}
}
}
Running this for Company A, I'd expect to get the list of four locations from above, but I only get the first location (Aberdeen). I've tried every combination I can think of, to no avail. I need to keep the data structured this way, as I intend having a select multiple for inserting and also editing the data when I can get this working.
Any ideas where I'm going wrong?
Rather than looping the database fetch inside the iteration of the array, which results in there being no data left to read once you come to the second entry in the array (and hence at most one output, as you are seeing), just loop the database fetch and use in_array to determine whether to output the location name:
while ($rowLocationNames = mysqli_fetch_assoc($rstLocationNames)) {
if (in_array($rowLocationNames["idLocation"], $LocationArray)) {
echo $rowLocationNames["LocationName"]."<br />";
}
}
The problem is that your while loop to read the location names from the db is nested within the for loop. After the the first iteration of the for loop, the database pointer is at the end of the recordset, so when you go through the next iteration, there are no records left to read.
Try reading the records in to an array before entering the for loop and then using the while loop to iterate over the newly created array.
I have to identify unsaved value from mysql table using php and mysql, for example i using table named as numtab and i have already stored some numbers 1, 3, 4, 7, 23, 12, 45 in numb column.
now i have generated one new number randomly(for example 23) and i have to check this number with already stored numbers,
if 23 is exist in the table mean i have to generate another one new number and have to check once again with stored values, this process have to continue till finding unsaved number.
if generated value is not exist in table mean can stop the process and can store this number in table.
here below the format i am currently using
$numb=23;
$qryb="select * from numtab where numb='$numb'";
$results=mysql_query($qryb)or die("ERROR!!");
if(mysql_num_rows($results) == 1)
{
$numb=rand(1,100);
mysql_query("insert query");
}
the problem is above the code is validation once only, its not verifying second time. i think if using for or while loop mean can solve this problem, but i dont know how to do looping, so help me to solve this problem.
You can use in clause like this :
$qryb="select * from numtab where numb in('$numb')";
$results=mysql_query($qryb)or die("ERROR!!");
$count = mysql_num_rows($results);
if ($count > 0) {
echo "number exist in db";
} else {
echo "number does not exist in db";
}
You could make a while() loop to check if the numbers exist in your database. You could also retrieve all numbers from the database, store them in an array and check if the generated number exists within that array.
The first option would be something like this:
do {
$numb=rand(1,100);
$qryb="select * from numtab where numb='$numb'";
$results = mysql_query($qryb) or die("ERROR!!");
} while(mysql_num_rows($results) >= 1)
mysql_query("insert query");
The second option would be something like this:
$query = mysql_query("SELECT DISTINCT(numb) as numb FROM numtab");
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row['numb'];
}
do
{
$numb = rand(1,100);
}
while(!in_array ( $numb , $array) ;
mysql_query("insert query");
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 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
Ok so basically my code isnt working as intended.. so i took it completely apart and even placed this query at the top of page; tried hardcoding in values and its still not working. This particular query is supposed to return 5 rows of data to the $weapons array, but its not working.
$weapons_sql = "SELECT weapon_id, weapon_name, weapon_strength FROM Weapon_Info WHERE weapon_id BETWEEN 1 AND 5";
$weapons_query = mysql_query($weapons_sql);
$weapons = mysql_fetch_array($weapons_query);
print_r($weapons);
so weapon_id in the databse is a smallint(8) or something rather, (exact length im unsure of atm).. and it has 30 rows in the table, weapon_id ranging from 1-30
this particular snippet when run returns:
Array ( [0] => 1 [weapon_id] => 1 [1] => Humvee [weapon_name] => Humvee [2] => 100 [weapon_strength] => 100 )
I just don't understand it.. every other query in my entire project works save this one. Please help? I've also tried replacing BETWEEN operator with >= <= operators, which outputs the same results.
try
while($weapons = mysql_fetch_array($weapons_query)){
print_r($weapons);
}
you need a loop like this to see all rows.
You are only fetching one row of the results. You need to loop through and collect all the results:
while(false !== ($row = mysql_fetch_array($weapons_query))) {
$weapons[] = $row;
}
var_dump($weapons);
mysql_fetch_array only fetches one row of results at a time, as shown in the documentation. This means, for instance, that you can deal with sets of results that demand more memory than your script is allowed.
mysql_fetch_array returns only one row. You want to keep fetching arrays until you have all the rows:
$weapons_sql = "SELECT weapon_id, weapon_name, weapon_strength FROM Weapon_Info WHERE weapon_id BETWEEN 1 AND 5";
$weapons_query = mysql_query($weapons_sql);
$weapons = array();
while ($weapon = mysql_fetch_array($weapons_query))
{
$weapons[] = $weapon;
}
print_r($weapons);