I have query that COUNT the data based from user search condition in search.
My question is just simple although I don't know what the solution here:
I want to call the COUNT column, which I know it was just temporary column
I have PHP code like this:
$count = mysql_query("SELECT *, COUNT(*) AS SAMPLECOUNT FROM `subscribers` WHERE `country` = 'USA' ");
$row=mysql_fetch_array($count);
so by this code I can echo the columns inside the subscribers by using this:
echo $row['country'];
*echo the count result here*
So maybe the output will be like this:
USA: (the count result)
As requested
Since you're using an alias COUNT(*) AS SAMPLECOUNT you pass it along in the $row's array as
echo $row['SAMPLECOUNT'];
in order to show the row count's number.
Here are a few references:
http://www.mysqltutorial.org/mysql-alias/
https://dev.mysql.com/doc/refman/5.6/en/select.html
Sidenote: Aliases are case-sensitive on *NIX, but not so on Windows or Mac OSX”.
So echo $row['samplecount']; could fail if on *NIX.
However and quoting this answer https://stackoverflow.com/a/2009011/ on Stack:
"On Unix, table names are case sensitive. On Windows, they are not. Fun, isn't it? Kinda like their respective file systems. Do you think it's a coincidence?
In other words, if you are planning on deploying on a Linux machine, better test your SQL against a Linux-based MySQL too, or be prepared for mysterious "table not found" errors at prod time. VMs are cheap these days.
Field names are case-insensitive regardless."
Related
I'm trying to run an SQL query with PDO
This works
$result = $dbo->query("SELECT sum(c) as scfus
FROM tbl
WHERE
YEAR(ondate)=YEAR('".$_POST['startdate']."')
AND MONTH(ondate)=MONTH('".$_POST['startdate']."')
AND DAY(ondate)=$i");
but this does not
$result = $dbo->query("SELECT a,b,sum(c) as scfus
FROM tbl
WHERE
YEAR(ondate)=YEAR('".$_POST['startdate']."')
AND MONTH(ondate)=MONTH('".$_POST['startdate']."')
AND DAY(ondate)=$i");
The only difference is the addition of the a,b column names to the query.
I can run this query (both of them) directly into mysql and get a single record back, as expected, but PDO does not seem to like column names AND sum in the same query?
I can't see a reason, or solution. New to PDO, so was never an issue for me before.
Thanks.
UPDATE - OK, I still think this should work fine, but as a workaround, I've run 2 sql statements, almost exactly the same. One with SELECT SUM(x), one with SELECT a,b, but without the sum. Works fine, but I really should be able to do it in one statement, unless I'm into some PDO limitation I'm not aware of yet.
you might need to GROUP BY c (or whatever column you may want to group domain aggregate function SUM() by) in order to obtain the desired result-set... and maybe take the suggestion above into account.
Try it this way for your query, worked for me for what you want to achieve :
$result = $dbo->query("SELECT a,b,(SELECT sum(c) as whateverFROM tbl),
as scfus
FROM tbl
WHERE
YEAR(ondate)=YEAR('".$_POST['startdate']."')
AND MONTH(ondate)=MONTH('".$_POST['startdate']."')
AND DAY(ondate)=$i");
SUM returns only one line so you'll never get all your results and only the ones of the first matching WHERE criterias (it registers first record found, then only count what it needs).
It will work
Oh, btw, make a timestamp of the date, make a string of the date post in the date sql format and check
WHERE date = $_POST['date']
will work
SELECT a, b , (SELECT SUM(ID)*30 FROM table) FROM table WHERE ID = SOME(SELECT ID FROM tables WHERE users_ID = idYouWant);
I wrote a simple PHP script to provide me some data, but I can't get all the columns to be shown ( as a JSON string), but in the PHPmyadmin frontend for the latest MariaDB all columns are shown. The interesting thing about this error is that through the same script another query (different POST variable value) shows all the expected columns. Also the order gets messed up in the first query.
My result in the PHP script:
{"id":"2","name":"it","mail":"john.doe#contoso.com","surname":"john"}
Expected result (also shown in Phpmyadmin as rows in the correct query order):
{"id":"2","name":"john","surname":"doe", "department":"it","mail":"john.doe#contoso.com"}
The order error I can fix with some dirty tricks (last option), but the columns are the real problem. Is there a column limit in MariaDB or/and PHP? I am not sure what to look for to resolve this error.
PS: I googled around and someone on the official MariaDB site says there is a 1000(I am using the same storage engine) column limit. I also checked
while($r = mysqli_fetch_assoc($sth))
{
$rows[] = $r;
}
and
while($r = mysqli_fetch_array($sth)){$rows[] = $r;}
The second option gives me everything I would like to receive, still it isn't the desired result because, everything is duplicated. The only lines after this loop are
echo json_encode($rows);
mysqli_close($link);?>
What the I and and the community discovered:
1.$rows[0] = $r; >>displays only one record, but still not in the correct format.
array_push($rows,$r); >> does not do the trick.
echo json_encode($rows[0]); and print_r($rows[0]) >> {"ID":"6","Name":"IT Department","Surname":"Doe","Email":"john.doe#contoso.com","DeparmentRole":"Maintanacei","Available":"Everyday from 8am to 17pm","Phone Number":"44 1206 256000","Office":"A1-Maitanance","CompanyRank":"standard employee"} and same for the print_r.
So a close observation did the trick. I created a two tables with the same column name. It is nothing wrong when we have two columns, but when we join them we can have a real mess, the original column has been overwritten by the joined one, what also explained, why the order was messed up.
So remember
Having two columns in tables that can "be on their own" is OK, but when joining them ALL columns MUST HAVE an UNIQUE name. What I do not understand, why the AS keyword failed to display it with an alias and took the regular column name.
I have the following MySQL query:
SELECT * FROM users WHERE name LIKE '%jack%'
I want it to order by how much it's like jack so
jack
jacker
majack
I can also use PHP.
I think you can accomplish what you want by using full text search function in mysql. Your query will be like this:
SELECT name, MATCH (name) AGAINST ('jack') as score
FROM users ORDER BY score DESC;
There are some conditions you need to take into consideration when using full search text:
The mysql engine should support this functions. I think InnoDB 5.6 and MYISAM 5.5 support that.
You have to add a FULLTEXT index in your table definition.
You can see a working demo here: http://sqlfiddle.com/#!9/72bf5/1
More info about full search text in MySQL here: http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html
Also, here is a working example I wrote on PHP using similar_text and sorting array functions: http://ideone.com/UQpBFk
Hope it helps!
I don't think you can do this kind of thing with plain SQL. The first thing you need to do is define what it means for two strings to be similar, for which there are various metrics. You should probably pick one of those and write a stored procedure to sift through the data.
As every one mentioned, you can't achieve this using normal way other than using full text search but if you know all the different pattern before hand then you can use FIELD function to achieve something which resemble a approx result like
SELECT * FROM users WHERE name LIKE '%jack%'
ORDER BY FIELD (name,'jack','jacker','majack')
Try something like this:
$query = mysql_query("SELECT * FROM users WHERE name LIKE '%jack%' ORDER BY name ASC ");
while($fetchdata=mysql_fetch_array($query))
{
echo $fetchdata["name"] ;
}
I have two arrays. Each is being pulled from MySQL via the following;
$query ="SELECT country,";
$query.="GROUP_CONCAT(report) AS reports, ";
$query.="GROUP_CONCAT(topic) AS topics, ";
$query.="FROM reports GROUP BY country";
So, it is giving me two strings like this:
reports[$i] = 2011-05-11 A,2011-05-11 B,2011-05-11 C
topics[$i] = A,B,C
And it is working just fine, however, when the reports string is getting too long, MySQL just truncates it, and then I am throwing
Warning: array_multisort(): Array sizes are inconsistent
Becuse I am exploding the string down the line.
Obviously this is ruining my program. But I don't know what to do, I am kind of in a crisis, because my boss said he was going to have the whole company start to use it. How can I make MySQL not truncate results?
Set group_concat_max_len to higher value.
Personally, I would rewrite code not to use group_concat function, but retreive all records instead.
group_concat_max_len is set in the mysql configuration file by the way. You'll need to restart mysql afterward.
I have an app that works with an idea of "redemption codes" (schema: ID, NAME, USES, CODE). And example would be "32, Stack Overflow, 75, 75%67-15hyh"
So this code is given to the SO community, let's say, and it has 75 redemptions. You redeem it by entering some shipping info and the code. When entered, this check is preformed:
if (code exists){
if (count_entries_where_code=$code < $uses_set_at_creation){
//enter information into DB for processing
{
//echo "sorry, not a real code"
}
So the number of total uses is hardcoded, but the current # of redemptions is generated with a SQL query (count_results from entry_data WHERE code=$code). This part works fine, but here is the question:
At the view page where I manage the codes, I have the basic setup (in pseudo PHP, with the real code separated into an MVC setup):
$results = "SELECT * FROM codes";
foreach ($result as $code){
echo $code->code;
echo $code->name;
//etc. It's actually all in a nice HTML table.
}
So I want to have a column listing "# of uses remaining on code". Should something like this be stored in the DB, and drawn out that way? It would be easier to generate with the foreach loop, but I don't usually prefer to store "generated" statistics like that. Is there a clever way to get those results onto the correct rows of the table created with the foreach loop?
(I'm fine with code so I don't need a working/great syntax example, just an explanation of a pattern that might fit this problem, and maybe a discussion of a common design for something like this. Am I right to avoid storing generate-able data like # of uses left? etc.)
Am I right to avoid storing generate-able data like # of uses left?
Yes, you are correct to not store computed values.
Computation logic can change, and working with a stored computed value to reverse engineer it can be a nightmare - if it is possible at all in some cases.
It sounds like you want to combine the two queries:
SELECT c.id,
c.name,
c.uses,
c.code,
x.num_used
FROM CODES c
JOIN (SELECT ed.code,
COUNT(*) 'num_used'
FROM ENTRY_DATA ed
GROUP BY ed.code) x ON x.code = c.code
When you run your query to get the codes for the page add a subquery to get the number of used codes from the entry_data table.
select codes.id, codes.name, codes.uses, codes.code (select count(code) from entry_data where entry_data.code=codes.code ) as used_codes
Id use code_id as a foreign key and not code.
This is all assuming i'm reading your problem correctly