Count number of rows in Mysql using PHP7 [duplicate] - php

This question already has answers here:
number of rows in a table
(3 answers)
Closed 2 years ago.
I have upgraded PHP on my server from version 5 to 7 and I found out that mysql_* functions were removed and now I should use mysqli or PDO. I updated the following code (mysqli instead of mysql) that I used to print number of rows in a given table, but it doesn't work as it used to.
$link = mysql_connect("xxx", "xxx", "xxx");
mysql_select_db("xxx", $link);
$result = mysql_query("SELECT * FROM blackandwhite", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n"; // This works in PHP5
Updated code PHP7:
$link = mysqli_connect("xxx", "xxx", "xxx");
mysqli_select_db("xxx", $link);
$result = mysqli_query("SELECT * FROM blackandwhite", $link);
$num_rows = mysqli_num_rows($result);
echo "$num_rows Rows\n"; // This doesnt work anymore.

The mysqli_ functions actually accept the link as the first argument, as it is non-optional like it is with the normal mysql_ functions.
This should work as you expect:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("host", "username", "password","db_name");
mysqli_set_charset($link, "utf8mb4");
$result = mysqli_query($link, "SELECT count(*) FROM blackandwhite");
$num_rows = mysqli_fetch_row($result)[0];
echo "$num_rows Rows\n";

Related

How to return integer of COUNT mysql query result in PHP [duplicate]

This question already has answers here:
How to get count of rows in MySQL table using PHP?
(3 answers)
Closed 2 years ago.
I'm just putting a simple PHP program together that simply counts the number of total rows in my database and returns the result as a JSON object when it recieves a get request from my frontend.
This should all be super simple but for the life of me I can't figure out how to retrieve the count result in a usable format. All I get from this is "null"
any ideas?
$con = mysqli_connect($servername, $username, $password, $dbname);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$query="SELECT COUNT(*) FROM database";
$result = mysqli_query($con,$query);
$count = mysqli_fetch_assoc($result);
echo json_encode($count);
You can use COUNT as to avoid a very long key.
Here's a code example
$sql = "SELECT COUNT(column) as count FROM mytable";
$stmt = mysqli_stmt_init($db);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$count = mysqli_fetch_assoc($result)['count'];
echo $count;
To display data in JSON you can try this:
echo json_encode(['count' => $count])
That by itself will not give you the count.
I would suggest that you start using MySQL object methods instead of functions.
You should also use the "as" satement as way to give a name to the column that has the count value; in my example that column will be known as C .
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT COUNT(*) as C FROM database";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
$row = $result->fetch_assoc();
echo $row["C"];
}
EDIT:
In the specific case of SELECT COUNT you'll only get 1 row, so for this specific example you could do just fetch_assoc().

Using mysqli_query with mysql_query arguments

I'm migrating from PHP 5 to PHP 7, and I made a grep to get all mysql_query to change them to mysqli_query. The problem is, apparently the parametres changed using the procedural style.
mysql_query($query, $link_identifier)
mysqli_query($link_identifier, $query)
Even tho using the object oriented style they're still the same parametres.
Question is, will it work if I leave the parameters of mysqli_query as $query, $link thinking that the function is smart enough to detect which is which or I need to change them all to match the right parameters ?
Order of arguments isn't interchangeable.
Php.net mysqli_query.
Php.net mysql_query.
I also tested it.mysql_query
$link = mysql_connect("localhost","login","pass");
$db_selected = mysql_select_db('db', $link);
$sql = "SELECT * FROM table LIMIT 5";
$result = mysql_query($sql, $link);
while($row = mysql_fetch_array($result)) {
echo $row['col_name'];
}
mysql_close($link);
mysqli_query with with wrong order of arguments will produce: Warning: mysqli_query() expects parameter 1 to be mysqli, string given code here:
$link = mysqli_connect("localhost", "login", "pass", "db");
//arguments in wrong order
if ($result = mysqli_query("SELECT * FROM table LIMIT 5", $link)) {
while($row = mysqli_fetch_array($result)) {
echo $row['col_name'];
}
}
//produce
//Warning: mysqli_query() expects parameter 1 to be mysqli, string given in
mysqli_close($link);

PHP and DB connections replace with mysqli from mysql [duplicate]

This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 3 years ago.
$con = mysql_connect("localhost", "root", "");
$db = mysql_select_db("dbname", $con);
$q = "select*from tablename";
$qry = mysql_query($q);
can you please help me to convert this mysql query to mysqli
Use like
// mysqli_connect(host,username,password,dbname,port,socket);
$con = mysqli_connect("localhost", "root", "", "your_db");
// mysqli_select_db(connection, dbname);
$db = mysqli_select_db($con, "dbname");
$q = "select*from tablename";
// mysqli_query(connection,query,resultmode);
$qry = mysqli_query($con, $q);
Refer below docs
PHP Mysqli
w3schools Mysqli

PHP get data from DB not working [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
Can you figure out my code? All the code does is: No database selected It won't get the data from the db. The server os is Ubuntu or OS X. I been pulling my hair out for hours.
<?php
mysqli_connect("localhost", "root", "");
mysql_select_db("hit-counter");
$sql_get_count = mysql_query("SELECT id FROM hit_info ORDER BY id DESC LIMIT 1");
if($sql_get_count === FALSE) {
die(mysql_error());
}
while($row = mysql_fetch_assoc($sql_get_count)) {
print_r($row);
}
?>
I try this, it does the same
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("hit-counter");
$sql_get_count = mysql_query("SELECT id FROM hit_info ORDER BY id DESC LIMIT 1");
if($sql_get_count === FALSE) {
die(mysql_error());
}
while($row = mysql_fetch_assoc($sql_get_count)) {
print_r($row);
}
?>
you have an error in your code. You use mysqli_ function to connect the server but you use a deprecated function mysql_ to select the database.
Try this code:
mysqli_connect("localhost", "root", "");
mysqli_select_db("hit-counter");
Another option when using mysqli_ is to select the database you want during connecting to the server:
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
You didn't mention database name:try this
<?php
$con = mysqli_connect("127.0.0.1","root","654321","testV2") or die("Some error occurred during connection " . mysqli_error($con));
// Write query
$strSQL = "SELECT id FROM did ORDER BY id DESC LIMIT 1";
// Execute the query.
$query = mysqli_query($con, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo $result["id"]."
";
}
// Close the connection
mysqli_close($con);
?>
You cannot interchange the mysql and mysqli functions, please modify your mysql_select_db to mysqli_select_db.
I will not go over the errors everyone else has pointed out. But, I will mention one that no one has. I think the - character in your database name will also cause problems. You should enclose the database name in back ticks. The back tick is this ` character, most likely the far left key above the TAB key. If you had error reporting turned on, or looked at your php error log, you would have seen the error.

PHP Count SQL gives no result [duplicate]

This question already has answers here:
select count(*) from table of mysql in php
(12 answers)
Closed 7 years ago.
I want to Count a number of elements in a MySQL Table with the PHP element count, but when i try to give out the result it print 'Resource id #5' which is of course the id for succeeded MYSQL srcipts. If I type it in the SQL console it says I have got Syntax Error (#1064). Thats my code:
<?php
$dbhost = >>hostname<<;
$dbuser = >>user<<;
$dbpass = >>password<<;
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db(>>database to be selected<<)
or die ("Database couldnĀ“t be found");
echo mysql_query('SELECT COUNT(*) FROM table'); ?>
Which mysql_fetch_ do i have to use?
Thanks for any effords and a happy new year
Tim
You have to fetch the result from the query.
$result = mysql_query('SELECT COUNT(*) AS count FROM table');
$row = mysql_fetch_assoc($result);
echo $row['count'];
You should also convert from the mysql extension to PDO or mysqli, but the basic structure is the same -- after performing a query you have to fetch the results as a separate step.
If you just looking for:
Which mysql_fetch_ do i have to use?
Than you can try these:
mysql_fetch_assoc();
mysql_fetch_array();
mysql_fetch_object();
Side note:
Also remember what Mr. Barmar said about the **PDO or mysqli_* **

Categories