using mysqli::fetch_array but only getting 2 of the items? - php

Ive got a database that Im trying to pull data from (the name of each unique identifier and also how many times it appears in the database) by using this query:
$query = "SELECT Dcol, COUNT(*) FROM dtest GROUP BY Dcol";
and then using this to actually print the data out:
while($result->fetch_row()){
$row = $result->fetch_array(MYSQLI_NUM);
printf("<strong>%s</strong> : <i>%s</i><br />",$row[0],$row[1]);
}
and it works great except for the fact that it only gets 2 of the 4 unique items from the Dcol column. I've tested it by just putting everything that the fetch_row() returns into an array and then using print_r and when I do that it actually shows all 4 with the correct number of times it was used, but when I try to print it using the above statement I get 2 of the 4 (the second and fourth one, if that helps at all)
Can anyone tell me why this would only be giving two of the four unique items?

The 'fetch_row' command is getting the first row - then you ask for the 2nd row with the 'fetch_array' command. So you're only seeing 2 and 4 as a result.

Related

db2_fetch_assoc() fails midway through iterating over result set

I'm running on IBM i (an AS/400) V7R2, PHP v5.6.5, Zend Server v8.0.2.
I have a query which takes less than a second to execute from iNavigator. When I run the same query from a PHP script and then loop through it using:
$numRows = 0;
while ($row = db2_fetch_assoc($stmt))
{
//Do stuff
$numRows++;
}
echo $numRows++;
$numRows ends up only being a fraction of the expected result set and I get this error in the Zend logs:
PHP Warning: db2_fetch_assoc(): Fetch Failure in /path/to/script.php on line XXX
Note that the value of $numRows varies every time I run it. It is almost like it is timing out and ending before it can iterate through all of the result sets, but the page loads in seconds. Outside of results missing from the result set everything seems to function and load perfectly fine on the page.
Does anyone know what might be contributing to this behavior?
Is it possible that the data has errors? One possibility is decimal data errors.
#Buck Calabro got me on the right track. The issue wasn't decimal data errors but rather a sub-query in the view definition which was returning more than 1 row. So it was a "Result of select more than one row" error.
If I did a simple SELECT * FROM VIEW1 in iNavigator or PHP everything seemed to come up fine. It wasn't until I either ran the mentioned query in STRSQL or ran the view definition manually as if it weren't part of a view in iNavigator that the error would be reported.
To help future users here is basically what was happening.
TABLEA contains a single column with 10 rows.
I write a view such as this:
CREATE VIEW VIEWA (COL1, COL2, COL3)
AS SELECT 1, 2, (
SELECT * FROM TABLEA
);
The sub-select is returning 10 rows and the DB engine doesn't know how to handle it. If instead you add FETCH FIRST 1 ROW ONLY as part of the sub-query the error is fixed. That isn't to say logically you will get the correct results though, since you may need the 2nd row not the first. Second it would also be suggested you specify an ORDER BY and/or WHERE clause to ensure the first (and only) row returned would be what you want.

Output won't display if it exists more than once in the DB

Alright so I'm testing with some SQLi on localhost and I stumbled upon a really wierd "error" that I've never seen before.
I'm trying to get information from a database called "game" with a table called "users" (15 columns)
Here's the first part of the table:
http://i.gyazo.com/7e6c81ef2b235a778dec1fd343e8c3bf.png
The hashes are "test" and "test1".
So I'll get the first hash with
'+union+select+concat(password),2,3,4,5,6,7,8,9,10,11,12,13,14,15+from+game.users limit 0,1--+-
a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
Let's continue, we move to the other row with
'+union+select+concat(password),2,3,4,5,6,7,8,9,10,11,12,13,14,15+from+game.users limit 1,1--+-
and it gets b444ac06613fc8d63795be9ad0beaf55011936ac
So everything's working correctly, HOWEVER if I would change the users hashes so they have the same as
http://i.gyazo.com/df1154a02cae5e5bbde04d7e47256899.png
then our second injection doesn't work anymore
'+union+select+concat(password),2,3,4,5,6,7,8,9,10,11,12,13,14,15+from+game.users limit 1,1--+-
it returns nothing how and why is this possible and most importantly how would I fix this? I only want it to get 1 result at a time, not more.
I'm testing on a Windows 7 machine using Wamp.
The query being executed is
SELECT *
FROM users
WHERE id='-1'
UNION
SELECT concat(password),2,3,4,5,6,7,8,9,10,11,12,13,14,15
from game.users
limit 1,1
From MySQL Manual:
The default behavior for UNION is that duplicate rows are removed from the result.
http://dev.mysql.com/doc/refman/5.6/en/union.html
If you changed the password field to be the same for those two rows, then you will also two identical rows in the second part of the UNION that will be de-duped.
What you are doing however makes basically no sense. Why are you using CONCAT, but then not concatenating anything?
Also, why would you use an offset of 1 if you only wanted one row? I would think your offset should be 0 (i.e. LIMIT 0, 1).
Finally, why are you even doing this union to begin with?
What is probably happening is there is no record meeting the criteria of user id = -1 then because of the de-dupe, there is only one row returned in the pre-limit result set, which you are skipping over by specifying an offset of 1. Thus you get an empty result set.
Before when the password fields were different, you had two different rows in the pre-limit result set, thus there was a row at offset 1.

echo specific item from multidimensional array

Been hammering away at this for weeks. I think it's actually simple...but I just can't get it.
I want to pull info from the database and use it in divs later on in my html. I've been successful in other cases looping through and displaying the full results of a query in the past. In this case I just want to echo a specific team name or team ID in my html. All the data gets used...so I'd like to just have one query, but the data gets used in different divs in different places...so being able to echo specific parts of the query is important.
The query I have returns 10 rows and 4 columns.
<?php
$playoffs = mysqli_query($con, "SELECT playoffseed, ttName, teamID, ttsUID
FROM standings
WHERE ttsUID = $season_view
AND playoffseed > 0
ORDER BY playoffseed
LIMIT 10");
?>
Now, I think I've learned that this query returns a result set and not an array. It needs to be processed using some php to turn it into an array. Correct? And given the fact it's got multiple columns and rows once it is processed it would be a multidimensionsal array. Ok I've scoured this site and google...tried many ideas using mysqli_fetch_array, mysqlifetch_assoc, and any other mysqli_fetch that I'd come across.
In my mind anyway, after processing the query with some php I'm thinking the array would look like this...
playoffseed ttName teamID ttsUID
1 Buffalo 13 1993
2 Miami 19 1993
3 Detroit 8 1993
4 Denver 3 1993
5 Chicago 26 1993
...and so on. 10 rows total
After that I'd like to be able to call on (echo) various items from the above in my html. Let's say in one div I'd like to be able to echo the ttName "Detroit" and then to call and image associated with the teamID I'd like to be able to call that too (it'd be something like this in my html...
IMG SRC="../images/<?php echo "teamID" ?>.jpeg
...where in this case Detroits image is "8.jpg").
How can that be done? How do I correctly fetch the array and then echo a specific item of data from it?
I'm thinking if the above is an associated array I'd be able to echo something like this to return "Detroit"...
echo $playoffs[3]['ttName'];
[3] = 3rd row and ['ttName'] = column. no? I realize that [3] would actually refer to the 4th row if it's actually pointing to rows that start with zero and not one, but I'd like to be able to call on the item by using the "playoffseed" identifier, but I'm just too confused at this point.
I already feel I've made this question too confusing in itself. Thanks a ton for your help.
kevinabelita:
this could shed some light to you us2.php.net//manual/en/mysqli-result.fetch-assoc.php
OP:
been there a 100 times. i'm just not getting something. long story short in case the above is too much....take query and process it with php to create an array...then echo....say..."detroit" from that array
And still didn't notice this simple way?
while ($row = mysqli_fetch_assoc($playoffs)) {
$values[]=$row;
echo $row["ttName"];
//print_r($row); // if you want to see all the data this row contains
}
mysqli_free_result($result);
}
Now you can use $values with an index like you wish. i.e.
echo $values[0]["ttName"];
Edit
I mistakenly was trying to execute the query again. Fixed in the code above. Now for a little explanation of what you are confused with. Here's how the flow goes roughly
Connect to the database
Prepare/Run a query (mysqli_query in this case)
Store the result resource In a variable ($playoffs in this case)
Either fetch all rows from that result all together or fetch one by one. In this case mysqli_fetch_assoc in a loop is fetching the rows one by one till all of the result set has been fetched.
Provide that fetched row as an array for you to use, in that case its stored in $row variable.

Why Output of PHP script and MySQL database data are not same?

Please refer to the following image. In this image number (1) is what the field position in my database userdb looks like before I run my code. Number (2) is what change I am expecting in the position field of some rows after I run the code. The value of the position field of second row is primarily 2 what I want to be changed to 3. Similarly, The values of the position field of third, fourth and fifth rows are primarily 3, 4 and 5 respectively what I want to be changed to 4, 5 and 6 respectively. So, I run the following code and in my browser I see what I expect. However, In the database I see wrong data is inserted, like number (3) on the image. Notice that my last expected value of the position field is 6 (for fifth row), but I am getting 6 in all rows!!!
Here is the code I run:
$requestedPosition = 2; $oldPosition = 6;
for($i=$requestedPosition+1; $i <= $oldPosition; $i++){
$query = mysql_query("UPDATE userdb SET position = '$i' WHERE position='{$requestedPosition}' ");
echo 'Old Position: '.$requestedPosition.' is now: '.$i.'<br>';
$requestedPosition++;
}
I think something must be wrong in the mysql query. If I comment out the query I get expected result in browser. However, to insert those data into database I need to run the query but when I do it, I get wrong data inserted in database. I am on windows, running PHP 5.3.13, MySQL 5.5.24.
Most Confusingly, in the for loop, if I change $i=$requestedPosition+1; to $i=$requestedPosition; I get 2,3,4,5 inserted (in 2nd,3rd,4th,5th row respectively) rather than 6,6,6,6. However, I want 3,4,5,6 inserted (in 2nd,3rd,4th,5th row respectively), so I had to use $i=$requestedPosition+1; in for loop, and when I do, Code gets Mad!!! So, do I :( Stuck with this (with bad headache) for last two days!
There's a slight flaw in your logic.
The first time that your loop runs, you're updating one row - you're updating the row with position 2 to be position 3. This is fine.
But the second time the loop runs, you're updating all rows where position is 3 to be position 4 - and there's two of them now, the one from the table, and the one you've just updated. The same happens on the third and fourth iteration.
You can probably do this more elegantly, with one call:
$query = mysql_query("UPDATE userdb SET position = position + 1 WHERE position >={$requestedPosition} AND position <= ${oldPosition}' ");
I've not tested that, but it should at the least give you an idea.

Can you help me understand this php script

I'm a fairly newbie php coder, got this php code in a tutorial to create a randomly generated quote, but I don't fully understand the code
IN particular, I don't understand
a) line 4 -- where does the "rows" come from. Is that a name made up on the spot. Could it just as easily have been called "ferrari"
b) line 9 -- where does "storedtext" come from? is it just made up on the spot?
c) based on the code, do you have an idea what the database is supposed to look like. Would it just be a database called "text" with a table called "quotables" in it?
<?
//
// count() gets the number of rows from database text--
//it assigns a number to rowcount
1 $rowcount = mysql_query("select count() as rows from text");
// don't understand what exactly is happening here, where did "rows" come from
2 while ($row = mysql_fetch_assoc($rowcount))
3 {
4 $max = $row["rows"];
5 }
// Selects an item's index at random
6 $rand = rand(1,$max)-1;
//there is a database table called "quotables?" taking one random row
7 $result = mysql_query("select from quotables limit $rand, 1");
8 $row = mysql_fetch_array($result);
//where does "storedText" come from?????
9 $randomOutput = $row['storedText'];
10 echo '<p>' . $randomOutput . '</p>';
11 ?>
where does the "rows" come from?
It is a name assigned to a value in the SQL query select count() as rows from text.
where does "storedtext" come from?
It seems to be the name of a field in the quotables table.
based on the code, do you have an idea what the database is supposed to look like. Would it just be a database called "text" with a table called "quotables" in it?
No. We cannot say anything about the database name. But this database contains the tables text and quotables where the latter has at least the field storedText.
a) Yes.
b) It must be a column in the database. In line 7, it's pulling all columns in the database, but isn't specific about it's names
c) No, you could print_r($row) to see the table structure though (will print out the array, showing all columns). You should also have access to the db (to make this work, you'll need the db and tables set up), so however you mysql_connect() and mysql_select_db() will tell you the name of the host/db.
A) rows is the alias given to the count() function in the mysql query in line 1. If you changed rows in line one to ferrari then changed rows in line 4 to ferrari then it would still work.
B) stored text comes from the second mysql query on line 7. This will be the name of a column from within that table.
C) Based on the code you have given I can tell you that you have a database which I do not know the name of and that database has two tables one called text and the other quotables I can tell you that quotables has one column called storedText.
a) rows came from sql query "select count() as rows from text"
b) I think there "*" in line 7 because there is no column specified, so if * is there then its selecting all the columns in that table and "storedText" is one column in it
c) text,quotables both are tables
a) rows comes from the SQL query:
$rowcount = mysql_query("select count() as rows from text");
It is the name given to the count() column.
b) storedText is a column in the quotables table, probably with the quote in it.
What the script does is, get a row count from the text table.
Get a random number in the range of 1 to $max.
Get the corresponding quote from the quotables table.
The SQL doesn't tell us anything except that quotables is a table and storedText is a column in it. The names in strings show up in the SELECT statement and come into existance when it completes.
"rows" come from mysql table. This is the name of column. For instance, if you have table with 2 columns, and one of them named like "price" you should use $var['price'] after using mysql_fetch_assoc to use it.
'storedText' the same.
ANS - 1
in while loop, we have assigned value to $row...
ANS - 2
If you have looked code carefully, on line no 8, you have again assigned value to $row.
in line no 8 mysql_fetch_array($result) will fetch all the values for 1st row in array format.
there must be one column in "quotables" table named "storedText" so that it is coming in the $row['storedText'].
you should refer php manual toi understand mysql_fetch_array and mysql_fetch_assoc functions..
refer this url : http://be.php.net/manual/en/book.pdo.php
Line 2 is relevant to a)
while ($row = mysql_fetch_assoc($rowcount))
the while-construct will repeat as long as the expression inside the parentheses evaluates to a true-ish value. In PHP; an assignment is also an expression, which evaluates to the value being assigned, i.e. $row. Before each iteration, the function is executed and tries to retrieve the next row from the database. When it fails, it will return false instead of a row, which then in turn make the loop end, because the assignment-expression will evaluate to false, which is the terminating condition for the while-statement.
b) line 9 -- where does "storedtext" come from? is it just made up on the spot?
It comes from a randomly fetched result from the database. It's the value of one column.
c) based on the code, do you have an idea what the database is supposed to look like. Would it just be a database called "text" with a table called "quotables" in it?
We only know that the database has at least two tables text and quotables, the latter of which has at least one column storedText.
What it does
It tries fetching a random quote. However, the logic is not sound and will most likely not work in all instances.
Why is it wrong?
Basically, it assumed that for each row in text, there is exactly one entry in quoteables. If that was so, you would not need two tables in the first place. Because of this, I assume that quoteables can contain any number of rows, possibly even less, in which case you would sometimes not get a single result from the query. This would have your query fail and your script, because you try to access "false["storedText"] so to speak.
A
$rowcount = mysql_query("select count() as rows from text");
// the $rowcount is an array, the lines below get the values (that actually is just one)
// and put into $max variable
while ($row = mysql_fetch_assoc($rowcount))
{
$max = $row["rows"];
}
B
//get the text from database based on randon limit offet
$result = mysql_query("select from quotables limit $rand, 1");
//put the value returned into $row variable
$row = mysql_fetch_array($result);
//get the storedText (that is a table column name), and put the value into $randomOutput
$randomOutput = $row['storedText'];
C:
Based on code I can't afirm what is the database model.

Categories