I have a problem with getting the right value after I counted the rows from a table. I searched on the web but didn't find an answer.
In the database i have a table with all the categories in it they all have an id, and i would like to count using this column.
I have this PHP code, it works but is there an other and better to get over this?
$sql2 = "SELECT COUNT(id) FROM categories";
$stmt2 = sqlsrv_query($conn, $sql2);
$res = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC);
foreach($res as $row)
{
$rows = $row;
}
//if there are categories display them otherwise don't
if ($rows > 0)
{
$sql = "SELECT * FROM categories";
$stmt = sqlsrv_query($conn, $sql);
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo "<a href='#' class='cat_links'>" . $row['category_name'] . " - <font size='-1'>" . $row['category_description'] . "</font></a>";
}
}
else
{
echo "<p style='text-align: center'>No categories yet.</p>";
}
I think has to be a better way to convert the $stmt2 variable from a SQL resource to an actual number, or to convert the $res variable from an array to an number. If I try to echo the whole array using foreach, it will only print out the number of rows. This is why I use it to count the rows now.
I can't use the sqlsrv_num_rows function because I then get an error, or no answer.
Related
I'm trying to count the rows which are not NULL inside a table when exucting the query inside Phpmyadmin it gives me the right output.
SELECT COUNT(`column_name`) FROM `Table_name`
but when I'm trying to execute it inside Php it always returns one I tried 2 methods both returning one for some reasons any ideas ?
method 1
$query = "SELECT COUNT(`column_name`) FROM `Table_name`";
if ($result = $mysqli->query($query)) {
$field1name = $rowcount=mysqli_num_rows($result);
echo '<tr>
<td>English</td>
<td>'.$field1name.'</td>
</tr>';
$result->free();
}
method 2
$query = "SELECT COUNT(`column_name`) FROM `Table_name`";
if ($result = $mysqli->query($query)) {
while ($rowcount = $result->fetch_assoc()) {
$field1name = $rowcount=mysqli_num_rows($result);
echo '<tr>
<td>Bahdini</td>
<td>'.$field1name.'</td>
</tr>';
}
$result->free();
}
The SELECT COUNT Query returns a resultset of 1 row, in that row you get the number of rows: 10228 as you stated.
the function mysqli_num_rows returns the number of rows in the RESULTSET, that's why it returns 1.
You have several assigment in a row .. which is your expected result ??
$field1name = $rowcount =mysqli_num_rows($result);
Instaed You should use a proper column alias for your count and then query, fecth, loop over the result and show
$query = "SELECT COUNT(`column_name`) my_count FROM `Table_name`";
$result = mysqli_query($conn, $query );
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row["my_count"]. "<br>";
}
} else {
echo "0 results";
}
I am trying to display some values from a database, and having some issues displaying the correct info.
In my database, there is a column called coplevel that column has enum values upto 7.
In my PHP side of things, I am trying to count all the user's in the database who have a coplevel > 0 but the thing's I have tried on SOF, work but not how I want it to work.
So if I have 5 user's with a cop level of 1,2,3,4,5 I want to count only the users who're coplevel is more than 0
<?php
$sql = "SELECT COUNT(*) FROM `players` WHERE `coplevel` > 0";
if ($result = mysqli_query($link, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$totalc = $row['0'];
echo "<b>" . $totalc . "</b>";
}
mysqli_free_result($result);
} else {
$totalc = "Couldn't find cop info";
}
} else {
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
?>
If there is 5 user's who all have a coplevel over 0, then count and display only the ones who have > 0 as their coplevel
Your query is correct, but you are messing up with the $row array.
This:
while ($row = mysqli_fetch_array($result))
Will return the rows into an associative array called $row
An Associative array stores pairs of KEYS and VALUES
In this case, the key is the column name and the value is the data in the column.
You can access a value in the array either with its index in the array, or with its key name.
When you say :
$totalc = $row['0'];
You try to get the value of the array for which the key is named 0, but it doesn't exist
What you want to do, is getting the index 0. So you should say :
$totalc = $row[0];
A clearer alternative is to alias properly your COUNT(*) in the query, in order to have a proper name for its key in your array :
$sql = "SELECT COUNT(*) AS cnt FROM `players` WHERE `coplevel` > 0";
if ($result = mysqli_query($link, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$totalc = $row['cnt'];
It calculates, but starting from the second row.
<?php
include('connect-db.php');
$query = "select * from users";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$sold= array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sold=$row['contract']+$row['tva'];
echo "<table><tr><td>" . $sold. "</td></tr></table>";
}
?>
Your code has many issues:
Your code starts to calculate from the second row because of the line:
$row = mysql_fetch_array($result);
which obtains the first result from the opened recordset before the while loop.
$sold = array();Why is that an array?
If you want to sum to $sold, threat the variable as an integer and initialize it with a 0.
$sold = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
$sold += $row['contract']+$row['tva'];
echo "<table><tr><td>" . $sold. "</td></tr></table>";
It seems to me also that you may want to print the table only once. If this is true, consider to query the database with an aggregation function like SUM():
SELECT SUM(contract + iva) AS contractIva FROM users GROUP BY <some column in your table>;
The above allows to remove the while loop.
Since you already extracted a row from the result, with $row = mysql_fetch_array($result);, the script starts adding only with the next row. Th correct code would be:
<?php
include('connect-db.php');
$query = "select * from users";
$result = mysql_query($query);
$sold= array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sold=$row['contract']+$row['tva'];
echo "<table><tr>
<td>" . $sold. "</td>
</tr></table>";
}
?>
you can do that via query as well so that you don't need to perform calculation on the application level, database level can do this job for you.
select sum(col1+col2) as total from users
And you want one table instead of multiple tables I guess, if yes then do it like this:
echo "<table>
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sold=$row['contract']+$row['tva'];
echo <tr><td>" . $sold. "</td></tr>";
}
echo "</table>";
$sql = "SELECT title, article, filename, caption FROM articles
INNER JOIN images WHERE articles.image_id = images.image_id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
var_dump($row);
This only grabs the first row in the db when what I need is for it to grab all rows. How can I achieve this?
fetch_assoc() returns the next row of the result set with each call, so you need to call it in a loop like this:
while($row = $result->fetch_assoc()) {
var_dump($row);
}
The loop ends when $row = null (i.e. there's no more rows in the result set).
Please have a look at the Quick start guide, more specifically the Executing statements chapter. Right from that page:
$mysqli->real_query("SELECT id FROM test ORDER BY id ASC");
$res = $mysqli->use_result();
echo "Result set order...\n";
while ($row = $res->fetch_assoc()) {
echo " id = " . $row['id'] . "\n";
}
I feel like I'm missing something really simple here. Here's my sql query:
$getpages = "SELECT id FROM pages WHERE account = 2 ORDER BY page_order";
$showpages = #mysqli_query ($dbc, $getpages);
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
I then print the first result:
echo $row[0];
And get a correct value, the id of the first page (by page order):
10
So I submit a form which simply turns that $row[0] into $row[1].
And nothing prints. I don't understand.
You have to do this:
while ($row = mysqli_fetch_array($showpages, MYSQLI_NUM)) {
$id = $row[id];
// do something with the id
echo $id . "<br/>"; // Echo every id
}
This will iterate through all of the results
mysqli_fetch_array is a special function as each time you call it, it outputs the NEXT row.
So:
while ($row = mysqli_fetch_array(stuff)){
$var = $row['sql column'];
// In your case "$var = $row[0];" to get the id for the first row found.
}
is how you use it.
This will keep running the function until mysqli_fetch_array() eventually returns false. These each time it will output a new row. And the $row array is the array of one row in the sql table.
Use :
print_r($row);
in the while loop to see exactly what's being returned for use.
$getpages = "SELECT id FROM pages WHERE account = 2 ORDER BY page_order";
$showpages = #mysqli_query ($dbc, $getpages);
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
Question how many rows are fetched in this query in this case id, So MYSQL will result to 1 row affected, But since you are using
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
This code you used will not output anything try
$row[n] as n-1
$result->fetch_assoc() or mysqli_fetch_assoc($result)
catch one line at a time, from a mysqli_result:
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
source: http://www.w3schools.com/php/php_mysql_select.asp