Array From database - php

I'm not keen on how to make an array from database. Tried to avoid learning those but apparently it's in need for now.
Basically my database is structured with millions of rows. Player Name and Snap (Unix TimeStamp) are usually "duplicated" but with different data in those rows (city, x, y, etc).
Ideally, trying to figure out HOW to make an array via SELECT statement, something like:
Output, I would like would be something like:
Name = Snap => (how many city on those day), Snap => (how many city on another day).. so on..
Question here is, what's the proper array "command" (if you call that) to pull the name ONCE and pull multiple snap with the counts based on the snap.
My SELECT goes:
// SELECT count(*), player, snap
// FROM DB WHERE GROUP BY snap, player ORDER BY snap, player DESC
while ($row = fetch_assoc($Result) {
// How you go about putting array here?
}

It'll be done like this:
$Result = mysql_query("SELECT count(*) as count, player,
snap FROM DB GROUP BY snap, player ORDER BY snap, player DESC");
while ($row = mysql_fetch_array($Result) {
print_r( $row );
echo "This is the count value -> " . $row['count'];
}

I agree with the comment about needing to read up a little more on the basics, but you can do something like the following, to create your multidimensional array:
<?php
$results = array();
$Result = 'SELECT count(*),player,snap FROM DB WHERE GROUP BY snap,player ORDER BY snap,player DESC';
while ($row = fetch_assoc($Result){
if (!isset($results[$row['player']][$row['snap']]) {
$results[$row['player']][$row['snap']] = 0;
}
$results[$row['player']][$row['snap']] += $row['count(*)'];
}
?>

Try these first:-
http://phpsense.com/2006/php-mysql/
http://www.freewebmasterhelp.com/tutorials/phpmysql
You need basics on SQL as well.

You can try
$sql = "SELECT count(*) as count, player,
snap FROM DB GROUP BY snap, player ORDER BY snap, player DESC";
/* Connect To Database */
$mysqli = new mysqli ( "localhost", "username", "password", "database" );
/* check connection */
if ($mysqli->connect_errno) {
printf ( "Connect failed: %s\n", $mysqli->connect_error );
exit ();
}
$result = $mysqli->query ( $sql );
$array = array();
if ($result) {
while ( $row = $mysqli->fetch_assoc ( $result ) ) {
$array[$row['player']] += $row['count'];
}
print_r($array); // Return array
}

Related

How to echo the result of count(*) AS in PHP?

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);

Php stuck because to long load on mysqli query in php function, how to fix?

i'm using a php function to get dome mysql data from other mysql host than my webserver.
Function:
public function theMysqli($build){ // $build is given by othe code (no usedata)
$mysqli = new mysqli($server, $user, $password, $database);
$catid = array( /* +/- 40 id's */ ); //data is $catid = configs::songcats();
$type = array( /* +/- 15 captical letters */ ); //data is $type = configs::songtype();
$limit = 20;
$lstart = $_post['page'];
if($lstart == ''){
$lstart = 0;
}
else{
$lstart = $lstart * $limit;
}
$sletter = $_POST['letter'];
$search = $sletter.'%';
$catquery = "SELECT songid FROM category WHERE catID IN('".implode("', '", $catid)."')";
if ($db = $mysqli->query($catquery)){
while($row = $db->fetch_array()){
$idsong[] = $row;
}
$db->close();
}
foreach($idsong as $gt){
$songid[] = $gt['songid'];
}
// songid is a array over the 30000 values
$countquery = "SELECT id FROM songlist WHERE songtype IN('".implode("', '", $type)."') AND id IN('".implode("', '", $songid)."') AND songname LIKE '".$search."'";
if ($db = $mysqli->query($countquery)){
$countr = $db->num_rows;
$db->close();
}
$pages = ceil($countr / $limit);
$songquery = "SELECT id, songname, artist, copyright, duration FROM songlist WHERE songtype IN('".implode("', '", $type)."') AND id IN('".implode("', '", $songid)."') AND songname LIKE '".$search."' ORDER BY songname ASC LIMIT $lstart, $limit";
if ($db = $mysqli->query($songquery)){
while($row2 = $db->fetch_array()){
$result[] = $row2;
}
$db->close();
}
if($built == 'counter'){
$final == $pages;
}
else if($build == 'gresult'){
$final == $result;
}
return $final;
}
Now my problem is the load time he need for this script it will be to long. Even when i set php.ini so that execute may be 300sec he will stuck by loading the page. Now i know you can get data grom mutiple mysql tables by one query but i can't find any solution to do that in combination with php implode function.
Total rows i must get by $_POST['letter'] M is +/- 1200; (web radio mp3 database)
Can someone help me to fix this function so i get no timeout's anymore.
Thanks
The problem here is that you're fetching a list from the database, and then sending that list back as part of a query. You should really be doing most of this stuff in SQL, using either JOIN or nested queries. This will make your program much faster.
First, create a table for all of your catids and types. Your catquery should then be:
SELECT songid
FROM category
WHERE catID IN (
SELECT id
FROM catids
)
Use the same sort of pattern to join your queries together. It looks like you can cut down most of your code here to just one SQL query. You'll save a ton of time and memory by not having to send all that data back and forth between your program and the database.
Some reading material for you:
SQL Joins: http://beginner-sql-tutorial.com/sql-joins.htm
SQL Subquery: http://beginner-sql-tutorial.com/sql-subquery.htm

'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.

mysql queries which is the best

i want to know which way is better (faster) from those sql methods;
1st method:
public static function getlistusers($limit=88888888888888 ) {
$sql = "SELECT id,name FROM users order by id desc limit 0,$limit";
$st = mysql_query( $sql ) or die(mysql_error());
$list = array();
while ( $row = mysql_fetch_assoc($st) ) {
$picss = new users( $row );
$list[] = $picss;
}
return ( array ( "users" => $list) );
#mysql_free_result($st);
for print output i use
foreach() the array $users ;
2nd method
$sql = "SELECT id,name FROM users order by id desc limit 0,$limit";
$st = mysql_query( $sql ) or die(mysql_error());
while ( $row = mysql_fetch_assoc($st) ) {
extract($row);
return "Id: $id and The Name is : $name";
}
#mysql_free_result($st);
}
===========
i want to know which is faster and safty for sql load.
Regards
Al3in
$sql = "SELECT id,name FROM users order by id desc limit 0,$limit";
$st = mysql_query( $sql ) or die(mysql_error());
while ( $row = mysql_fetch_assoc($st) ) {
extract($row);
return "Id: $id and The Name is : $name";
}
#mysql_free_result($st);
I doubt this approach will even work. Because, even though you limit it to 1 or a million, the loop will only run once because of return "Id: $id and The Name is : $name"; . So if you're comparing this and the other method, the other method would obviously work better.
Unless you're assigning to an array instead of returning. In which case the second method has an unnecessary function call extract which puts two variables into the heap.
Both are essentially the same. They execute the same query and retreive the results in the same way. The advantage of the first method is that it returns a list of data arrays that each represent a records in the database. All individual can be used any way you want. The second approach returns only a single string. The entire while loop is useless there.
So the second may be faster, because it only retrieves a single row, but from here that looks more like an error than like an actual implementation decision.

Simple way to read single record from MySQL

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 :)

Categories