count number of rows in table using php - php

I just want to count the number of rows in a table that already created in a database using php. I used mysqli(). I need the number of rows in the table as the output.

<?php
$mysqli = new mysqli("hostname", "dbusername", "dbpassword", "dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT count(*) cc FROM tablename")) {
/* fetch the first row as result */
$row = $result->fetch_assoc();
printf("Result set has %d rows.\n", $row['cc']);
/* close result set */
$result->close();
}
/* close connection */
$mysqli->close();
?>
In fact it's a common question you can find the answer anywhere.
Like, http://php.net/manual/en/mysqli-result.num-rows.php
You could separate this problem in to two
I wanna know how to connect to mysql.
I wanna know how to write that sql instruction.

<?php
$mysqli = new mysqli("hostname", "dbusername", "dbpassword", "dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT columnName from tablename")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
/* close result set */
$result->close();
}
/* close connection */
$mysqli->close();
?>
EDIT:
$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];

Try simple query like:
SELECT COUNT(*) AS count
FROM mytable

If you dont want to use COUNT in SQL, you can just select all rows (SELECT id FROM table) and then just use PHP count().

also you simply do this
"SELECT COUNT(*) AS `Rows`, `any column` FROM `tablename` GROUP BY `any column` ORDER BY `any column` "

mysqli_num_rows should do the trick if you want to count the rows in php.

Related

Warning: mysqli_query() expects at least 2 parameters, 1 given in D:\wamp64\www\magento\includes\functions.php on line 1579 [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I need a little help again... I get error mysql parameters, I know the problem but I cant find the missing parameters... this is the problem line
**`$result_template = mysqli_query($select_template) or die(mysql_error());`**
I know 1 parameter is missing but I dont know whichone?? Can you pls help me? Thanks
This is part of the codes maybe usefull....
/*function to display the active template*/
function displayTemplate(){
$tableprefix = "";
global $tableprefix,$_SESSION;
$template_array = array();
$select_template = "SELECT vtop_filename,vleft_filename,vbottom_filename,vimages_folder,vcss_name,vtemplate_name
FROM ".$tableprefix."template_master WHERE vactive_status = 'Y'";
1579---->>>> $result_template = mysqli_query($select_template) or die(mysql_error());
$template_row = mysql_fetch_assoc($result_template);
array_push($template_array,$template_row['vtop_filename'],$template_row['vleft_filename'],$template_row['vbottom_filename'],$template_row['vimages_folder'],$template_row['vcss_name'],$template_row['vtemplate_name']);
return $template_array;
}
You need to tell it where to connect to. Here is a simple example of working code to connect to a database from PHP.
<php
//Connect to DB
$conn = new mysqli("Hostname","Username","Password","Database");
//If the connection has errors
if ($conn->connect_error){
//Display the error
die("Connection failed because: " . $conn->connect_error);
}
//Otherwise the connection is good so lets create a sql query
$sql = "SELECT * FROM Database";
//Get the results of the query
$result = $conn->query($sql);
You should refer the php documentation for this here
As you are using the procedural style, so you will have to pass the mysqli_connect resource to your mysqli_query
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* Create table doesn't return a resultset */
if (mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
printf("Table myCity successfully created.\n");
}
/* Select queries return a resultset */
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* free result set */
mysqli_free_result($result);
}
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = mysqli_query($link, "SELECT * FROM City", MYSQLI_USE_RESULT)) {
/* Note, that we can't execute any functions which interact with the
server until result set was closed. All calls will return an
'out of sync' error */
if (!mysqli_query($link, "SET #a:='this will not work'")) {
printf("Error: %s\n", mysqli_error($link));
}
mysqli_free_result($result);
}
mysqli_close($link);
?>
but as I can see that you are using it in some function so pass an object of db to this function and then use it in your mysqli_query

PHP - mysqli_num_rows - Saying I only have 1 row when I have many rows

I am trying to display the number of rows in a table using mysqli_num_rows. When I print the results, it says I only have 1 row, when I really have several rows.
When I tested the SQL in phpMyAdmin, it counts the correct number of rows. But when I display the results on my web page, it counts only one row.
Please help me. What I am doing wrong?
$mysqli = new mysqli("localhost", "myusername", "mypass", "mydatabase");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT COUNT(*) FROM mytable")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
/* close result set */
$result->close();
}
/* close connection */
$mysqli->close();
The above codes prints the following, no matter how many rows I have:
Result set has 1 rows.
The result of a simple COUNT(*) statement is always one row. You want to fetch that row and get the value returned from the first column.
Actually when you use COUNT, the result of the query is the number of rows.
I usually try to write the sql query straight to phpmyadmin to see what happens. It would reveal the mistake ;)
<?php
$mysqli = new mysqli("localhost", "myusername", "mypass", "mydatabase");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql="SELECT * FROM mytable";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("Result set has %d rows.\n",$rowcount);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
Use mysqli_num_rows() method to fetch number of rows in the resultset.
Refer link http://php.net/manual/en/mysqli-result.num-rows.php
You could do like this if the database i small.
if ($result = $mysqli->query("SELECT * FROM mytable")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
/* close result set */
$result->close();
}
With i big database you could be doing like this as mentioned in the comments. I'm not so good with PDO or object oriented requests so this will be procedural.
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT COUNT(*) FROM users";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result)){
$row = mysqli_fetch_row($result);
printf("Result set has %d rows.\n", $row[0]);
}
mysqli_close($conn);

Mysql restrict on delete check

I have a mysql database with restrict on delete setting.
I have this delete query:
if(isset($_POST['delete_id']))
{
$sqldelete="DELETE FROM tblAcqDetail WHERE ID=".$_POST['delete_id'];
$resultdelete = $conn->query($sqldelete);
}
How can I check if the query does delete anything or is restricted by mysql.
I need to run an update query (see below) only if the delete query works.
I tried:
if ($resultdelete->affected_rows> 0) {
// Escape user inputs for security
$status = mysqli_real_escape_string($link, $_POST['status']);
if(isset($_POST['status']))
{
$setsql="UPDATE tblInvoiceDetail SET TRANSFER = '0' WHERE ID='$status'";
$setresult = $conn->query($setsql);
}
}
I also tried
if ($resultdelete->num_rows > 0) {
And also :
if ($resultdelete) {
All of the above stop the update query from executing.
You can use mysqli_affected_rows().
From the docs:
Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query.
Note this is run on the connection object, not the result. So use $conn->affected_rows instead of $resultdelete->affected_rows.
Rather than passing $resultdelete in to mysqli_affected_rows you actually want to pass the DB link (returned by mysqli_connect) which will give you the number of rows affected by the previous query
$sqldelete="DELETE FROM tblAcqDetail WHERE ID=".$_POST['delete_id'];
$resultdelete = $conn->query($sqldelete);
if ($conn->affected_rows > 0) {// pass db link here
Read http://php.net/manual/en/mysqli.affected-rows.php
Your problem is you're referencing the wrong thing
if ($resultdelete->affected_rows> 0) {
But
$resultdelete = $conn->query($sqldelete);
only returns a boolean(emphasis mine).
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE
You want to reference the connection itself for how many rows were affected
if ($conn->affected_rows> 0) {
If condition should be
if ($conn->affected_rows> 0){}
not
if ($resultdelete->affected_rows> 0){}
You're using it wrong if ($resultdelete->affected_rows> 0) you're using num_rows() syntax with the >0 bit.
The connection is passed to the function and not from the result set.
RTM http://php.net/manual/en/mysqli.affected-rows.php
Object oriented style
int $mysqli->affected_rows;
Procedural style
int mysqli_affected_rows ( mysqli $link )
From the manual:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* Insert rows */
$mysqli->query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", $mysqli->affected_rows);
$mysqli->query("ALTER TABLE Language ADD Status int default 0");
/* update rows */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", $mysqli->affected_rows);
/* delete rows */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows);
/* select all rows */
$result = $mysqli->query("SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", $mysqli->affected_rows);
$result->close();
/* Delete table Language */
$mysqli->query("DROP TABLE Language");
/* close connection */
$mysqli->close();
?>
Procedural style
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
if (!$link) {
printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
exit();
}
/* Insert rows */
mysqli_query($link, "CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", mysqli_affected_rows($link));
mysqli_query($link, "ALTER TABLE Language ADD Status int default 0");
/* update rows */
mysqli_query($link, "UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($link));
/* delete rows */
mysqli_query($link, "DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", mysqli_affected_rows($link));
/* select all rows */
$result = mysqli_query($link, "SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", mysqli_affected_rows($link));
mysqli_free_result($result);
/* Delete table Language */
mysqli_query($link, "DROP TABLE Language");
/* close connection */
mysqli_close($link);
?>

search recent in mysql?

I have a table named 'transactions', in which i store a user's all transactions. i want an mysql query such that it would extract recent 3 transactions from table for a specific user id.
i know i can use limit.
SELECT * FROM 'transactions' WHERE 'userid'=20 LIMIT 0,3;
but how can i access attributes of different transactions which are returned as object after query? also using limit 0,3 would start search from start of table but i want to start search from bottom of table. I am using it with php.
Well, since you are not using a programming language, and just mysql, all your attributes would be displayed in the query result in the console window.
Edit:
To access your query and results, see the following article on PHP.net's website: http://www.php.net/manual/en/mysqli-result.fetch-assoc.php
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
/EndEdit
To sort newest first, assuming you have a id column, use ORDER BY:
SELECT * FROM 'transactions' WHERE 'userid'=20 ORDER BY id DESC LIMIT 0,3;

PHP/MySQL Count Num Rows

I have the following PHP code:
$sql = new mysqli(/*connection info/db*/);
$query = $sql->$query("SELECT * from users WHERE /* rest of code */);
I was now wondering if there was any way I could retrieve the amount of rows that the above query found...
You should consider using PDO, it's safer and a more object oriented approach:
$database = new PDO(/*connection info/db*/);
$statement = $database->prepare('SELECT FROM fruit WHERE fruit_id = ? AND name = ?');
$statement->bindValue( 1, 'fruit_id_value' );
$statement->bindValue( 2, 'Banana' );
$statement->execute();
$count = $statement->rowCount(); # <-- The row count you are looking for!
--> visit http://php.net/manual/en/pdostatement.rowcount.php for more info
in Mysqli I know you can do
printf("Number of rows: %d.\n", $sql->num_rows);
Here is all the code
<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli->prepare($query)) {
/* execute query */
$stmt->execute();
/* store result */
$stmt->store_result();
printf("Number of rows: %d.\n", $stmt->num_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
I got that from this php manual http://php.net/manual/en/mysqli-stmt.num-rows.php
There is a modifier for the SELECT query that holds on to the information of the count you need: SQL_CALC_FOUND_ROWS
SELECT SQL_CALC_FOUND_ROWS * from users WHERE /* rest of code */
After running that query, you can run SELECT FOUND_ROWS(); to get the resulting number of rows.
If all you need is the count, you can just do
SELECT count(*) from users WHERE /* rest of code */

Categories