MySQL consequent numbers - php

I use this function in my while loop to track the numbers of results.
$lvarcontributor = "SELECT * FROM dD_Contributors WHERE idAlbum = '".$idAlbum."' ORDER BY idContributor ASC";
$lvarresult=mysql_query($lvarcontributor);
$var = 0;
while ($lvarrow = mysql_fetch_array($lvarresult))
{
$var++;
//STUFF HERE...
}
How do I know the last result?
I need to know when $var++ is arrived at the last result. such as
If($var == "LAST RESULT") {
//do this
}
THANKS!

Use mysql_num_rows function - http://php.net/manual/en/function.mysql-num-rows.php

This function may be helpfull:
mysql_num_rows
if (($var + 1) == musql_num_rows($result))
{
//this is the last row
}

if( $var == mysql_num_rows($lvarresult) - 1 ) {
// this is the last row, do your thing
}

Maybe you want to check the mysql_num_rows function.
If you want to access only the last result, you should review your SQL query to fetch only this one (try messing with ORDER BY and LIMIT).
If you want to fetch every rows, but have a special treatment for the last result, then you can dut as follow:
$nextRow = mysql_fetch_array($lvarresult);
while ($nextRow)
{
$currentRow = $nextRow;
if($nextRow = mysql_fetch_array($lvarresult)) {
//Not the last row, data in $currentRow
}
else {
//Last row, data in $currentRow
}
}

Related

How can I determine if an SQL result has been returned in PHP?

I am trying to condition a table so that it only shows when SQL results are returned. If no values are returned, then do not display the table. Here is what I have:
## PPAP Information
$q23 = "SELECT * FROM $modlible.P0353 JOIN $amflible.CUSMAS ON PCUSNO = CUSNO WHERE PITEM='$id'";
$stmt23 = db2_prepare($con, $q23);
$result23 = db2_execute($stmt23);
$fin23 = db2_fetch_assoc($stmt23);
How can I detect whether or not a result has been returned to me?
This might help
$iRows = db2_num_rows($stmt23);
if ($iRows > 0) {
//Do if zero results
} else {
//Do if more results
}
or you can check
if ($fin23) {
//Row was fetched
}
You can check the SQL code returned. If the code is SQL0100 (+100) it means no rows were returned.
If there are no results your while loop will not loop
while($fin23 = db2_fetch_assoc($stmt23)){
// print your results
}

Php how to check for duplicate results?

Hi I'm currently querying from a database base user ids for a contest, However I want to avoid choosing duplicates in my results_array, this function getrandomspecies receives a array_result, this array results iterates 7 times. How test that I don't put duplicates in my results_array? I have gotten several duplicates.
function getrandomspecies($array_result){
//database connection
$dbn = adodbConnect();
foreach($array_result as $possible){
//query the results
$querys= "select * from taxonomic_units where tsn = $possible";
$resultss = $dbn -> Execute($querys);
while($rowss=$resultss->FetchRow()){
$id = $rowss['tsn']; //there ID
$ranksss = $rowss['rank_id']; //ranking id, I choose 220 and 230
if($ranksss == 220 || $ranksss == 230){
$prelimary_array[] = $id;
}
}
//grab random index
$index = array_rand($prelimary_array,1);
//put result id into a variable
$newspecies = $prelimary_array[$index];
//put that variable in an array
$results_array[] = $newspecies; //there is 7 newspecies/winners at the end, I dont want duplicates
}
return $results_array;
}
MySQL should be the following :
select distinct tsn, rank_id from taxonomic_units where tsn = $possible
But you should ideally use prepared statements.
what about this? You may do it with one query:
$querys= "select DISTINCT tsn from taxonomic_units where tsn IN (".implode(",",$array_result).") AND rank_id IN (220,230) ORDER BY RAND() LIMIT 7 ";
Loop your result array and if it does not exists add it. If you end up with less than 7, do your big loop again.
replace this line :
$results_array[] = $newspecies;
by:
$loop_1_more_time=0;
if (isset($results_array)){
foreach($results_array as $result){
if ($result == $new_specie){
$loop_1_more_time=1;
}
}
}
if ($loop_1_more_time == 0){
$results_array[] = $newspecies;
}
//there, if $loop_1_more_time equals 1, start again. To start again and be sure you have seven instead of 6 or less, You could replace your big first "foreach" loop with a "for" loop that depends of the count() of the $array_result, and the $array_result would be array_result[$i] instead of $possible. $i would start at 0 and increment at each end of loop. It would not be incremented if ­­$loop_1_more_time==1;.
Example :
for ($i = 0; $i < count($array_result); $i++) {
//stuff
//if ($loop_1_more_time=1;) { $i--; }
}
Why don't you try shuffling the array, and then picking the first X numbers?
That way, rather than having to check the results array for duplicates, it will never come up in the first place

as of now it just ignores the if statement and gives them a ticket everytime.php, mysql, If else

Alright so i'm trying to put value in an array and shuffle them to be random, then have it use that random value in a query. I know my code is bad and not to use mysql anymore lets stay off that topic please.
I don't understand why this isn't working I have other things like it that work just fine.
right now it ignores the if statement and gives them a ticket each time.
if(isset($_POST['Submit'])) {
$ticket = array("0","0","0","0","0","0","0","1");
shuffle($ticket);
if ($ticket >= 1) {
echo "You have Found a Shop Ticket!" ;
mysql_query("UPDATE users SET ticket=ticket+1 WHERE username = '".$_SESSION['username']."'")
or die(mysql_error());
} else {
echo "";
}
}
You're checking if the entire array is >= 1, which is obviously TRUE all the time.
Pick a value instead:
$ticket = array_shift($ticket); // do this after you shuffle
try
if (current(shuffle($ticket)) >= 1) {
# yay
} else {
# ney
}
$ticket is an array, not a number.
u could use foreach or array_map to do this.
example:
function foo($n){
if($n >= 1){//do something}
}
$ticket = array("0","0","0","0","0","0","0","1");
shuffle($ticket);
array_map('foo', $ticket);

PHP - MySQL, think the $result is empty on some moments when there should be elements in

I have a PHP page with 3 dropdownlists on it. Everytime with an 'onchange' event a javascript docs get's the selected value's and transfers it to a php function, where I can transfer them to my mysql-database and get results out of them. This thing works perfect, but not when I apply my logic to define which function I should call
My php page contains the effective logic (see code-box) and underneed there are the 2functions with the actions. The function do work, but the problem is this. There's the possibility in the if-else construction that the functions can be called on 2 different moments. The first time in the if-else construction both of the calls are succesfull and the result is what it should be, the second moments it seems that the $result parameter is empty?
$result = mysql_query($sql) or die("Query failed with error: ".mysql_error());
$aantal = mysql_num_rows($result);
if($amount == 0){
echo "<p>This combination does not exist</p>";
}
else {
// lists are empty
if($soort == 'Empty' && $land == 'Empty' && $jaar == 'Empty'){
}
else {
if ($aantal > 2){
maketable($aantal, $result); // -> **succesfull call**
}
else if($aantal == 1){
makedetails($result); // -> **succesfull call**
}
else {
$first = mysql_result($result, 0);
$second = mysql_result($result, 1);
if (($second - $first) == 1){
makedetails($result); // -> **does not work**
}
else {
maketable($aantal, $result); // -> **does not work**
}
}
}
}
function maketable($aantal, $result) { … }
function makedetails($result){ … }
greetings
You don't show your query, so we can't tell what's going on. But mysql_result by default returns the FIRST field in the specified row, if you don't explicitly state which field to use, so unless your query is
SELECT somenumber FROM yourtable ...
then your mysql_result is going to be fetching who knows what. Note that you're also comparing that default 'first' value from two different rows - are you sure the query is actually returning 2+ rows of data?
$aantal is the number of rows affected by the query. Your logic does not work because you're trying to use query results when there are no rows affected.
Your logic:
$result = mysql_query($sql);
$number_of_rows = mysql_num_rows($result);
if ($number_of_rows > 2)
{
//do something
}
else if ( $number_of_rows == 1)
{
//Do something else
}
else if( $number_of_rows == 2 OR $number_of_rows == 0)
{
// Do something else (the part which fails)
}
The only way to reach that part and not fail is if the rows affected are exactly 2. When they are 0, the query didn't return anything and you are trying to access an empty result set.
Had to fetch my result once more to make it possible to loop through my array once again.
$first = mysql_result($result, 0);
$second = mysql_result($result, 1);
$result = mysql_query($sql) or die("Query failed with error: ".mysql_error());
But thanks for the help!
greetings

goto equivalent for php version < 5.3.0?

I need to use the goto operator in my code as I can't seem to think of a way around it. However the problem is my host only has PHP version 5.2.17 installed.
Any ideas?
Below is my code:
if ($ready !=="y")
{
$check=mysql_query("SELECT `inserted` FROM `team`");
$numrows = mysql_num_rows($check);
$i="0";
while ($i<$numrows && $row = mysql_fetch_assoc($check))
{
$array[$i] = $row['inserted'];
$i++;
}
if (in_array("n", $array))
{
goto skip;
}
else
{
mysql_query("
UPDATE game SET ready='y'
");
}
}
skip:
There are a few anti-patterns in your code. Let's clean it up. I'll explain what's been changed in a jiffy.
if($ready !== "y") {
$sth = mysql_query("SELECT inserted FROM team WHERE inserted = 'n'");
if(mysql_num_rows($sth) > 0) {
mysql_query("UPDATE game SET ready = 'y'");
}
}
First things first: There is no need to perform a query, fetch all of the results, then loop through those results (in_array) looking for a specific value. Let the database do that for you by expressly looking only for rows where inserted is the string literal "n".
Because we know that we're only getting "n" records back, we just need to check if there are any results. If so, run the query. If there are no "n" records, the UPDATE isn't run.
If you need to know that the UPDATE ran, add a check for it:
$ran_update = false;
if($ready !== "y") {
$sth = mysql_query("SELECT inserted FROM team WHERE inserted = 'n'");
if(mysql_num_rows($sth) > 0) {
mysql_query("UPDATE game SET ready = 'y'");
$ran_update = true;
}
}
if($ran_update) {
// ...
}
You want to use the correct control word to break from the loop:
if ($ready !=="y")
{
$check=mysql_query("SELECT `inserted` FROM `team`");
$numrows = mysql_num_rows($check);
$i="0";
while ($i<$numrows && $row = mysql_fetch_assoc($check))
{
$array[$i] = $row['inserted'];
$i++;
}
if (in_array("n", $array))
{
break;
}
else
{
mysql_query("
UPDATE game SET ready='y'
");
}
}
The break keyword will do exactly what you want: End the execution of the while loop. Never ever ever use a goto!
As a direct response to the title of this post:
do{
if (!$condition){
break;
}
// Code called if conditions above are met
}while(0);
//Code always called
In some circumstances, this, or a goto, can make for very tidy and readable code.
First, you could use a break to exit your initial loop. Second, if you need to test for anything, set a variable (must be global not local) as a flag or indicator before calling break, then do a conditional test statement where your skip line is to perform any additional steps you need.

Categories