how to get the number of rows of mysql db with php - php

i would like to get the number of rows of a mysql database table with one single statement or a function
include "opendatabase.php"; //opens database
while (NUMBEROFROWS > 0){
//do something
}
the NUMBEROFROWS should be replaced with the statement that returns the number of rows
i already tried to create a function
function getRowNumber(){
$query = "SELECT COUNT(*) FROM `votes`";
$result = mysql_query($query, $connect);
list($length) = mysql_fetch_row($result);
return $length;
}
but it does not work if i dont put the include "opendatabase.php"; in it.
what am i doing wrong

$result = mysql_query("SELECT * FROM tablename");
if (mysql_num_rows($result) > 0) {
// rows found..
}

the problem is that include "opendatabase.php"; runs in another scope like described here
http://www.php.net/manual/en/language.variables.scope.php
there is a global $connect missing within the function

Here you go:
function num(){
$data = mysql_query("SELECT * FROM table");
if(mysql_num_rows($data) > 0){
while($row = mysql_fetch_assoc($data)){
// do something with your data..
}
}
}

would this work for you ?
function getRowNumber()
{
$query = "SELECT COUNT(*) as counts FROM `votes`";
$result = mysql_query($query, $connect);
$row = mysql_fetch_array($result);
$counts = $row['counts'];
return $counts;
}

Related

How to get total number of row by using this function php mysql?

How to get total number of row by using this function php mysql ?
i use this code for display data from mysql. It's work good,
Buy i want to know can i get total number of row by using this code ?
<?PHP
include("connect.php");
$query = "SELECT * FROM table";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
}
?>
Try this mysql_num_rows ($result)
Use this line of code
<?PHP
include("connect.php");
$query = "SELECT * FROM table";
$result = mysql_query($query) or die(mysql_error());
$number_of_rows = mysql_num_rows($result); // this will return the number of rows found by the $result query.
echo $number_of_rows;
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
}
?>

Get all values in column MySQL and count PHP

I try to create a function that will get all values (int) in specific column in my database (MySQL), and create the total of all values. I have an error: Resource id #12
This is my function:
function vuesCours() {
$con = mysql_connect("localhost","root","root");
mysql_select_db("myDataBase", $con);
$result = mysql_query("SELECT SUM(views) FROM articles");
return $result;
}
And this my declaration:
<h4><?php echo vuesCours(); ?></h4>
Thank you in advance for your response.
This is not error just you have to do one thing more after query, so try to replace following code and try again.
function vuesCours() {
$con = mysql_connect("localhost","root","root");
mysql_select_db("myDataBase", $con);
$result = mysql_query("SELECT SUM(views) as total FROM articles");
$row = mysql_fetch_array($result);
return $row['total'];
}
It may help you.
you need to return not results but the value of row. something like this:
function vuesCours() {
$con = mysql_connect("localhost","root","root");
mysql_select_db("myDataBase", $con);
$result = mysql_query("SELECT SUM(views) as total FROM articles");
$row = mysql_fetch_array($result)
return $row['total'];
}
hope this helps.
$con = mysql_connect("localhost","root","root");
mysql_select_db("myDataBase", $con);
$result = mysql_query("SELECT views FROM articles");
$sum=0;
while($row=(mysql_fetch_row($result)))
{
$sum=$sum+$row['views'];
}
echo $sum;
1) i have just changed the select query
2)we have result set of query in $result
3)mysql_fetch_row will return result row as an enumerated array
from which you can access
particular column by it's name or by giving id into subscript brackets in a line $sum=$sum+$row[index/name of column];

Fetch array returns only one row

<?php
function comment($postid,$db_con)
{
$commentdiv='';
$sql="SELECT userid,time,comment FROM comments WHERE postid='$postid' LIMIT 3";
$query = mysqli_query($db_con, $sql);
while($row = mysqli_fetch_array($query,MYSQLI_ASSOC)){
$uid=$row["userid"];
$timecomment=$row["time"];
$comment=$row["comment"];
$sql="SELECT username,photo FROM users WHERE id='$uid'";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_array($query,MYSQLI_ASSOC);
$username=$row["username"];
$photo=$row["photo"];
$userphoto='<img src="xxx/'.$username.'/'.$photo.'">';
if($photo== NULL){
$userphoto = '<img src="xxx/default.png">';
}
$commentdiv.='<div class="xxxxxxx"><div class="yyyyyy">'.$userphoto.'</div><div class="zzzzz">'.$username.'</div><div class="vvvvv">'.$comment.'</div></div>';
}
return $commentdiv;
}
?>
I am new to PHP, I am trying to return 3 comments from above PHP code, but above code returns only 1 row from database, why does fetch array return only 1 row when there is more then 1 row?
Try,I use $query2 = mysqli_query($db_conx, $sql); for your second query,Because it will reset first loop
<?php
function comment($postid,$db_con)
{
$commentdiv='';
$sql="SELECT userid,time,comment FROM comments WHERE postid='$postid' LIMIT 3";
$query = mysqli_query($db_con, $sql);
while($row = mysqli_fetch_array($query,MYSQLI_ASSOC)){
$uid=$row["userid"];
$timecomment=$row["time"];
$comment=$row["comment"];
$sql="SELECT username,photo FROM users WHERE id='$uid'";
$query2 = mysqli_query($db_conx, $sql); // added new variable
$row = mysqli_fetch_array($query2,MYSQLI_ASSOC);
$username=$row["username"];
$photo=$row["photo"];
$userphoto='<img src="xxx/'.$username.'/'.$photo.'">';
if($photo== NULL){
$userphoto = '<img src="xxx/default.png">';
}
$commentdiv.='<div class="xxxxxxx"><div class="yyyyyy">'.$userphoto.'</div><div class="zzzzz">'.$username.'</div><div class="vvvvv">'.$comment.'</div></div>';
}
return $commentdiv;
}
?>
You are overwriting the mysql resource variable that gives the result inside the while loop.
while($row = mysqli_fetch_array($query,MYSQLI_ASSOC)){
^^^^^^ Original resource variable
and inside the while loop again you are using the query variable
$query = mysqli_query($db_conx, $sql);
^^^^^^ Overwriting $query inside the while loop
One suggestion would be to rename the variable inside the loop to something else.

PHP MYSQLI two queries in a page

I have two php files. They each have a different query in them. Both of them work. Then I have one file where I include both files inside of it. The queries work on their individual pages, but in the page where they are both included only the first query works. They look something like this (The first one uses * because I pull out every row)
include 'connect.php';
$query = "SELECT * FROM table ORDER by jid DESC";
$ex = $mysqli->query($query) or die(mysqli_error());
$row_cnt = mysqli_num_rows($ex);
if ($row_cnt > 0) {
/* fetch associative array */
while ($row = $ex->fetch_assoc()) {
echo $row["one"] . $row["two"] . $row["three"] . $row["four"];
}
$result->free();
}
$mysqli->close($mysqli);
The second one is like this
include 'connect.php';
$q = "SELECT one, three FROM table ORDER by jid DESC";
$d = $mysqli->query($q) or die(mysqli_error());
$row_cnt = mysqli_num_rows($d);
if ($row_cnt > 0) {
/* fetch associative array */
while ($row = $d->fetch_assoc()) {
echo $row["one"] . $row["three"];
}
$result->free();
}
$mysqli->close($mysqli);
Then the file that includes them is just two includes like include ' ';
How do I get both queries to work on the one page?
add value in array, like this:
include 'connect.php';
$q = "SELECT one, three FROM jokes ORDER by jid DESC";
$d = $mysqli->query($q) or die(mysqli_error());
$row_cnt = mysqli_num_rows($d);
$values = array();
if ($row_cnt > 0) {
/* fetch associative array */
while ($row = $d->fetch_assoc()) {
$values[0][] = $row["one"];
$values[1][] = $row["two"];
$values[2][] = $row["three"];
$values[3][] = $row["four"];
}
$result->free();
}
$mysqli->close($mysqli);
... after, use foreach for print the value
I have not tested
How do I get both queries to work on the one page?
Just run them one after another like everyone does.
If something goes wrong - debug your code, like everyone does. Read all the error messages and act accordingly.

How to query a database with an array outside a loop

Hie. I am trying not to place an SQL query inside a loop, since this improves performance. I think I am supposed to use implode. But can't figure out how to do it. Here is my code:
<?php
//FUNCTION CONNECTNG TO DB HERE
function turn_result_to_array($result)
{
$result_array = array();
for ($count=0; $row = mysql_fetch_array($result); $count++)
{
$result_array[$count] = $row;
}
return $result_array;
}
function get_sender_username()
{
//connect to DB
$query = sprintf("SELECT DISTINCT sender FROM direct_messages
WHERE receiver_username='%s'
ORDER BY direct_messages.id DESC",
mysql_real_escape_string($_COOKIE['username']));
$result = mysql_query($query);
$result = turn_result_to_array($result);
return $result;
}
$senders = get_sender_username();
foreach($senders as $sender)
{ //SELECT IMAGE(S) FROM USER TABLE WHERE USERNAME = $SENDERS }
Instead of putting the query inside the FOREACH, i want to put it after, so i don't make multiple round trips to the database. FYI i already know that we supposed to switch to PDO. Thanks in advance.
Here is one way of doing it:
$senderInString = implode("','",$senders);
$senderInString = "('$senderInString')";
$newQuery = "SELECT something FROM tables WHERE sender in $senderInString;"
$newResult = mysql_query($newQuery);
Use
$query= "SELECT IMAGE(S) FROM USER TABLE WHERE USERNAME IN (".implode(',',$senders).")";
$result = mysql_query($query);
In the place of foreach

Categories