Setting variable equal to count of a field in database table - php

For the query below, I would like to set a variable called $totalcount equal to the count of all loginids in table called login. How can I do this?
Thanks in advance,
John
$sqlStrcount = "SELECT loginid FROM login";

$sqlQueryStr = "SELECT loginid FROM login";
$sqlQuery = mysql_query($sqlQueryStr);
$totalCount = mysql_num_rows($sqlQuery);
If you only need to count your records in login use this instead
for performance reasons.
$sqlQueryStr = "SELECT COUNT(loginid) as totalCount FROM login";
$sqlQuery = mysql_query($sqlQueryStr);
$row = mysql_fetch_assoc($sqlQuery);
$totalCount = $row['totalCount'];

Related

How to output a value of an other table from an indexed field in mySQL?

I have two MySQL tables
users with id, user_formOfAdress and serveral additional fields. Field user_formOfAdress contains the id of table formofadress
formofadress with id, formOfAdress_german and serveral additional fields, for example id 1 = Mr., id 2 = Mrs.
The record of the users table is identified by a Session variable.
To output not the id of the field user_formOfAdress but the value of the table formofadress.formOfAdress_german (for example Mr. or Mrs.) I have written this:
if(array_key_exists("id", $_SESSION) && $_SESSION['id']){
$uid = $_SESSION['id'];
$link = mysqli_connect("localhost:3307", "root", "Dinah123", "proficrm");
$query = "
SELECT formofadress.ID AS formofadress_ID, formofadress.formOfAdress_german, users.ID, users.user_formOfAdress
FROM `formofadress`
LEFT JOIN users
ON formofadress.formofadress_ID = users.user_formOfAdress
WHERE `users.ID` = '".$uid."'
LIMIT 1
";
$result = mysqli_query($link, $query);
$record = mysqli_fetch_assoc($result);
$user_formOfAdress = $record['formOfAdress_german'];
}
"FROM formofadress" because I want to output the Mr. or Mrs. of this table, but I have to use also the users table because of the Session ID which is also the id of the users record ...
Not every record in the users table has a value in user_formOfdAdress (value 1, 2 or NULL) but every record in the formofadress table has a fixed value.
Error is:
Undefined variable: user_formOfAdress located in the last row
It's my first time to use JOINs and I'm unfortunately not able to solve this issue even after a long time of searching.
Correct code:
if(array_key_exists("id", $_SESSION) && $_SESSION['id']){
$uid = $_SESSION['id'];
$link = mysqli_connect("localhost:3307", "root", "Dinah123", "proficrm");
$query = "
SELECT formofadress.ID, formofadress.formOfAdress_german, users.ID, users.user_formOfAdress
FROM formofadress
LEFT JOIN users
ON formofadress.ID = users.user_formOfAdress
WHERE users.ID = '".$uid."'
";
$result = mysqli_query($link, $query);
$record = mysqli_fetch_assoc($result);
$user_formOfAdress = $record['formOfAdress_german'];
}
There were problems with your SQL syntax. You used LEFT JOIN to join users to formofadress while users sometimes can't follow and you will possibly get a NULL value. I also cleaned up your other query syntax so it is more readable.
Also, check to see if the database is expecting an INT for $uid. If not then return the apostrophes ''.
if(array_key_exists("id", $_SESSION) && $_SESSION['id'])
{
$uid = $_SESSION['id'];
$link = mysqli_connect("localhost:3307", "root", "Dinah123", "proficrm");
$query = "SELECT u.ID, u.user_formOfAdress, f.ID, f.formOfAdress_german,
FROM users u LEFT JOIN formofadress f ON f.formofadress_ID = u.user_formOfAdress
WHERE u.ID = ".$uid." LIMIT 1";
// if database is not expecting `INT` for `u.ID` then return the apostrophes ' '
$result = mysqli_query($link, $query);
// mysqli_fetch_assoc returns case sensitive keys
$record = mysqli_fetch_assoc($result);
$user_formOfAdress = $record['formOfAdress_german'];
}

retrieve count in php

I need to retrieve the count of a field name called remark corresponding to a particular user.
select count(remark) from attendance where username=_POST['username']
How will I implement this in php? I need to store the count to a variable $totalcount.
This is what i tried out:
$result = mysql_query("select count(1) FROM attendance where stud_id='$_POST['user']'");
$row = mysql_fetch_array($result);
$total = $row[0];
Also quotes are not used properly in the query string. Try this code.
$result = mysql_query("select count(*) FROM attendance where stud_id='".$_POST['user']."'");
$row = mysql_fetch_array($result);
$total = $row[0];

Warning: mysql_error() expects parameter 1 to be resource, string given

<?php
session_start();
$username = "root";
$password = "password";
$database = "meipolytechnic";
mysql_connect('localhost', $username,$password);
#mysql_select_db($database) or die(mysql_error());
$username=$_SESSION['MM_Username'];
$query = "SELECT rollno FROM users where username = '".$username."'";
$result = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result);
mysql_close();
$rows = array();
while($r = mysql_fetch_row($result))
{
$rows[] = $r[0];
}
echo ($rows['rollno']);
?>
i want to retrieve only the logged in users roll no from users table in database
when i run this code
and log in as foo
i get the following stuff
Unknown column 'foo' in 'where clause'
There should be session_start() at the top of the page
query need to change as
$query = "SELECT rollno FROM users where username = '".$_SESSION['MM_Username']."' ";
EDIT
Please try something before posting a question here. Please google or go through www.w3school.com for clearing this kind of issues. Make a good knowledge about arrays and mysql connection. And mysql_query function won't work latest PHP version.
Please try following code.
$result = mysql_query($query) or die(mysql_error());
$rows = array();
while($r = mysql_fetch_row($result))
{
$rows[] = $r[0];
}
print_r($rows);
To use an array inside a string you need to put a curly bracket before it and after it
so
$query = "SELECT rollno FROM users where username = {$_SESSION['MM_Username']}";
or
$query = "SELECT rollno FROM users where username = ".$_SESSION['MM_Username'];
First of all start session using start_session()
then change your query:
$query = "SELECT rollno FROM users where username = ".$_SESSION['MM_Username'];
then change:
$num = mysql_num_rows($result); instead of $num = mysql_numrows($result);
Try this query
$query = "SELECT rollno FROM users where username = ".$_SESSION[MM_Username]." ";
And start session on same page.
You can use
$username=$_SESSION[MM_Username];
$query = "SELECT rollno FROM users where username = '".$username."'";
and start the session by using session_start()
and you have used two closing tags omit one make it like below
echo ($rows['rollno']);
?>
This type of error occur when query goes false
May be becouse You have not start session, becouse if you dont have session_start(), then nothing will come in session variable... just try as
$query = "SELECT rollno FROM users where username = '".$_SESSION[MM_Username]."'";
may this help you
You must need to use session_start() before using $_SESSION variable in code.
So put below code at start,
session_start();
Then do some modification in query like,
$query = "SELECT rollno FROM users where username = '".$_SESSION['MM_Username']."'";
first start your session
session_start();
and Change your query like this...
$query = "SELECT rollno FROM users where username = '".$_SESSION['MM_Username']."'";

php mysql query works in phpmyadmin but not on webpage

i wrote the following query
SELECT COUNT(userID) From statistics WHERE userID = ""
this query displays the number of unathunticated visit to the website.
the query works in phpmyadmin when i use double quotes however it doesnt when i use single quotes like below it just gives me the number of record stored in the table
$queryB = "SELECT COUNT(userID) From statistics WHERE userID = ''";
$resultB =mysql_query($queryA, $con) or die(mysql_error());
$authB = mysql_result($resultB, "COUNT(userID)");
echo "the number of authenticated visits were $authB<br />\n";
i've no idea why it breaks, any ideas?
you store your query in $queryB but you use $queryA
not sure if it will work...its just first think that came to mind:
how about when u use escaped double quotes?
$queryB = "SELECT COUNT(userID) From statistics WHERE userID = \"\""
Try this:
$queryB = "SELECT COUNT(userID) AS total From statistics WHERE userID = ''";
$resultB =mysql_query($queryB, $con) or die(mysql_error());
$authB = mysql_fetch_assoc($resultB);
echo "the number of authenticated visits were ".$authB['total']."<br />\n";
Does userID have a default value? If the default value is NULL, then change your query to
$queryB = "SELECT COUNT(userID) From statistics WHERE userID IS NULL";
you should change a little to your code
$queryB = "SELECT COUNT(userID) From statistics WHERE userID = ''";
$resultB =mysql_query($queryB, $con) or die(mysql_error());
$authB = mysql_result($resultB, 0, 0);
echo "the number of authenticated visits were $authB<br />\n";

'Counting' the number of records that match a certain criteria and displaying the numbers (using PHP and MySQL)

I have a MySQL database containing a user's country and whether they are an individual or an organisation. The field names are 'country' and 'type'.
Using PHP, I'd like to 'count' the number of countries, the number of individuals and the number of organisations in the database and then display the numbers in the following example format:
<p>So far, <strong>500</strong> individuals and <strong>210</strong> organisations from <strong>40</strong> countries have registered their support.</p>
I am currently listing the total number of records using the below code if this helps:
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $link);
$result = mysql_query("SELECT * FROM table_name", $link);
$num_rows = mysql_num_rows($result);
echo " $num_rows\n ";
?>
My PHP / MySQL skills are very limited so I'm really struggling with this one.
Many thanks in advance!
Ben
To get the number of countries:
SELECT COUNT(DISTINCT country) AS NumCountries FROM tableName
To get the number of individuals, or the number of organisations:
SELECT COUNT(*) AS NumIndividuals FROM tableName WHERE type = 'individual'
SELECT COUNT(*) AS NumOrganisations FROM tableName WHERE type = 'organisation'
What you are looking for is a count based on a grouping. Try something like this:
$sql = "SELECT type, count(*) as cnt FROM users GROUP BY type";
$result = mysql_query($sql);
$counts = array();
while ($row = mysql_fetch_assoc($result)) {
$counts[$row['type']] = $row['cnt'];
}
This will give you an array like
Array (
'individual' => 500,
'organization' => 210
)
For counting the countries, use the first statement as posted by Hammerite.
EDIT: added a verbose example for counting the countries
$sql = "SELECT COUNT(DISTINCT country) AS NumCountries FROM users";
$result = mysql_query($sql);
$number_of_countries = 0;
if ($row = mysql_fetch_assoc($result)) {
$number_of_countries = $row['NumCountries'];
}
This altogether you can then print out:
printf('<p>So far, <strong>%d</strong> individuals and <strong>%d</strong> '.
'organisations from <strong>%d</strong> countries have registered '.
'their support.</p>', $counts['individual'], $counts['organization'],
$number_of_countries);
The answer is to retrieve the answer by using the COUNT(*) function in SQL:
SELECT COUNT(*) AS individual_count FROM user WHERE type = 'individual';
SELECT COUNT(*) AS organization_count FROM user WHERE type = 'organization';
SELECT COUNT(*) AS country_count FROM user GROUP BY country;
The last will group your query set by the country name, and will result in one row for each country. Using COUNT on this result set will give the count of distinct coutries.
You can then fetch this value by using mysql_fetch_assoc on your $result from mysql_query, and the answer will be contained in 'invididual_count', 'organization_count' and 'country_count' for each query.
Thank you for all of your help with this (especially Cassy).
I think it's worthwhile displaying the full code in case anybody else comes across a similar requirement in the future:
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $link);
$sql = "SELECT type, COUNT(*) as cnt FROM table_name GROUP BY type";
$result = mysql_query($sql);
$counts = array();
while ($row = mysql_fetch_assoc($result)) {
$counts[$row['type']] = $row['cnt'];
}
$sql = "SELECT COUNT(DISTINCT country) AS NumCountries FROM table_name";
$result = mysql_query($sql);
$number_of_countries = 0;
if ($row = mysql_fetch_assoc($result)) {
$number_of_countries = $row['NumCountries'];
}
printf('<p><strong>So far, <em class="count">%d</em> individuals and <em class="count">%d</em> organisations from <em class="count">%d</em> countries have registered their support.', $counts['Individual'], $counts['Organisation'], $number_of_countries); ?>
If you're just looking for the number of rows returned try this:
$result = mysql_db_query($db, $query);
$num_rows = mysql_num_rows($result);
Another option would be to execute a separate query with the mysql count function and use the result from that.

Categories