I am using the count(*) AS, as an alternative to mysql_num_rows().
I get a count for all 3 kinds of feedback (positive, negative and neutral).
But I don't know how to assign the count of, say, positive feedback to a variable that I would call $positive_feedback and then, echo it. How can you do this with the following example?
I have this:
SELECT feedback, count(*) AS `count`
FROM feedback
WHERE seller='$user'
GROUP BY feedback
which gives something like that:
feedback | count
----------------
positive | 12
neutral | 8
negative | 3
$result = mysql_query($query); // with your query.
$feedback=array();
while ($row = mysql_fetch_assoc($result)) {
$feedback[$row['feedback']]=$row['count'];
}
It will give an array consisting of feedback['positive'],feedback['negative'] and so on with count stored in each.
Use Count(1), not Count(*), it's faster because the SQL engine can just use the count values from the counting B-Tree index and does not need to ever access any other values. If you plan to make this query a lot, make sure you add an index on the feedback tuple.
$query = "SELECT feedback, count(1) AS `count`...";
$result = mysql_query($query, $link); // don't forget to share your db conn
$feedbackArr = new array();
while ($row = mysql_fetch_assoc($result)) {
$feedbackArr[$row['feedback']] = (int)$row['count'];
}
echo "Positive Feedback: \n";
print_r($feedbackArr);
With PDO it will look something like this:
$dsn = "mysql:host=%;dbname=%"; // insert your host and dbname
$db = new PDO($dsn, $username, $password); // insert your username and pass
$sql = "
SELECT
feedback, count(*) AS `count`
FROM
feedback
WHERE
seller='$user'
GROUP BY feedback
";
$feedback = array();
foreach ( $db->query($sql) as $row ) {
$feedback[ $row['feedback'] ] = $row['count'];
}
// result in here
print_r ($feedback);
Related
This question already has answers here:
number of rows in a table
(3 answers)
Closed 6 years ago.
Going to make this quick.
So I am doing something that should be relatively simple but none of the answers I have found online (Yes, I have read through and implemented them ALL) have yielded the right result.
Basically, all I am trying to do is count how many times a specific field shows up in a column in one of my databases. Sounds easy, right?
Well, this is where it gets a bit sketchy for me. The query I am trying to use to attain this information is this:
$sql2 = "SELECT user_id COUNT(*) FROM ch_documents_list WHERE user_id = $users_id ";
From here, I want to take the result as an int and echo it into a specific part of the site (not important as to where exactly).
The only way I can get information out of the result is to run a print_r($result) Where $result is set to the response of the query.
NOTE The information printed looks like this:
mysqli_result Object ( [current_field] => 0 [field_count] => 5 [lengths] => [num_rows] => 1 [type] => 0 )
Which, as many of you can figure out, is useless. What changes do I need to make in order to get this right?
Thanks everyone!
Pasting more of my code below
Query As Of Now
$dbname_classes = "classes";
$conn2 = new mysqli($servername, $username, $password, $dbname_classes);
$sql2 = "SELECT user_id, COUNT(*) AS total FROM ch_documents_list WHERE user_id = $users_id";
$result2 = $conn->query($sql);
$row = mysqli_fetch_assoc($result2);
Then below in the html
<div class='overview-stat'><?php echo $row['total']; ?></div>
Which leads to this:
Notice: Undefined index: total
May this be helpful.
$sql2 = "SELECT COUNT(*) as total FROM ch_documents_list WHERE user_id = $users_id";
$result = mysqli_query($con,$sql2); // $con is Boolean returned from mysqli_connect()
$row = mysqli_fetch_array($result);
echo $row["total"];
Try this code
$query = "SELECT * FROM ch_documents_list WHERE user_id = $users_id ";
$result = mysqli_query($con,$query );
$rows = mysqli_num_rows($result);
print_r($rows);
May not the propper way, but works fine for me since years:
$sql2 = "SELECT user_id COUNT(*) AS total FROM ch_documents_list WHERE user_id = $users_id";
$result = mysqli_fetch_assoc($sql2)
You can then access it with
$result['total']
Using the SQL AS Keyword
Rewrite your query like this below query:
$sql2 = "SELECT user_id, COUNT(*) AS total FROM ch_documents_list WHERE user_id = $users_id";
After that just index your result array using the total key and boom you got your int counts
Like: $result['total']
return int two query example:
1. $sql2 = "SELECT COUNT(user_id) as id FROM ch_documents_list WHERE user_id = $users_id";
**You should return count
mysql_num_rows
**
$conn = mysqli_connect("localhost", "username", "password", "databasename");
$result = mysqli_query($conn, "SELECT user_id FROM ch_documents_list WHERE user_id = $users_id");
$num_rows = mysqli_num_rows($result);
echo "$num_rows Rows\n";
this is mysqli function support
I would like to know if the following is possible, and how:
I want to check if a username in my table appears in 5 or more rows
my table:
Example of usage that I want:
If the name (teste) is on more than 5 rows then do something..
Use HAVING, it allows you to filter by aggregated / manipulated fields
SELECT count(username) as shows_counter from tbl
group by username
HAVING count(username)>5
$check = mysql_query("SELECT count(name),name
FROM hack_log group by name HAVING count(name)>5");
$check = mysql_num_rows($result);// **Add this row**
if($check){ echo "HACKER!"; }else{ echo "not hacker"; }
Please use PDO or mysqli build-in objects
Accorging to your needs
You need to check number of rows
$db = new PDO('mysql:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
$q = $db->prepare('SELECT count(name),name
FROM hack_log group by name HAVING count(name)>5');
$q->execute();
$rows = $q->fetchAll();
$res= count($rows)>0?"Hacker":"No Hacker";
echo $res;
So what I'm trying to do is create a live friends search. To do this I need an array of names for AJAX to search through.
Heres my while loop.
if($_REQUEST['D'] == 'viewfriends') {
$FREINDS = array();
$FRIENDS_QUERY = "SELECT * FROM `FRIENDS` WHERE `USER` = '{$Modules['User']->Username}' AND `STATUS` = 'accepted' ORDER BY `ID` Limit 10 ;";
$FRIENDS_RESULT = mysql_query($FRIENDS_QUERY);
if(mysql_num_rows($FRIENDS_RESULT) > 0) {
while($FRIENDS_ROW = mysql_fetch_assoc($FRIENDS_RESULT)) {
$sql = "SELECT * FROM `USERS` WHERE `USERNAME` = '{$FRIENDS_ROW['FRIEND']}' ;";
$REQUEST_ROW = mysql_fetch_assoc(mysql_query($sql));
$FRIENDS = $REQUEST_ROW['USERNAME'];
}
echo json_encode($FRIENDS);
} else {
echo'<div class="update status">Sorry, You have no friends at this time. sadface.</div>';
}
}
I put the echo $FRIENDS in there as a test, right now it doesn't display anything. Where did I derp?
You can't echo an array. You can use either print_r($friends) to display the whole row of fields requested in the query (you request *)
or you can echo $friends['name'] (depending on how you declared name in your database)
try this:
if($_REQUEST['D'] == 'viewfriends') {
$FRIENDS = array();
$USERNAME = $Modules['User']->Username;
$SQL_QUERY = "SELECT F.*, U.* FROM FRIENDS AS F LEFT JOIN USER AS U ON F.USER = U.USERNAME WHERE F.USERNAME = '{$USERNAME}' AND STATUS = 'accepted' ORDER BY F.ID LIMIT 10";
$RESULTS = mysql_query($SQL_QUERY);
if(mysql_num_rows($RESULTS) > 0) {
while($ROW = mysql_fetch_assoc($RESULTS)) {
$FRIENDS[] = $ROW['USERNAME'];
}
echo json_encode($FRIENDS);
} else {
echo'<div class="update status">Sorry, You have no friends at this time. sadface.</div>';
}
}
$FRIENDS[] = $REQUEST_ROW['USERNAME'];
then print_r($FRIENDS); echo will output array you need to loop the array or echo json_encode($FRIENDS); to see something
also are you sure that USERNAME is uppercase and not just username in lowercase lowercase as well as for the table name.
also i think you can use a JOIN clause instead of making to SQL requests
You have syntax error:
$FREINDS = array(); should be $FRIENDS = array(); .
And also:
$FRIENDS = $REQUEST_ROW['USERNAME'] should be $FRIENDS[] = $REQUEST_ROW['USERNAME']
And
echo $FRIENDS; should be echo json_encode( $FRIENDS );
The PHP won't actually echo out an array. If you do an echo of an array, it outputs "Array". Plus your javascript wouldn't know what to do with a PHP array if it did pass it that way.
Try:
echo(json_encode($FRIENDS));
Also, you should really listen to the feedback in the comments. Your code is very vulnerable to attack and not set up to scale well for such a potentially huge app.
You have a couple of issues that make your code either less secure or less efficient. The most obvious inefficiency is that you are doing a database call inside your while loop, so if someone has 10 friends, that means you've done 11 database queries when you may have only needed one or two. Here are the two queries:
SELECT * FROM `FRIENDS`
WHERE `USER` = '{$Modules['User']->Username}'
AND `STATUS` = 'accepted' ORDER BY `ID` Limit 10
SELECT * FROM `USERS` WHERE `USERNAME` = '{$FRIENDS_ROW['FRIEND']}'
So before we determine if these two can be combined, the first big red flag is the SELECT *. I use it all of the time, but it will get you kicked out of the better database bars. In your case, it's really unnecessary. We know from the second query that the only thing you are using from the first query is the $FRIENDS_ROW['FRIEND'] to match against the USERNAME. So that first query can become:
SELECT FRIEND FROM `FRIENDS`
WHERE `USER` = '{$Modules['User']->Username}'
AND `STATUS` = 'accepted' ORDER BY `ID` Limit 10
You also have the SELECT * in the second query, and we can tell that (for now) the the only thing you are using is the USERNAME, so it can become:
SELECT USERNAME FROM `USERS` WHERE `USERNAME` = '{$FRIENDS_ROW['FRIEND']}'
Finally, we can see from the second query that the FRIEND name and the USERNAME are identical; otherwise why would you query for the usernames where the username equals the friend name. If that's the case, we can drop your second query completely, since we already know the usernames from the first query.
The reason why it's both inefficient and unsafe is because you are using the OG mysql functions, which are clunky and don't offer the option of prepared statements. Prepared statements let you (among other things) put variables in your query in such a way that when you actually call the query, the parts that are variables are known and can thus be sanitized, avoiding the horrors of mysql injections that everyone has mentioned.
I won't bore you with the play-by-play, but here is what your code might look like if you used the newer mysqli library with a prepared statement:
if($_REQUEST['D'] == 'viewfriends') {
$friends = array();
$friend_lookup = $mysqli->prepare("SELECT FRIEND FROM FRIENDS WHERE
USER = ? AND STATUS = 'accepted'
ORDER BY FRIEND");
$friend_lookup -> bind_param('s', $userName);
$userName = $Modules['User']->Username;
$friend_lookup -> execute();
$friend_lookup -> bind_result($friend);
while($friend_lookup -> fetch()) {
$friends[] = $friend;
}
if($friends) {
echo json_encode($friends);
} else {
echo "Sorry, no friends. Boo.";
}
}
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.
What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)