I want to count the number of values in one field in MySQL. I would then like to store the resulting count in the database.
Please help me work out the query required to do this.
Also could you help me to write a count function in PHP?
$query="select count(<column>) as total from <table>";
$result = mysql_query($query);
$total=mysql_result($result,0,"total");
Incomplete question. Fuzzy answering.
http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html
SELECT COUNT(field) FROM table
http://php.net/manual/en/function.count.php
count($array);
This would return the count of rows in MySQL.
SELECT COUNT(*) AS Column_Count FROM Table_Name
You could also just do this:
SELECT * FROM Table_Name
And count manually via PHP, via:
$query = mysql_query("SELECT * FROM Table_Name");
$count = mysql_num_rows($query);
something like:
function getTotalRows($table,$column = 'id')
{
global $mysql_link;
try
{
$resource = mysql_query(sprintf('SELECT count(%s) AS count FROM %s',$column,$table),$mysql_link);
if($resource !== false)
{
return (int)mysql_result($resource,0,'count');
}
return false;
}catch(Exception $e)
{
return false;
}
}
and them do:
$mysql_link = mysql_connect(....);
$total = getTotalRows('users','id');
To store the result of a count directly in the database, you can use INSERT INTO ... SELECT:
INSERT INTO table1 (count_col) SELECT COUNT(*) FROM table2;
Connect to DB:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
Update column:
$qry = "UPDATE `<my_table>` SET `<column>` = (SELECT COUNT(<column>) FROM <table> )";
Mysql_query($qry);
How to select value are in others posts.
Related
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];
I want to display the current amount of users registered in my database (it's called dalton) / the users are stored in a table in that database called simpleauth_players. It stores their name, hash, registerdate, logindate, and lastip.
I want to somehow use a PHP code that (logs me into the database) and displays the current amount of names in the database. So I can display a message like "Hey, there is currently 1,894 registered players!" inside of my HTML/PHP page. I'm kinda a novice it would be awesome if somebody could share the code and instructions.
My code:
$connection = mysql_connect('host', 'username', 'password');
mysql_select_db('database');
$query = "SELECT * FROM simpleauth_players";
$result = mysql_query($query);
$registered = "SELECT COUNT(*) FROM dalton.tables WHERE simpleauth_players = 'name' and TABLE_TYPE='BASE TABLE';
echo "$registered";
mysql_close();
This is the code I used to display the amount of registered players (AKA rows) in the simpleauth_players table.
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("dalton", $link);
if ($_GET['task'] == 'total') {
$get_db = 'simpleauth_players';
$result = mysql_query("SELECT * FROM $get_db", $link);
echo '{"task":"total","amount":"';
echo mysql_num_rows($result);
echo '"}';
}
?>
select count(*) as total_player from simpleauth_players
OR
$sql = "select * from simpleauth_players";
$result = mysqli_query($con,$sql);
$count = mysqli_num_rows();
echo "Total ".$count." Players";
Try this one assumed that your column name is language
SELECT COUNT(*) FROM simpleauth_players WHERE language = "PHP"
or if you want to get count by each language type you can use this
SELECT COUNT(DISTINCT user_id) AS Count,language FROM simpleauth_players GROUP BY language
As per your original post/question Since you have not provided us with the MySQL API you're using to connect with, here's an mysqli_ version, using MySQL's aggregate COUNT() function, which will count the number of given rows in a table:
$connection = mysqli_connect('host', 'username', 'password', 'database');
$result = mysqli_query($connection, "SELECT COUNT(*) as count
FROM simpleauth_players"
);
while ($row = mysqli_fetch_array($result)) {
$var = $row['count'];
echo "There are currently " .$var. " users.";
}
Edit: if using mysql_
$connection = mysql_connect('host', 'username', 'password');
if (!$connection) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('database', $connection);
if (!$db_selected) {
die ('Can\'t use database : ' . mysql_error());
}
$result = mysql_query("SELECT COUNT(*) as count
FROM simpleauth_players", $connection);
while ($row = mysql_fetch_array($result)) {
$var = $row['count'];
echo "There are currently " .$var. " users.";
}
In the following code I'm attempting to connect to my database, pull the maximum ID from my table and then generate a random number using the the rand() function. The code successfully connects me to the the database but when I try to call for the maximum ID it won't return a value.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) FROM 'table'";
$rannmr = rand(1, $amount);
// Close the mysql connection
mysqli_close($dbLink);
?>
Any help in resolving this would be appreciated.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
Firstly, you are using the wrong identifier for FROM 'table' being single quotes.
If table is indeed the table's name, wrap it in backticks, your question shows file.
$amount = "SELECT MAX(id) FROM `table`";
Either way, you cannot use quotes around a table name. It appears you are using file as your table name.
So if table is only an example and it is called file let's just say, you would do:
$amount = "SELECT MAX(id) FROM `file`";
or
$amount = "SELECT MAX(id) FROM file";
Then, you also need to query, using mysqli_query() which you are not doing.
$amount = mysqli_query($dbLink,"SELECT MAX(id) FROM `file`");
Or Object oriented style:
$amount = $dbLink->query("SELECT MAX(id) FROM `file`");
if($amount){
echo "Success!";
}else{
die('Error : ('. $dbLink->errno .') '. $dbLink->error);
}
See example #1 from http://php.net/manual/en/mysqli.query.php
Use or die(mysqli_error($dbLink)) to mysqli_query() which would have signaled the error.
http://php.net/manual/en/mysqli.error.php
Edit:
Try the following. You may need to modify $row[0] and rand(0,$count) as 1 depending on the column number.
$result = $dbLink->query("SELECT MAX(id) FROM mytable")
while ($row=$result->fetch_row()) { $count = $row[0]; }
$random = rand(0,$count);
echo $random;
use this:
$amount = "SELECT MAX(id) FROM table";
You forgot to execute the MySQL-query:
$amount = $dbLink->query("SELECT MAX(id) FROM table")->fetch_assoc();
$rannmr = rand(1, $amount[0]);
You never executed the query, you need more logic
if ($result = mysqli_query($dbLink, "SELECT MAX(id) as amount FROM `table`")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
if ($row = mysqli_fetch_assoc($result)) {
$amount = $row['amount'];
$rannmr = rand(1, $amount);
}else{
echo 'no row found';
}
}
mysqli_close($dbLink);
I didn't seem to see the line of code which actually does the query:
Try this: Using the object-oriented mysqli approach
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) as max_id FROM 'table'";
// Do the actual query :
$run_query = $dbLink->mysql->query($amount);
// Retrieve the values:
$result = $run_query->fetch_array();
// Do the rand function together with the retrieved value
$rannmr = rand(1, $result['max_id']);
// Now you can echo the variable:
echo $rannmr;
// Close the mysql connection
mysqli_close($dbLink);
?>
Thanks!!
<?php
$db = mysql_connect('localhost', 'root', '') or
die ('Unable to connect. Check your connection parameters.');
mysql_select_db('my_db', $db) or die(mysql_error($db));
$query = 'SELECT
second, count(*) FROM tb_one GROUP BY second';
$result = mysql_query($query, $db) or die(mysql_error($db));
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $value) {
$queryy = 'INSERT INTO tb_two (name) VALUES ("' . $value . '")';
mysql_query($queryy, $db) or die(mysql_error($db));
}
}
?>
In this script first query is meant to select and count duplicate values(that works well), But in second query I want to insert the selected data in another table which has two columns, first column for its name and second column for its count of duplicate...If there is one column in the insert statement it works well and adds values. But I want two columns- one for name and one for its counted number of duplicates. thank you sir...I have been trying it for many days..
You can do this all in MySQL:
INSERT INTO tb_two(name, count)
SELECT second, count(*)
FROM tb_one
GROUP BY second;
Though, in other news the mysql_ functions have been deprecated. You should be using the PDO Library. Or at least the MySQL Improved Library.
Make your life easier by aliasing the duplicate column, so you can address it more easily.
Here is how:
Replace this
$query = 'SELECT second, count(*) FROM tb_one GROUP BY second';
by this:
$query = 'SELECT second, count(*) as duplicates FROM tb_one GROUP BY second';
You now have "duplicates" as the column name. Then you can use it, like this for example:
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $r) {
$queryy = "INSERT INTO tb_two SET name='".$r['second']."', duplicates='".$r['duplicates']."'";
mysql_query($queryy, $db) or die(mysql_error($db));
}
}
Try this, sorry if it has a syntax issue, I did it in notepad.
while ($row = mysql_fetch_assoc($result))
{
$query = "INSERT INTO tb_two (column1, column2) VALUES ('" . $row[0] . "', '" . $row[1] . "')";
mysql_query($query, $db) or die(mysql_error($db));
}
I want to execute a query that i saved in my database like this:
ID | NAME | QUERY
1 | show_names | "SELECT names.first, names.last FROM names;"
2 | show_5_cities | "SELECT cities.city FROM city WHERE id = 4;"
Is this possible ?
I am kinda noob in php so plz explain if it is possible.
If I understand you correctly, you have your queries saved in the database in a table and you want to execute those.
Break the problem down: you have two tasks to do:
Query the database for the query you want to run.
Execute that query.
It's a bit meta, but meh :)
WARNING: the mysql_ functions in PHP are deprecated and can be dangerous in the wrong hands.
<?php
if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
die('Could not connect to mysql');
}
if (!mysql_select_db('mysql_dbname', $link)) {
die('Could not select database');
}
$name = "show_5_cities"; // or get the name from somewhere, e.g. $_GET.
$name = mysql_real_escape_string($name); // sanitize, this is important!
$sql = "SELECT `query` FROM `queries` WHERE `name` = '$name'"; // I should be using parameters here...
$result = mysql_query($sql, $link);
if (!$result) {
die("DB Error, could not query the database\n" . mysql_error(););
}
$query2 = mysql_fetch_array($result);
// Improving the code here is an exercise for the reader.
$result = mysql_query($query2[0]);
?>
if you did create a stored procedure/function you can simply use:
mysql_query("Call procedure_name(#params)")
Thats will work. reference here: http://php.net/manual/en/mysqli.quickstart.stored-procedures.php
Querying the table to get the query, then executing that query and looping through the results and outputting the fields
<?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();
}
$RequiredQuery = intval($_REQUEST['RequiredQuery']);
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $sql);
if ($row = mysqli_fetch_assoc($result))
{
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $row['QUERY']);
while ($row2 = mysqli_fetch_assoc($result))
{
foreach($row2 AS $aField=>$aValue)
{
echo "$aField \t $aValue \r\n";
}
}
}
?>
just open the Table and get the individual query in a variable like
$data = mysql_query('SELECT * FROM <the Table that contains your Queries>');
while(($row = mysql_fetch_row($data)) != NULL)
{
$query = $row['Query'];
mysql_query($query); // The Query from the Table will be Executed Individually in a loop
}
if you want to execute a single query from the table, you have to select the query using WHERE Clause.