Call to a member function rowCount() on a non-object - php

Im having a problem with my query. I recently switched to PDO, which is kind of new to me. Now i need to use JOIN in my query to get data from another table without making two executions.
Problem is, i get this error:
Call to a member function rowCount() on a non-object
I don't understand what the problem is. This is how my code looks like:
$friends_string = "SELECT * FROM `friends` as F, `users` as U WHERE `F.userID` = '$sess_user' AND `F.request` = '0' AND `F.friendID` = 'U.id'";
$friends = $db->query($friends_string);
if ($friends->rowCount() > 0) {
while($row = $friends->fetch(PDO::FETCH_ASSOC)) {
echo "<br /><a href='profile.php?id={$row["id"]}'>{$row["friendID"]}</a>";
}
} else {
echo "no Friends";
}
Or for short, just the query:
SELECT * FROM `friends` as F, `users` as U WHERE `F.userID` = '$sess_user' AND `F.request` = '0' AND `F.friendID` = 'U.id'
What I want is, get all rows from friends where userID is session and request is 0. But then i want to get the ID of those friends in users so i can make a link to their profile. Note the $row["id"]
I appreciate any feedback, doesn't have to answer my questions, if you note any problem please comment it. Thanks!

Don't put back ticks around the `table.field` ... You have to put them around `table`.`field`

Change your query with this one:
$query = "SELECT * FROM `friends` as F INNER JOIN `users` as U ON `F.friendID` = `U.id` WHERE `F.userID` = '{$sess_user}' AND `F.request` = '0'";
And add this to your connection, it will show you the errors:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception

IMHO!
I saw problems like that with PDO...
and...
i think it's more likely to do all with pure SQL but good then duck your head with PDO.

Related

Using MySQL LIMIT in query after using FILTER_SANITIZE_NUMBER_INT

I'm kinda new on this one, and I'm building my first website. Just for fun and to learn how everything works.
I have this weird issue, I can't figure out how to do it:
$query = "SELECT * from artikel inner join categorie on artikel.artikelnummer = categorie.artikelnummer
inner join categorienaam on categorie.categorienummer = categorienaam.categorienummer
left join bestandsnaam on artikel.artikelnummer = bestandsnaam.artikelnummer
where categorie.categorienummer = ".filter_var($_GET['categorienummer'], FILTER_SANITIZE_NUMBER_INT)." LIMIT $first_product_shown, $products_per_page";
while($row = mysqli_fetch_assoc($query))
{
do stuff
}
It works when I'm not using the LIMIT. But I don't know how to get this limit to work. For example, this one works:
$query = mysqli_query($conn, "SELECT * FROM artikel LEFT JOIN bestandsnaam ON artikel.artikelnummer = bestandsnaam.artikelnummer LIMIT $first_product_shown, $products_per_page");
while($row = mysqli_fetch_assoc($query))
{
do stuff
}
I think my code fails because of the combined use of 'FILTER_SANITIZED_NUMBER_INT' and 'LIMIT'. Maybe anyone knows what the problem is? I need this to get my products on my website splitted into pages.
Thanks in advance!
Your code is failing because you appear to be missing the query call in the first code block. Try echoing out the mysqli error
In your second block you have called the SQL inside the query directly, but not in the first and have not added the query.

JOIN MySQL doesn't work

I've tried everything, but nothing works.. Even in an other code I wrote, it works. But for some reason it won't now.
I want to join two tables where the ID = userID. When I load the page, I get this error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL
result resource in
/home/ynxwleus/domains/mustseenmovies.nl/public_html/films/userinfo.php
on line 17
Is there anyone who can help me with this problem?
Code:
$userID = $_SESSION['s_userID'];
echo $userID;
$query = "SELECT userID, userName, userFrontname, userSurname, filmID
FROM users
JOIN seenIt
ON users.userID = seenIt.userID
WHERE (userID ='$userID')";
$res = mysql_query($query);
while ($row = mysql_fetch_array($res)) {
echo $row['userName'];
echo $row['userFrontname'];
echo $row['userSurname'];
echo $row['filmID'];
}
Thanks in advanced!
Your where clause needs an alias:
WHERE (users.userID ='$userID')
Your select clause also needs an alias on the userId:
SELECT users.serID, userName, userFrontname, userSurname, filmID
In fact, it is a really good idea to ALWAYS use aliases:
SELECT u.userID, u.userName, u.userFrontname, u.userSurname, si.filmID
FROM users u join
seenIt si
ON u.userID = si.userID
WHERE u.userID ='$userID'
The original query has syntax errors, because the SQL engine does not know which userID is being referred to. Oh, you are thinking "that's obvious because on clause specifies that the values are the same." Well, humans are smarter than SQL compilers, at least when it comes to common sense.
If your query returns an error, then mysql_query returns a boolean false. You can print out this error using mysql_error().
$res = mysql_query($query) or die(mysql_error());
Additionally, mysql_fetch_row will not work on a boolean, so you get the compilation error.
Your query has an error, as Gordon pointed out.
Additionally, I would suggest to not use mysql anymore, since it is deprecated. Use MySQLi, or PDO instead.
$query = "SELECT userID, userName, userFrontname, userSurname, filmID
FROM users
JOIN seenIt
WHERE users.userID = seenIt.userID
AND users.userID = ".$userID." ";

Count comments to each recension?

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

PHP & MySQL: How can I use "SET #rank=0;" in $query=

In my PHP file, I use this line to pull data from my mySQL database:
$query = "SET #rank=0; SELECT #rank:=#rank +1 as rank, Blah Blah...";
If I check the SELECT statement in phpMyAdmin's SQL window (without $query= ) it works fine.
But, if I use it in PHP, then I get an error. It doesn't like the "SET #rank=0;" bit. Is there a way to use "SET #rank=0;" when it's in "$query=" ? Is there a workaround?
The rest of the code is standard stuff for pulling data from a db:
public function getmyData() {
$mysql = mysql_connect(connection stuff);
$query = "SELECT #rank:=#rank +1 as rank, formatted_school_name, blah blah";
$result = mysql_query($query);
$ret = array();
while ($row = mysql_fetch_object($result)) {
$tmp = new VOmyData1();
$tmp->stuff1 = $row-> stuff1;
$tmp->stuff2 = $row->stuff2;
$ret[] = $tmp;
}
mysql_free_result($result);
return $ret;
}
Update: I'm trying to use Amerb's suggestion of using multi-query. I concatenated the query like so:
$query = "SET #rank = 0";
$query .= "SELECT #rank:=#rank +1 as rank...
I changed the result to:
$result = $mysqli_multi_query($query);
But, it's failing for some reason. I'm on a machine running PHP 5.2. Any suggestions?
This guy here seems to have a way of setting the variable in the same query to zero. I don't have MySQL set on up on this machine to try it, though.
Here's the query he suggests in his blog post:
select #rownum:=#rownum+1 ‘rank’, p.* from player p, (SELECT #rownum:=0) r order by score desc limit 10;
(Is there some homework assignment coming due somewhere having to do with computing ranks? This is the third question I've seen on this in two days.)
Are you checking for duplicate scores?
Try executing it as 2 separate successive queries.
You have to enable the use of multiple queries in one, but i forgot how do do this at the moment. It's a security feature.
Use mysql_multi_query() or rather mysqli_multi_query() instead of mysql_query()

PHP/SQL SELECT statement using asterisk

I am having trouble getting an sql request to work. Without giving more details than needed,
$db_query = mysql_query(" select years,avg,best,win,top10,champs from `profile` where PLAYERID = '$monkey_id'");
works fine. However,
$db_query = mysql_query(" select * from `profile` where PLAYERID = '$monkey_id'");
doesn't return any results. The only change is that I'm trying to pull all fields instead of just those few. I'm at a loss to explain this. I taught myself all this stuff, so it's always possible I'm doing something dumb.
Edit:
Here's the rest of the surrounding code:
$db_query_inside = mysql_query(" select * from `profile` where PLAYERID = $monkey_id");
$db_query = mysql_fetch_array($db_query_inside);
$years_prev = $db_query['years'];
$avg_prev = $db_query['avg'];
$best_prev = $db_query['best'];
$win_prev = $db_query['win'];
$top10_prev = $db_query['top10'];
$champs_prev = $db_query['champs'];
Edit again:
Still don't know why it wouldn't work with *, but I just got what I needed done by listing the specific fields. It doesn't end up with any sort of error that can be gleaned from
die(mysql_error())
so I'm just giving up and working on stuff that reacts rationally.
Why not try:
$db_query = mysql_query(" select `profile` where PLAYERID = '$monkey_id'");
Let's do this, modify the following line to reflect below. See what the error says, if any. I tried it myself (your code) and it seems to work fine.
$db_query_inside = mysql_query(" select * from `profile` where PLAYERID = $monkey_id") or die(mysql_error());

Categories