Undefined variable on empty database row - php

I'm getting this annoying error when my database row is empty,
But the rows are supposed to be empty until i add some values to it.
Any clues whats going wrong ? I tried to disable the problem by adding # before the variables but that doesn't work when they are in a foreach loop.
If I add data to the rows, the problems stops....
any ideas ?
some code.
$tweets = new Tweets();
foreach($tweets->fetch_tweets($_GET['uid']) as $tweet){
#$tweet_name = $tweet['username'];
#$tweet_date= $tweet['date'];
#$tweet_email= $tweet['email'];
}
function fetch_tweets($uid){ /*Mine and users I follow*/
$uid = (int)$uid;
$query = $this->link->query("SELECT user.id,
user.email,
user.username,
tweets.message,
tweets.date,
userdetails.profile_img,
userdetails.firstname,
userdetails.lastname,
following.id, following.user_id,
following.follow_id
FROM user
LEFT JOIN following ON user.id = following.user_id
JOIN userdetails ON user.id = userdetails.user_id
JOIN tweets ON userdetails.user_id = tweets.user_id
WHERE user.id='{$uid}' OR
user.id IN (SELECT follow_id
FROM following
WHERE following.user_id = '{$uid}' ) GROUP BY tweets.date ORDER BY tweets.date DESC "
);
$tweet = array();
while(($row = $query->fetch(PDO::FETCH_ASSOC)) !==FALSE) {
$tweet[] = $row;
} echo $query->rowCount();
return $tweet;
}

You need to check if the returned array is empty before you try to use it.
$tweets = new Tweets();
$res = $tweets->fetch_tweets($_GET['uid']);
if( empty($res) ) {
echo "no tweets.";
} else {
foreach($res as $tweet){
$tweet_name = $tweet['username'];
$tweet_date = $tweet['date'];
$tweet_email= $tweet['email'];
}
}
Also, you should always declare your functions before calling them. It's not a requirement in PHP as it is in most other languages, but it makes your code much easier to read.

Just run a code to check if number of rows is 0 before fetching the rows

Related

MySQL count(*) not returning rows with same input

I honestly have no idea what I'm doing with this one, spent atleast 1 hour looking for people with the same issue but couldn't find anything that would suit me / fix my issue.
$auth_user = new USER();
$user_id = $_SESSION['user_session'];
$asd = $auth_user->runQuery("SELECT COUNT(*) FROM ticket_replies WHERE uid=:userid");
$asd->execute(array(':userid'=>$user_id));
$rows = $asd->fetchAll();
$numrows = count($rows);
echo $numrows;
Not even sure if this is correct, but it does return 1 on the page.
$auth_user = new USER();
$user_id = $_SESSION['user_session'];
$asd = $auth_user->runQuery("SELECT uid, count(*) FROM ticket_replies WHERE uid=:uname");
$asd->execute(array(':uname'=>$user_id));
$ticketsrow = $asd->fetchAll();
$count = count($ticketsrow);
foreach($ticketsrow as $row9){
echo $row9['uid'];
}
The code above returns the value of '5' which is one if the values in the table, but obviously I wish for it to return in the 1, 2 & 3 orderly fashion.
Any help is greatly appreciated, thank you.
remove uid from where..
just apply groupBy on uid, i don't know the syntax but in simple sql statement it would be like
SELECT *,count(*) AS count FROM `ticket_replies` group By `uid` order by `count`
remove this also
$numrows = count($rows);
do this
foreach($ticketsrow as $row9){
echo $row9['uid'];
echo $row9['count'];
}
and you are good to go...
Lets fix the issues with your first code block do the following
$auth_user = new USER();
$user_id = $_SESSION['user_session'];
$asd = $auth_user->runQuery("SELECT COUNT(*) AS `count` FROM ticket_replies WHERE uid=:userid");
$asd->execute(array(':userid'=>$user_id));
$rows = $asd->fetchAll();
fetchAll function retuns an array so when you use count($rows) what you get is the size of the array and not the result of the sql statement. To obtain the result of the sql statement you need to do the follow
print_r($rows)
echo $rows[0]['count']; // print the result of the sql
To fix the problem with your second code block do the following
$auth_user = new USER();
$user_id = $_SESSION['user_session'];
$asd = $auth_user->runQuery("SELECT *, COUNT(*) AS `count` FROM ticket_replies GROUP BY `uid` ORDER BY `count`");
$asd->execute();
$ticketsrow = $asd->fetchAll();
print_r($ticketsrow);
foreach($ticketsrow as $row){
echo $row['uid'];
echo $row['count']
}
To get the count from the below query
select count(*) as count from FROM ticket_replies WHERE uid=:uname
Modify your code something like this
echo $ticketsrow[0]['count'];
The above query will always return exactly one row since you are passing userid in the where clause. Or just try to var_dump($ticketsrow) to get clue how to access count.

Count rows in while loop

I am trying to while loop information into a SELECT statement, then COUNT the results. I have tried at least 10 different "solutions" and none works. I only get 0, 1, or nothing. Here's my most recent attempt:
$query35 = "SELECT * FROM movies WHERE userID = $memberID";
$result35 = $db->query($query35);
while ($row35 = $result35->fetchAll(PDO::FETCH_ASSOC)) {
$movie = $row35['movie'];
$query36 = "SELECT COUNT(*) AS similar FROM movies WHERE userID = '$profileID' && movie = '$movie'";
$result36 = $db->query($query36);
$row36->fetchObject;
$similar = $row36['similar'];
echo $similar;
}
$row36->fetchObject;
Seems null object, I think it should be
$row36 = $result36->fetchObject();
If all you are looking to do is count the number of times your loop is run per script execution, then it is fairly simple to do. See below:
$count = 0;
while($row35 = $result35->fetch(PDO::FETCH_ASSOC)){
//Do all your loop stuff.
$count++;
}
var_dump($count);
Important to note that your $count variable needs to be declared outside of your loop.
Also you either need to use fetchAll with a foreach loop, or use fetch with a while loop, but don't mix them.
Also a tip on good practice. Try to avoid as much as possible executing any kind of database querying with a loop, you can run into serious performance issues down the line as your loops get bigger.
Not sure what are you doing. But at least try:
$query35 = "SELECT * FROM movies WHERE userID = $memberID";
$result35 = $db->query($query35);
if ($row35 = $result35->fetchAll(PDO::FETCH_ASSOC))
foreach ($row35 as $row) {
print_r($row);
}
or maybe
$query35 = "SELECT * FROM movies WHERE userID = $memberID";
$result35 = $db->query($query35);
while ($row = $result35->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
$movie = $row['movie'];
$query36 = "SELECT COUNT(*) AS similar FROM movies WHERE userID = '$profileID' && movie = '$movie'";
$result36 = $db->query($query36);
$obj = $result36->fetchObject();
$similar = $obj->similar;
echo $similar;
}

mysql_query inside for loop gives mysql_fetch_assoc related error/warning

Im trying to get the id's of the questions that are answered or asked by particular user and than im trying to use those id's and get questions where id is different from the id's retrieved from the first query.While trying to achieve this im getting an mysql_fetch_assoc() related error/warning and as a result my program crashes.
Following is the code from my DB_Functions.php file where im executing queries on database.
public function getQuestions($username){
$result = mysql_query("SELECT question_id FROM answered WHERE asked_by = '$username' OR answered_by = '$username'");
if($result){
$data = array();
while($row = mysql_fetch_assoc($result)) {
$data[] = array(
$r=$row["question_id"]);}
for($i=0; $i<sizeof($data); $i++){
$result2 = mysql_query("SELECT * FROM answers EXCEPT WHERE question_id='$data[i]'") or die(mysql_error());
return ($result2);
}
}else{
return false;}
}
Following the code located in index.php where im trying to receive the result from DB_Functions.php
if($tag == 'getQuestions'){
$username = $_POST['username'];
$getAllQuestions = $db->getQuestions($username);
$data = array();
while($row = mysql_fetch_assoc($getAllQuestions)) { //I'm getting ERROR on this line
$data[] = array(
$response["getAllQuestions"]["id"] = $row["id"],
$response["getAllQuestions"]["username"] = $row["username"],
$response["getAllQuestions"]["question_id"] = $row["question_id"],
$response["getAllQuestions"]["question"] = $row["question"],
$response["getAllQuestions"]["tag1"] = $row["tag1"],
$response["getAllQuestions"]["tag2"] = $row["tag2"],
$response["getAllQuestions"]["tag3"] = $row["tag3"],
$response["getAllQuestions"]["question_time"] = $row["question_time"]);}
echo json_encode($data);
}
Below is the logcat message:
06-26 21:08:13.920: D/JSON(478): <b>Warning</b>: mysql_fetch_assoc() expects parameter 1 to be resource, null given in <b>C:\xampp\htdocs\android_php_1\index.php</b> on line <b>178</b><br />
Thanks
MySQL does not support the EXCEPT keyword, so the query returns null to $result2 because no result set was formed, which is why you're getting that error. Instead, you can actually consolidate those two queries into one like so:
SELECT
a.*
FROM
answers a
LEFT JOIN
(
SELECT DISTINCT question_id
FROM answered
WHERE ? IN (asked_by, answered_by)
) b ON a.question_id = b.question_id
WHERE
b.question_id IS NULL
In your getQuestions() function, you can replace the whole thing with:
public function getQuestions($username) {
$filtered_username = mysql_real_escape_string($username);
$sql = "
SELECT a.*
FROM answers a
LEFT JOIN
(
SELECT DISTINCT question_id
FROM answered
WHERE '$filtered_username' IN (asked_by, answered_by)
) b ON a.question_id = b.question_id
WHERE b.question_id IS NULL";
return mysql_query($sql) ?: false;
}
Also note that your previous code was vulnerable to SQL injection. In my solution, I first passed the username variable through mysql_real_escape_string() to prevent that (not as good as prepared statements, but still better than nothing). NEVER pass user-input directly into a query.

adding values into an array using a while loop

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.";
}
}

MySQL Query not calling data based on variable

Im trying to call all users from a database with the same interests as the current, logged in user on my website.
I have the following
// Get Session USER interest
$interestsquery = "SELECT `interest` FROM `user_interests` WHERE `user_id` = " . $usersClass->userID();
$result = mysql_query($interestsquery);
$interests = array();
while(list($interest) = mysql_fetch_array($result))
$interests[] = $interest;
$interest1 = $interests['1'];
$interest2 = $interests['2'];
$interest3 = $interests['0'];
// END INTERESTS
//USers with Same Interests
$interests_query = "SELECT * FROM produgg_users
join user_interests on produgg_users.id = user_interests.user_id
where interest = '$interest1' and produgg_users.id != '".$usersClass->userID()."'";
$interests_result = mysql_query($interests_query) or die(mysql_error());
if($interests_result != 0) {
while($interests_row = mysql_fetch_array($interests_result, MYSQL_ASSOC))
{
echo $interests_row['user_id'];
}
}
else
{
print "No users to display!";
}
//END SAME INTERESTS
which doesnt bring back any data, yet if I add (beneath //USers with Same Interests)
$interest1 = 'footy';
the interests_query seems to work, can anybody see where im going wrong?
My problem seems to lie here...
$interest1 = $interests['1'];
$interest2 = $interests['2'];
$interest3 = $interests['0'];
// END INTERESTS
//USers with Same Interests
$interest1 = 'footy';
If I manually assign a value to $interest variable it works, but i need to get use the value from the array above, does this make sense?
If your code brings back the correct data when you add $interest1 = 'footy'; line, that would imply that there is something wrong with the value of that variable when you don't. Have you tried var_dump($interest1); right under //Users with Same Interests line to see what kind of input you get from your interestsquery?
I would expect the var_dump to not return a valid string (since if it would, the query would work following the $interest1 = 'footy'; assumption), so you would have to look at what interestsquery returns wrong.
Looks like you querying user_id from user_interests as number, but from produgg_users as string. Maybe there's a problem
You can do it with one query:
$userID = mysql_real_escape_string($usersClass->userID());
$sql = "
SELECT * FROM user_interests AS ui1
JOIN LEFT user_interests AS ui2 ON ui1.id = ui2.id
JOIN LEFT produgg_users AS pu ON ui2.user_id = pu.id
WHERE ui.user_id = " . userID ;

Categories