How to echo the result of my query? PHP & MySQL - php

so I have this query:
SELECT COUNT( * ) AS cnt
FROM table
WHERE datetime > NOW( ) - INTERVAL 45
SECOND
When I preform this query in MySQL I get the result: cnt 25 (http://puu.sh/7ZNh.png)
I now want to echo this in my PHP page, how would I do this?
UPDATE:
Here is the full code
<?php
$con = mysql_connect("host","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$query = ("SELECT COUNT(*) FROM usersonline WHERE datetime > NOW() - INTERVAL 5 MINUTE");
$result = mysql_query($query);
?>

list($count) = #mysql_fetch_row(mysql_query($sql));
echo $count;

Within your PHP application you need to setup a database object which can be used to connect to your database in order to execute your queries. A good place to start is with PHP PDO, more info # http://us.php.net/manual/en/pdo.query.php along with some good examples.

$con = mysql_connect("host","user","pass");
if (!$con)
{
die('Could not connect: '.mysql_error());
}
mysql_select_db("db", $con);
$query = ("SELECT COUNT(*) FROM usersonline
WHERE datetime > DATESUB(NOW(),INTERVAL 5 MINUTE) ");
$result = mysql_query($query);
if (!$result)
{
die('Error in select statement: '.mysql_error());
}
$row = mysql_fetch_array($result);
echo "number of rows = ".htmlentities($row['cnt']);

Related

Fetching SQL Current date for Graph lib php from timestamp

So i have setup the code to display graph from php sql. But i cant seem to order it by todays date from a timestamp in my table. Here is my code:
<?php
include("phpgraphlib.php");
$graph=new PHPGraphLib(550,450);
$link = mysql_connect('xxx', 'xxx', 'xxx')
or die('Could not connect: ' . mysql_error());
mysql_select_db('test') or die('Could not select database');
$dataArray=array();
//get data from database
// $sql="SELECT rating, COUNT(*) AS 'datentry' FROM main_table GROUP BY rating";
$sql="SELECT rating, COUNT(*) AS 'datentry' FROM main_table GROUP BY rating";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
$salesgroup=$row["rating"];
$count=$row["datentry"];
//add to data areray
$dataArray[$salesgroup]=$count;
}
}
//configure graph
$graph->addData($dataArray);
$graph->setTitle("Daily");
$graph->setGradient("lime", "green");
$graph->setBarOutlineColor("black");
$graph->createGraph();
?>
What i want to achieve is to be able to display just todays data. This specific code displays all of the data in my table.

Display amount of registered users in MySQL database using PHP

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.";
}

Adding either DISTINCT or GROUP BY to my mysql_query is causing no values to be returned

I am using php to get records from a mysql database using the following code:
<?php
$username="";
$password="";
$database="";
$hostname="";
$con = mysql_connect($hostname, $username, $password);
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
if(isset($_POST['emp'])){
$emp = $_POST['emp'];
$result = mysql_query("SELECT * FROM contact_log", $con);
echo mysql_num_rows($result);
die();
while($row = mysql_fetch_array($result)){
$emp = $row['emp'];
echo $emp.'<br>';
}
die();
}
mysql_close($con);
?>
This works fine and returns the correct fields. The problem is that if I change the query to
$result = mysql_query("SELECT DISTINCT * FROM contact_log", $con);
or
$result = mysql_query("SELECT * FROM contact_log GROUP BY emp", $con);
no results are returned.
mysql_num_rows does not even return a value which indicates to me that those lines are breaking my code but I am unable to figure out how.
I doubt you want to do a distinct * on your first query. Looking at your code, you probably want:
"SELECT DISTINCT emp FROM contact_log"
And you can get more information about what is going wrong with mysql_error:
mysql_query("select * from table") or die(mysql_error())
Finally, are you sure that $_POST['emp'] is being sent? Put an echo right after that if to make sure. And just so you know, you aren't using the emp POST variable for anything other than a flag to enter that block of code. $emp = $_POST['emp']; is doing absolutely nothing.

PHP MySQL - limit query result by time difference

This would be an example of database table:
PHP script should limit query result between NOW and time before 30 seconds
To be clear:
In current time is 2012-03-23 03:28:00 and database is as descibed in example, resoult should be: "guest"
This is a part of PHP script.
<?php
$con = mysql_connect("localhost", "user", "pass");
if (!$con) {
die('Could not connect: '.mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query('SELECT * FROM table LIMIT BY ...???...... ');
while ($row = mysql_fetch_array($result)){
echo $row['username'];
}
mysql_close($con);
?>
You don't want a LIMIT, you want a WHERE
$result = mysql_query(
'SELECT * FROM table WHERE `timestamp` > NOW()- INTERVAL 30 SECOND '
);
In SQL, a LIMIT clause executes the whole query, and then only takes a certain "range" of consecutive rows. You can say "The first 50", or "From 20 to 30".
A WHERE clause limits the query on certain criteria, such as field contents. That is what you want here.
... WHERE (unix_timestamp(NOW()) - unix_timestamp(timestamp))<30 ..
OR
WHERE TIME_TO_SEC(TIMEDIFF(NOW(), timestamp))<30
$result = mysql_query('SELECT * FROM table where date_sub(now(), timestamp ) < your_time_interval ');

MySQL - count total number of rows in php

What is the best MySQL command to count the total number of rows in a table without any conditions applied to it? I'm doing this through php, so maybe there is a php function which does this for me? I don't know. Here is an example of my php:
<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("some command");
$row = mysql_fetch_array($result);
mysql_close($con);
?>
<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("select count(1) FROM table");
$row = mysql_fetch_array($result);
$total = $row[0];
echo "Total rows: " . $total;
mysql_close($con);
?>
Either use COUNT in your MySQL query or do a SELECT * FROM table and do:
$result = mysql_query("SELECT * FROM table");
$rows = mysql_num_rows($result);
echo "There are " . $rows . " rows in my table.";
mysqli_num_rows is used in php 5 and above.
e.g
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
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 COUNT in a SELECT query.
$result = mysql_query('SELECT COUNT(1) FROM table');
$num_rows = mysql_result($result, 0, 0);
you can do it only in one line as below:
$cnt = mysqli_num_rows(mysql_query("SELECT COUNT(1) FROM TABLE"));
echo $cnt;
use num_rows to get correct count for queries with conditions
$result = $connect->query("select * from table where id='$iid'");
$count=$result->num_rows;
echo "$count";
for PHP 5.3 using PDO
<?php
$staff=$dbh->prepare("SELECT count(*) FROM staff_login");
$staff->execute();
$staffrow = $staff->fetch(PDO::FETCH_NUM);
$staffcount = $staffrow[0];
echo $staffcount;
?>
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
echo "number of rows: ",$rowcount;
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
it is best way (I think) to get the number of special row in mysql with php.
<?php
$conn=mysqli_connect("127.0.0.1:3306","root","","admin");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="select count('user_id') from login_user";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result);
echo "$row[0]";
mysqli_close($conn);
?>
Still having problem visit my tutorial http://www.studentstutorial.com/php/php-count-rows.php
$sql = "select count(column_name) as count from table";
Well, I used the following approach to do the same: I have to get a count of many tables for listing the number of services, projects, etc on the dashboard. I hope it helps.
PHP Code
// create a function 'cnt' which accepts '$tableName' as the parameter.
function cnt($tableName){
global $conection;
$itemCount = mysqli_num_rows(mysqli_query($conection, "SELECT * FROM `$tableName`"));
echo'<h6>'.$itemCount.'</h6>';
}
Then when I need to get the count of items in the table, I call the function like following
<?php
cnt($tableName = 'projects');
?>
In my HTML front end, so it renders the count number
It's to be noted that I create the cnt() function as a global function in a separate file which I include in my head, so I can call it from anywhere in my code.

Categories