PHP Count Arrays from MySQL counts Incorrectly - php

I am having trouble correctly counting elements within the array that I pulled from my database. Please see my code below:
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
//NEW QUERY TO OUR DATABASE
$query = $conn -> query("Select distinct Race from Races");
while($race[] = $query->fetch_object());
//Check how many elements are within our query
$racecount = count($race);
echo "<br>" . $racecount . "<br><br>";
$racecount = count($race,COUNT_RECURSIVE);
echo "<br>" . $racecount . "<br><br>";
var_dump($race);
echo "<br><br><br>";
Using both type count() in both ways yields the same result of "4". However, please see the result from my var_dump.
array(4) { [0]=> object(stdClass)#3 (1) { ["Race"]=> string(5) "Human" } [1]=> object(stdClass)#4 (1) { ["Race"]=> string(7) "Vampire" } [2]=> object(stdClass)#5 (1) { ["Race"]=> string(5) "Demon" } [3]=> NULL }
Var_dump shows that it is an array with 4 elements within it. So count was correct, it's just not giving me the number that I'm looking for.
Thus, I have three questions.
1) How do I count my elements correctly?
2) Could someone explain to me why this reads as 4 elements?
3) Is my array not multi-dimensional? (since both counts yield the same result of 4)
Best Regards and Thanks in advance,
Josh

`while($race[] = $query->fetch_object());`
$query->fetch_object() returns a null to indicate that there are no more entries in the dataset, but you're still assigning that null value to your $race array as a last entry, and only then allowing the while to terminate its loop.... that's why you have 4 entries in the array rather than 3.
Your array is not multidimensional, because the entities stored in the $races array are objects, not arrays; it would only be multi-dimensional if it was an array of arrays

The reason is actually pretty straight forward. When inserting data into your array using while($race[] = $query->fetch_object()) you always insert the final $query->fetch_object() which is gonna be equal to null. That is when you exit your while loop. Thus, your array's last item will always be null, just like in your own var_dump.
One way to fix this would simply to subtract 1 from your result. Another way would be to implement inserting like this:
$race = [];
while($row = $query->fetch_object()) {
array_push($race , $row);
}
The best way to count however would be by simply executing an SQL COUNT command:
$query = $conn->query("SELECT COUNT(DISTINCT Race) FROM Races");

Your php count is returning the amount of fields on your result object, not the amount of rows.
Try this for your SQL query:
$query = $conn->query("SELECT COUNT(DISTINCT Race) FROM Races");
Should you wish to use the same query as you have now, try:
$raceCount = $query->num_rows;

Related

Unexpected result, I obtain always 0 in row[2]. Why?

row[0] return giocatore’s field value
row1 return avversario’s field value
row[2] should return the values of “coins” field but it returns everytime value=0, WHY?
Here it is an image of the table, the fields and the values that row[2] is missing
Everytime I call the function coins() in a php script that I created, it always returns me the third value of the row array with value 0 (so row[2] always = 0) but when I check the value of it on php-MyAdmin using the same SQL instruction I obtain the correct values (different by 0). So why PHP is not using the right value with row[2]. The values of row[0] and row1 are always correct in php-MyAdmin and in the script results.
This is the SQL statement I created and it seems to work fine on php-MyAdmin:SELECT `giocatore`, `avversario`, `coins` FROM `tiri_dadi_table2` WHERE `contatore`= (SELECT MAX(`contatore`) FROM `tiri_dadi_table2`)
The database name: is tiri_dadi_db
The Table name is: tiri_dadi_table2
Columns names are: 'contatore' int(11), 'giocatore' int(11), 'avversario' int(11), coins int(11)
In php, as a result of the row[2] always equal to 0 I have always DB_coins = 0 at the beginning of the function in my script, so it's increased or decreased and then return to be 0 everytime.
It seems to be a scope problem but I'm not able to solve it at the moment.
Thank you in advance for your help.
(sorry for my bad english, I'm working on it! :)
function coins() {
/* Connect to the database */
$conn = new mysqli('localhost','root', '');
// Check connection
if ($conn->connect_error)
{
die("<br>Connessione fallita: " . $conn->connect_error);
}
//echo "<br>DB connesso con successo.<br>";
// Select database
mysqli_select_db($conn,"tiri_dadi_db");
// sql READING values
$sql = "SELECT `giocatore`, `avversario`, `coins` FROM `tiri_dadi_table2` WHERE `contatore`= (SELECT MAX(`contatore`) FROM `tiri_dadi_table2`)";
// on php-MyAdmin this SQL statement return me 3 correct values but here in the script, on the row[2] value there is always 0. Why??? Is a static problem or what?
if ($result = mysqli_query($conn, $sql)) {
// Fetch one and one row
while ($row = mysqli_fetch_row($result)) {
$last_roll_R = $row[0];
$last_roll_B = $row[1];
$DB_coins = $row[2]; // ...... but this is 0 everytime even though in SQL give me the correct value...
var_dump($row); // The var_dump($row) return me something like this:
// array(3) { [0]=> string(1) "2" [1]=> string(1) "4" [2]=> string(1) "0" }
}
// free memory
mysqli_free_result($result);
}
// close connection
mysqli_close($conn);
...
}

mysql query looped with results stored in an array

I have a shipping module I'm working to wrap up and am trying to query a mysql table, count the number of rows for a given line item on a PO, and store that result in an array. I don't think I can do group by within mysql as it will not provide a result for a line item that hasn't had any shipments against it. The intent is to take the original order quantity, count the number of units shipped against that via my query, and then subtract the units shipped from the original amount providing the remaining units to be shipped against that line item.
To ensure I receive even the zero qty for line items without shipments and to store that in the array I am trying to loop my query and store each single result as a value within my array. I'm open to suggestions on changing the approach if there is a better way.
Here is what I have for my query:
// I have a previous query that provides the number of line items for a given po. that number is stored in variable $num1
$a=1;
$LiShipped = array();
while($a<$num1){
$query2="SELECT count(E3_SN) AS SCount FROM Shipped WHERE Cust_Ord_Num = '$SO_Num' AND LineItem=$a";
$LiShipped[] = mysql_fetch_array($query2);
$a++;
}
Unfortunately when I go to iterate through my array it appears as though nothing is stored in the array.
<?php
echo $LiShipped[0]; //results nothing
echo var_dump($LiShipped); // results array(1) { [0]=> NULL } array(2) { [0]=> NULL [1]=> NULL } array(3) { [0]=> NULL [1]=> NULL [2]=> NULL }
?>
Looks like all null values.
You need to execute the query (by calling mysql_query()) before you try and attempt to retrieve the result:
$query2="SELECT count(E3_SN) AS SCount FROM Shipped WHERE Cust_Ord_Num = '$SO_Num' AND LineItem=$a";
$query2 = mysql_query( $query_2); // <-- NEED THIS
$LiShipped[] = mysql_fetch_array( $query2);
Note the above omits basic error checking and sanitation of the SQL query to prevent SQL injection.
You are not executing your query, it can't work. Try this code:
// I have a previous query that provides the number of line items for a given po. that number is stored in variable $num1
$a=1;
$LiShipped = array();
while($a<$num1){
$query2="SELECT count(E3_SN) AS SCount FROM Shipped WHERE Cust_Ord_Num = '$SO_Num' AND LineItem=$a";
$res = mysql_query($query2);
while($LiShipped[] = mysql_fetch_array($res));
$a++;
}

php implode function not working on concatenated variables

I have multiple arrays which I am passing to a file sales_process.php on the form submit action. The arrays are named like this : boards1 = {a , b , c}, boards2 = {b , c , d}, boards3 = {a , c , d} . . and so on (The values are not a,b,c,d). I am passing them through multiple 'multiple select boxes' in my form like this where a,b,c,d are my multiple select options :
for ($count=1;$count<10;$count++)
echo "<td>"."<select name='boards".$count."[]' multiple='multiple'>".showOptionsDrop($boards,$arr)."</select></td>";
Now when i pass them to the file sales_process.php, i want to convert these arrays into strings using implode function so that i can store them into my 'schools' table. In sales_process.php file, I am doing this:
for ($i=0;$i<$count;$i++) {
$board = implode(',',${'boards'.$i});
$query = "UPDATE schools SET board = '$board' where schoolcode = (some_no)";
$result = mysql_query($query) or die("Error in updating table :".mysql_error());
}
So in this way, every time my loop runs, the values of boardsX gets converted into string and gets stored in the table, where X is 1,2,3.... and so on.
The problem is the implode function is not working and giving error :
Warning: implode() [function.implode]: Invalid arguments passed in C:\xampp\htdocs\relationshipReport\sales_process.php on line 18
Now if you say that the variable ${'boards'.$i} is not an array, i did this and found out that its giving me an array only :
$i=1;
var_dump(${'boards'.$i});
print_r(${'boards'.$i});
which gives the output as :
array(3) { [0]=> string(4) "CBSE" [1]=> string(4) "ICSE" [2]=> string(5) "IGCSE" }
Array ( [0] => CBSE [1] => ICSE [2] => IGCSE )
I hope my question is clear. Please help me in finding out whats going wrong in the implode function. If you don't understand the question, please mention it.
From your examples, I believe this is your current code:
for ($i=0;$i<$count;$i++) {
$board = implode(',',${'boards'.$i});
$query = "UPDATE schools SET board = '$board' where schoolcode = (some_no)";
$result = mysql_query($query) or die("Error in updating table :".mysql_error());
}
If so, try altering it so it looks like this:
for ($i=0;$i<$count;$i++) {
if(isset($_POST['boards'.$i]))
{
$board = mysql_real_escape_string(implode(',',$_POST['boards'.$i]));
$query = "UPDATE schools SET board = '$board' where schoolcode = (some_no)";
$result = mysql_query($query) or die("Error in updating table :".mysql_error());
}
else
{
echo '$_POST[\'boards' . $i . '\'] doesn\'t exist or is null.<br>';
}
}
This contains an if condition, checking that the array entry actually exists. If it does exist, it runs the query. If it doesn't, it echos back a message, telling you which one doesn't exist.
Even if you have confirmed at the frontend with Javascript, you should always check before running code, just to be sure it won't break it. You can never be too safe, especially if your code contains sensitive information.
Try this, and let me know how you go.
Assume ${'boards'.$i} comes from $_POST['boards'.$i]. (If not, you are using register_globals, but that is not good.)
For multiple select, if no options is selected, then $_POST['boards'.$i] will give you null instead of an array.

Retrieving a JOIN array from MySql

I'm pulling a joined query from the DB using the following code:
$query = 'SELECT `profiles`.`city`, `users`.`first_name`, `users`.`last_name`'
. ' FROM profiles, users'
. ' WHERE ((`profiles`.`user_id` = 3) AND (`users`.`user_id` = 3))'
. ' LIMIT 1';
$result = $connection -> query($query);
$arr = $result -> fetch_array();
$feedback = $arr;
$result -> close();
return $feedback;
This isn't my final code, this is just preliminary to test my join.
The query seems to work fine, it pulls the single row of information I need but I noticed that when I var_dump it, it's put the array into 2 different indexes, a numerical index and an index of the name of the db field. Here's what the var_dump looks like:
array(6) { [0]=> string(4) "Reno" ["city"]=> string(4) "Reno" [1]=> string(4) "John" ["first_name"]=> string(4) "John" [2]=> string(3) "Doe" ["last_name"]=> string(3) "Doe" }
This is effectively doubling the size of my query result. For a single row this won't be that big of a deal but if/when I begin to use this same method to draw multiple records, doubling the size of the result can be costly.
I've tried to do a foreach loop:
foreach ($arr as $key=>$value) {
$feedback[$key] = $value;
}
but it leaves me with the same result. Am I doing something wrong and if so, how do I correct it or is this normal?
Thanks for you help
The default result type for mysqli_result::fetch_array() is MYSQLI_BOTH meaning you get both named and numeric result array indices (see http://php.net/manual/en/mysqli-result.fetch-array.php).
Try using fetch_assoc() instead.
To reduce the size, you'll want to look at the second optional argument to mysql_fetch_array. This is documented here:
http://www.php.net/manual/en/function.mysql-fetch-array.php
You can specify if you just want numerical-indexes or associative arrays.
If you use fetch row (http://www.php.net/manual/en/mysqli-result.fetch-row.php) you will fetch without the names. I think this is what you are looking for, right?
EDIT: This also apllied to mysql, but the function is mysql_fetch_row($result) instead of mysqli

MySQLi query stops at first item in a column when I need all items

I want to get all the image_name values from one of my tables where the category and account_id match.
The query joins 3 tables.
I am using mysqli.
SELECT image_name
FROM add_images, item, user_item
WHERE user_item.account_id = '$accountId' AND item.category = '$category';
However when this query executes and var_dump() the result, I find only the first record? there should be 8 items?
I have confirmed this by returning count() on the array which returned 1.
If I run this query in phpmyadmin the query runs successfully and it finds all 8 items, however they are repeated 8 times, not sure what that is about?
I have replaced image_name with * also I have tried image_name.* and image_name* all fail in my code and in phpmyadmin.
When I dump out the object I get:
object(mysqli_result)#3 (5) { ["current_field"]=> int(0) ["field_count"]=> int(1) ["lengths"]=> NULL ["num_rows"]=> int(512) ["type"]=> int(0) } int(1) string(29)
I have also tried the following suggested in:
How get all values in a column using PHP?
while($row = mysqli_fetch_array($result,MYSQL_ASSOC))
but the suggested code also fails.
Below is my code:
public function searchItems($accountId, $catagory,$userId){
$imagePath = "D:\imagesdb\images\\" . $userId;
$thumb_path = $imagePath . "t\\";
$conn = $this->create_connection('read');
$sql = "SELECT image_name FROM add_images, item, user_item WHERE user_item.account_id='$accountId' AND item.catagory='$catagory'";
$result = $conn->query($sql)or die(mysql_error());
var_dump($result);
while ($row = mysqli_fetch_array($result)){
$path = $thumb_path . $row['image_name'];
$result = count($path);
var_dump($result);
return $path;
}
$conn->close();
}
I have also tried a prepared statement I have the same issue which I expected!
Does anyone have any suggestions please? This has been driving me mad!
You are returning $path unconditionally in the while-loop. So the function returns after it has fetched one row. This is probably not what you intended.
You probably want to create an array, add all image paths to that and return the array at the end of the function.

Categories