How do I count the number of rows in a MySQL Table? - php

I know that inside MySQL, you can use:
SELECT COUNT(*) FROM table
I have written the following code in PHP to display the number of rows on the page:
$sql = 'select * from users';
$data = $conn -> query($sql);
echo $data;
But when I run it, I get the following error:
Catchable fatal error: Object of class PDOStatement could not be converted to string in [Directory] on line 19.
I think the problem is that the returned value is not in string form. If that is correct, how would I be able to display the number of rows on the page?

If you want to count the rows you can do this with PDO:
$sql = 'select * from users';
$data = $conn->query($sql);
$rows = $data->fetchAll();
$num_rows = count($rows);

Well, you arent badly off, you are almost there:
$sql = 'SELECT COUNT(*) as numrow FROM users';
$data = $conn -> query($sql);
rows = $data->fetchAll();
Depending on the type of return data, you could use
$rows->numrow if the return data is an object

There are some easy and faster way to do this
COUNT the column in query and fetch
$sql = "SELECT COUNT(id) AS total_row FROM table_name";
$stmt = $conn->query($sql);
$stmt->execute();
echo $count['total_row'];
Using rowCount()
$sql = "SELECT * FROM table_name";
$stmt = $conn->query($sql);
$stmt->execute();
$count = $stmt->rowCount();
echo $count;

Related

PHP PDO - incremental for loop that fetches the next array row with each loop

I'm in the process of updating my old mysql database techniques to prepared pdo statements. I'm all good with while loops while($row = $result->fetch()) however how would I do the following with PDO prepared statements?
$sql = "SELECT * FROM table WHERE id=".$id;
$result = mysql_query($sql) or die(mysql_error());
$loop_count = mysql_num_rows($result);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = mysql_fetch_array($result);
echo $loop_row['field'];
}
I've tried this but with no joy:
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_count = $result->rowCount();
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = $result->fetch();
echo $loop_row['field'];
}
Thanks!
UPDATE: The reason for using a for loop instead of a while loop is the ability to paginate the results, otherwise I would just put LIMIT 7 on the end of the SQL query.
To properly count rows with PDO you have to do this -
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$rows = $result->fetch(PDO::FETCH_NUM);
echo $rows[0];
But you would be better off using LIMIT in your query if all you want to do is get a static number of results.
In addition you're making your loop overly complex, there is no need to test for a range in the for condition just set the static number unless you're doing something weird, like possibly pagination.
You can try it this way:
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_rows = $result->fetchAll();
$loop_count = count($loop_rows);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
echo $loop_rows[$row]['field'];
}
As requested by the OP, here's an example of PDO prepared statements using LIMIT and OFFSET for pagination purposes. Please note i prefer to use bindValue() rather than passing parameters to execute(), but this is personal preference.
$pagesize = 7; //put this into a configuration file
$pagenumber = 3; // NOTE: ZERO BASED. First page is nr. 0.
//You get this from the $_REQUEST (aka: GET or POST)
$result = $conn->prepare("SELECT *
FROM table
WHERE id= :id
LIMIT :pagesize
OFFSET :offset");
$result->bindValue(':id', $id);
$result->bindValue(':pagesize', $pagesize);
$result->bindValue(':offset', $pagesize * $pagenumber);
$result->execute();
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
This gives you the complete resultset of rows, limited to your required page. You need another query to calculate the total number of rows, of course.
What you could try is:
//Get your page number for example 2
$pagenum = 2;
//Calculate the offset
$offset = 7 * $pagenum;
//Create array
$data = array();
$result = $conn->prepare("SELECT * FROM table WHERE id= ? LIMIT 7 OFFSET ?");
$result->bind_param("ii", $id,$offset);
$result->execute();
$resultSet = $result->get_result();
while ($item = $resultSet->fetch_assoc())
{
$data[] = $item;
}
$result->close();
//echo resultSet you want
var_dump($data);

PDO equivalent of mysql_num_rows

I want to be able to translate the mysql code below into PDO equivalent. Please can someone help me out as I have looked around and tried other examples but they are not working for me.
// Count Participants
$result = mysql_query("SELECT * FROM table2");
$num_rows = mysql_num_rows($result);
You can either just issue a count query to the DB
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$count = $db->query('SELECT count(*) FROM table2')->fetchColumn();
or get an array back that can be counted
$stmt = $db->query('SELECT * FROM table2');
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = count( $rows );
or get any kind of other resultset back, and count that etc.

Count rows in mysql with php when have specific string

I have a table in my database named visitor_table . Within table i have a column named visitor_affiliate. I want to get the count of the rows when visitor_affiliate = "someurer" .
I want to get the count as number. I already have this code but i don't know how to get the count only for the rows containing the string. I currently get the number of all rows,
$result = mysql_query("SELECT * FROM visitor_table");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
You can ask MySQL to return the count:
SELECT COUNT(*) FROM visitor_table WHERE visitor_affiliate = 'someurer'
You shouldn't be using the ancient (deprecated as of PHP v5.5.0, soon to be removed entirely) MySQL extension for writing new codeā€”use instead the improved MySQLi extension or the PDO abstraction layer, both of which enable you to pass variables to the database in a safe, parameterised, fashion that ensures they are not evaluated for SQL (and therefore prevents SQL injection attacks):
$dbh = new PDO("mysql:dbname=$dbname", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$qry = $dbh->prepare('
SELECT COUNT(*) FROM visitor_table WHERE visitor_affiliate = ?
');
$qry->execute(['someurer']);
echo $qry->fetchColumn(), ' rows';
$result = mysql_query("SELECT * FROM visitor_table WHERE `visitor_affiliate` = 'someurer'");
$num_rows = mysql_num_rows($result);
echo $num_rows . " Rows\n";
With what little information you have given just try this-
$result = mysql_query("SELECT * FROM visitor_table Where visitor_affiliate like '%someurer%'");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
The deprecated MySQL:
$res = mysql_query('SELECT * FROM visitor_table');
echo 'Number of rows:'.mysql_num_rows($res);
Procedural MySQLi:
$tu = mysqli_prepare($DBH,'SELECT * FROM visitor_table');
mysqli_execute($tu);
$num_rows = mysqli_num_rows($tu);
echo $num_rows.' rows\n';
mysql has been deprecated. Please use mysqli.
Using MySQLi bind_param to get your result:
$someuser = 'Dave';
$DBH = mysqli_connect('localhost','user','pass','database');
$query = mysqli_prepare($DBH,'SELECT * FROM visitor_table WHERE user = ?');
mysqli_bind_param($query,'s',$someuser);
mysqli_execute($query);
mysqli_bind_result($id,$user,$tabCol1,$tabCol2);
while(mysqli_fetch_result){
$row = $row +1;
echo $user.': was found in the record with ID of: '.$id;
}
echo 'total records found:'.$row;
That's one way of doing it as I'm not completely 100% sure about using a mysqli_num_row() with the query above.

inner join query in joomla

I want to fire one complex query in my joomla site. I have written below code for it.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('`chr`.`characteristic_id`,`chr`.`characteristic_value`,`prc`.`price_value`');
$query->from('`#___hikashop_product` AS `pdt`');
$query->join('inner', '`#__hikashop_variant` AS `vari` ON `pdt`.`product_id` = `vari`.`variant_characteristic_id`');
$query->join('inner', '`#__hikashop_characteristic` AS `chr` ON `vari`.`variant_characteristic_id` = `chr`.`characteristic_id`');
$query->join('inner', '`#__hikashop_price` AS `prc` ON `pdt`.`product_id` = `prc`.`price_product_id`');
$query->where('`pdt`.`product_id` = 68');
$db->setQuery($query);
Query is executing in my local mysql.
any help will be appreciated
You can try this
$db->setQuery("Your query");
$result = $db->query();
//if you need the count
$rowcount = $db->getNumRows();
//if the result is multiple rows
$result_array = $db->loadAssocList() or $db->loadObjectList();
//if the result is single row you can use
$result = $db->loadAssoc() or $db->loadObject();
To fire the query, all you need to do is:
$rows = $db->loadAssocList(); // or loadObjectList()
The above will put all of the rows into $rows
You can also fire the query without grabbing the rows with:
$db->query();

Using php to access mysql, how can I get the query result which is only a number?

For example, for some queries like SELECT MAX(field), the query result is usually only a field value, rather than returning rows to you.
Now the field of the value I wanna get is integer type.
As I'm a beginner of php, how can I get that value from the query result?
As I do the following
$query = "SELECT MAX(stringid) FROM XMLString";
$result = mysql_query($query, $link);
echo $result;
Then nothing is echoed out.
I have check the db connection made by mysqlconnect, and it's got no problem.
And I tried this query in MySQL at phpMyAdmin, then the query is what I want, too?
So why would it be like that, and any solution?
Thanks!
You will always retrieve rows back from an SQL query, even if there's only one row with one field. You can directly retrieve a specific field of a specific row using mysql_result:
$query = "SELECT MAX(stringid) FROM XMLString";
$result = mysql_query($query, $link);
echo mysql_result($result, 0, 0);
$query = "SELECT MAX(stringid) as val FROM XMLString";
$result = mysql_query($query, $link);
$rows = mysql_num_rows($result);
if($rows > 0) {
$rstAry = mysql_fetch_array($result);
echo $rstAry['val'];
}
Try This
mysql_query is not printing results. Maybe try this:
echo mysql_result($result);
You are not getting any result because mysql_query returns a database object.
You will need to process this "database object" using mysql_fetch_array. This command 'fetches' an array out of a MySQL "database object". The array you are fetching is the rows your query produced. In your case, it is just one row.
Here is the code:
This step sets your query:
$query = "SELECT MAX(stringid) as val FROM XMLString";
This step will run your query, and return the database object:
$result_database_object_whatever = mysql_query($query, $link);
This step will process the database object, and give you an array of the queried rows:
$result_array = mysql_fetch_array($query, $link);
This step will echo the first row returned by your query:
echo $result_array[1];
You can do something like this:
$query = "SELECT MAX(stringid) FROM XMLString";
$result = mysql_query($query, $link);
$fetch = mysql_fetch_assoc($result);
echo $fetch['stringid'];
The mysql_fetch_assoc() function retrieves the data in an associative array.
Would it help to give the max a name you could reference? Also ifyou think there's syntax errors you could just add the error to help clarify.
$query = "SELECT MAX(stringid) as maxNum FROM XMLString";
$result = mysql_query($query, $link) or die(mysql_error());
echo $result;

Categories