I need someone to help me with this problem. My head doesn't want to think straight today.
So, i have a table named "recensions", and another named "comments". In each table, i have a column named "amne_id". This would make so i could connect the comments to the correct recension.
Now, on my first page, i simply get all the recensions with the code:
$rec = $this->db->get('recensions');
What i want is to count how many comments each recension has. But i have no idea how. I guess i maybe should use JOIN and num_rows()?
Please ask if you dont understand, so i can explain better.
Have a nice day!
$this->db->select('COUNT(*) as count, recensions.anme_id as recension_id')
->from('recensions')
->join('comments','recensions.anme_id = comments.anme_id','left')
->group_by('anme_id');
$result = $this->db->get();
Should give you the recensions id and the comment count for that id.
then loop:
foreach($result->result() as $row){
echo "Recension id $row->recension_id has $row->count comments<br />";
}
Like this??
$sql = mysql_query("SELECT * FROM recensions");
while($row = mysql_fetch_array($sql)){
$amne_id = $row{"amne_id"};
$sql2 = mysql_query("SELECT * FROM comments WHERE amne_id='$amne_id'");
$total_comments = mysql_num_rows($sql2);
echo $total_comments;
}
I don't know about the database connector you are using, but in pure SQL (assuming the connection recensions.id=comments.anme_id connection), try this:
SELECT COUNT(comments.id), anme_id
FROM recensions
LEFT JOIN comments on comments.anme_id=recensions.id
GROUP BY anme_id
Related
I have looked all over and at tons of code and examples.. This is such a small bit of code but I just can't seem to get it to work.
I have dbo.accounts which contains the id, username, password, createtime..
I have a simple form, you type in the username, and I need the select query to return the ID based on the username.
$result = mssql_query('SELECT id FROM dbo.account WHERE name = $username');
The dbo.gamemoney table will just insert some hardcoded info such as an amount of coins for the game..
My problem is that if I use a query as ID = 123, it works, but when I try to grab the id of dbo.accounts by using the username, I get nothing back.
I know it has to be something small, But I have tried to figure it out for so many hours now that I'm honestly lost..
Thanks for your time,
Chris
Since, $username is string type, you have to enclose it in quotes.
$result = mssql_query("SELECT id FROM dbo.account WHERE name = '$username'");
As a better practice would suggest use a try-catch scenario so that you get the exact error log. Try -
$result = mssql_query('SELECT id FROM dbo.account WHERE name = "'.$username.'"') or die('MSSQL error: ' . mssql_get_last_message());
Thanks everyone for the help!
I was able to get it working. Now I'll make sure it's the right way. I had forgot to add,
while($row = mssql_fetch_array($result)) {
$id = $row['id'];
$ip = $row['ip'];
}
Thats why the id was blank. I was missing some code.
Chris
I am trying to get a date from my database, but only when certain conditions are met.
I want a table to populate with data from mySQL, only when the data is submitted under a users name. (i.e. this data is relevant to this user.)
This data has been saved as a TIMESTAMP.
$sql = "SELECT * FROM bug LIMIT 100";
$result = mysql_query($sql)or die(mysql_error());
while($row = mysql_fetch_array($result)){
$bdate = $row['bugDate'];
$bfor = $row['bugFor'];
$finduserid= mysql_query
("SELECT UserId FROM user WHERE userName='{$_SESSION['myusername']}'");
if($finduserid)
{
$getuserid = mysql_fetch_assoc($finduserid);
}
$findbdate =
mysql_query("SELECT bugDate FROM bug WHERE bugDate = '$bdate'
AND '$bfor' = '" . $getuserid['UserId'] . "'");
if($findbdate)
{
$getbdate = mysql_fetch_array($findbdate);
}
$bdatetime = new DateTime($getbdate['bugDate']);
$formattedbdate = date_format($bdatetime, 'd,M Y');
If anyone can help me I'd greatly appreciate it.
Obviously the security is terrible and I'm pretty sure this method would be the most inefficient way of doing what I'm trying to do, however I'm a noob and kind of learning by doing. If you have some noob friendly documentation on security and seeing this is making you cringe, feel free to post a link. Any help is greatly appreciated.
(Let me know if you need to know more and sorry if I didn't include it in the first place!)
EDIT: I got it working. I was doing it the most roundabout, ridiculous way anyone could come up with. Although I didn't use JOIN it sent me on the right path. Condensed 250 lines of pointless not working code down to 3-4 that will be obvious to everyone but me.
I selected the row where my session login equalled my loginName on the database.
$finduserid= "SELECT UserId FROM user WHERE userName='{$_SESSION['myusername']}'";
$runuserid = mysql_query($finduserid)or die(mysql_error());
while($getuserid = mysql_fetch_array($runuserid)){
$userid = $getuserid['0'];
}
I then, only Selected records that included my username (instead of everything and then trying to get rid of everything that didn't have my username in it.) -_- (Im an idiot.)
$sql = "SELECT * FROM bug WHERE bugFor = '$userid'";
$result = mysql_query($sql)or die(mysql_error());
Read up on JOINs.
I can't exactly tell what your code is supposed to do, or completely decipher your DB's schema, but the below query should get all bugs for the current user that were filed on the given date:
SELECT b.*
FROM bug b INNER JOIN users u
ON b.bfor = u.userID
WHERE u.userName = '{$_SESSION['myusername']}'
AND b.bugDate = '$bdate'
Is there any way to take the contents of my while query below and use it elsewhere in my php script ?. What I am trying to do is collect the answers from a quiz and then compare them to the correct answers, the problem I am having is that the answers come from one table and the questions from another, so I am currently having to run two different while queries, but I cant use $quiz in the 2nd query as it just stays fixed with the last value it spat out. What im basically trying to do it load table A, look inside for the questionID, select that table and pull out the correct answer. Then load table B, looking inside that, select the answer with the same questionID and then use an if statement to compare to to, so that if correctanswer = actualanswer = correct , and loop over this for each question. The main problem that im coming up against though is the first while pulls out all the correct answers just fine, but I cant then use that in the other while to compare too. Im not sure if this is the correct way of doing it, or if there is a better way ?.
LOOK FOR THE CORRECT ANSWER :
$result0 = mysql_query("SELECT * FROM itsnb_chronoforms_data_createquestions
WHERE quizID='$quizID' ORDER BY cf_id ASC");
while($row0 = mysql_fetch_array($result0))
{
$answer = $row0['correctanswer'];
}
LOOK FOR THE ACTUAL ANSWER SUBMITTED :
$result = mysql_query("SELECT * FROM itsnb_chronoforms_data_answerquiz
WHERE quizID='$quizID' AND userID='$userID' ORDER BY cf_id ASC");
while($row = mysql_fetch_array($result))
{
$quiz = $row['quizselectanswer'];
}
Join is propably the best way to do this. But you could also use the php in_array()-Function:
$result0 = mysql_query("SELECT * FROM itsnb_chronoforms_data_createquestions WHERE quizID='$quizID' ORDER BY cf_id ASC");
while($row0 = mysql_fetch_array($result0))
{
$answers[] = $row0['correctanswer'];
}
And Then
$result = mysql_query("SELECT * FROM itsnb_chronoforms_data_answerquiz WHERE quizID='$quizID' AND userID='$userID' ORDER BY cf_id ASC");
while($row = mysql_fetch_array($result))
{
if(in_array($row['quizselectanswer'],$answers)){
...correct...
break;
}
}
SELECT * FROM itsnb_chronoforms_data_answerquiz a, itsnb_chronoforms_data_createquestions
q WHERE a.quizID='$quizID' AND a.userID='$userID' and q.quizID=a.quizID and
a.quizselectanswer = q.correctanswer
Should return all the correct answers. If you also want the wrong answers, you need to do a outer join on the two tables.
I have small PHP script which has
$query = "SELECT MAX(id) FROM `dbs`";
//query run
$row = mysql_fetch_array($result);
$val = $row[0];
Which runs fine, but I want to understand why i can't access the row with the fieldname, like if i have this
$query = "SELECT id FROM `dbs`";
i am able to use the folowing
$val = $row['id'];
but whenever i use this MAX() function, i have to change to
$val = $row[0];
to access the values
I have no clue about this. Any help would be appreciated. Thankss
You need to give it an alias:
<?php
$query = "SELECT MAX(id) AS `id` FROM `dbs`";
//query run
$row = mysql_fetch_array($result);
$val = $row['id'];
Edit:
To explain this it's probably best to show an example of a different query:
SELECT MAX(`id`) AS `maxId`, `id` FROM `dbs`
Using the above it will return as many rows are in the table, with 2 columns - id and maxId (although maxId will be the same in each row due to the nature of the function).
Without giving it an alias MYSQL doesn't know what to call it, so it won't have an associative name given to it when you return the results.
Hope that helps to explain it.
SELECT MAX(id) AS myFieldNameForMaxValue
FROM `dbs`
and then
$row = mysql_fetch_array($result);
$val = $row['myFieldNameForMaxValue'];
If you run this query on mysql commandline you'll see that the field name returned by mysql is MAX(id). Try running on phpmyadmin and you'll see the same. So if you try $row['MAX(id)'] it'll work. When using a mysql function, it gets added to the name, so use an alias, like other said here, and you're good to go: SELECT MAX(id) AS id FROM dbs. Also, never forget to use the ` chars, just in case you have some columns/tables with reserved names, likefrom`.
i got a fairly simple layout going and for the life of me i cant figure out why this returns nothing:
<?php
// Gets A List Of Comic Arcs
$result = mysql_query("SELECT * FROM ".$db_tbl_comics." GROUP BY ".$db_fld_comics_arc." ORDER BY ".$db_fld_comics_date." DESC LIMIT 20");
while ($comic = mysql_fetch_array($result)) {
// Now Go Back And Count Issues For Each Comic Arc Above
$result22 = mysql_query("SELECT * FROM ".$db_tbl_comics." WHERE ".$db_fld_comics_arc."=".$comic[$db_fld_comics_arc]);
$total_issues = mysql_num_rows($result22);
echo $total_issues;
}
?>
No other query is refered to as $result22.
$comic[] has already been defined in the previous query.
echo mysql_error($result22); returns no errors.
Let me know if you need any other info.
I am assuming that the column $db_fld_comics_arc is a string.
Change:
$result22 = mysql_query("SELECT * FROM ".$db_tbl_comics." WHERE ".$db_fld_comics_arc."=".$comic[$db_fld_comics_arc]);
To:
$result22 = mysql_query("SELECT * FROM ".$db_tbl_comics." WHERE ".$db_fld_comics_arc."='".$comic[$db_fld_comics_arc]."'");
Am I wrong? If so, let me know the table structure, and what your error reporting is set to.
Also, could you let us know the purpose of your SQL? It may also be possible to put the data together in one query, instead of looping sql queries through, and using data from a first query.
Maybe it is because $db_fld_comics_arc is in $comic[$db_fld_comics_arc]
if both are the same then you should try replacing $db_fld_camics_arc with $comic[$db_fld_comics_arc].