Building unread_message counter ends in resource id error - php

Trying to get the unread messages from my database with this function, but I end in resource id errors like this one: "Resource id #45"
function unread_message_count() {
$sql = "SELECT conversations_messages.message_id, conversations_members.user_id, conversations_members.conversation_last_view, conversations_messages.message_date
FROM conversations_members
INNER JOIN conversations_messages ON conversations_messages.user_id = conversations_members.user_id
WHERE conversations_members.conversation_last_view < conversations_messages.message_date AND conversations_members.user_id = {$_SESSION['user_id']}";
$result = mysql_query($sql);
return $result;
}
I call the function this way, but to nothing prints:
$count = unread_message_count();
echo $count;

mysql_query() returns a resource on success, or FALSE on error, you need to fetch the data from results, like:
...
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
return $rows;
Btw, mysql_ is deprecated, MySQLi or PDO_MySQL extension should be used.

mysql_query() returns a resource. The to string (implicitly triggered by using echo to output it) of that is Resource ID # followed by the id.
A resource in PHP is only supposed to be used with other PHP functions. This includes but is not limited to file, curl, ftp handles, etc.
use mysql_fetch_array() (or similar)
Just Try this
function unread_message_count() {
$sql = "SELECT conversations_messages.message_id, conversations_members.user_id, conversations_members.conversation_last_view, conversations_messages.message_date
FROM conversations_members
INNER JOIN conversations_messages ON conversations_messages.user_id = conversations_members.user_id
WHERE conversations_members.conversation_last_view < conversations_messages.message_date AND conversations_members.user_id = {$_SESSION['user_id']}";
$result = mysql_query($sql);
$data = mysql_num_rows($result);
return $data;
}

Related

mysqli_multi_query() - Returns true instead of returning data

So, I have written some query code returns the error:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
I understand that this is caused to a boolean response from the query, and I have checked it out, and the Boolean returned is equal to true. So I don't see why there is no response with a data array instead... Here's my code:
$data = mysqli_multi_query($connection, 'UPDATE teams SET teams.teamViews = teams.TeamViews
+ 1 WHERE (teams.teamID, \''.$userToken.'\') NOT IN (SELECT teams_views.teamId,
teams_views.'.$viewType.' FROM teams_views) AND teams.teamUrl = \''.TEAM_URL.'\';
INSERT INTO teams_views (teamId, '.$viewType.') SELECT t.teamId, \''.$userToken.'\'
FROM teams t WHERE t.teamUrl = \''.TEAM_URL.'\' AND NOT EXISTS (SELECT \''.$userToken.'\'
FROM teams_views WHERE t.teamId = teamId);
SELECT * FROM teams WHERE teams.teamUrl = \''.TEAM_URL.'\';');
$dataRow = mysqli_fetch_array($data, MYSQLI_ASSOC);
There are three queries in the SQL - An update, insert, and selection.
How could I alter my query or PHP to return data, rather than a boolean? Thanks
As suggested in a comment by spencer7593, my question was solved using a combination of mysqli_store_result, mysqli_free_result, and mysqli_next_result. The following is the function used to do this:
function multi_queries($query, $numQueries) {
$connection = new database_connection();
$data = mysqli_multi_query($connection->connection, $query) or die(mysqli_error($connection->connection));
$data = mysqli_store_result($connection->connection);
if (sizeof($data) > 0) {
$this->success = true;
do {
if ($result = mysqli_store_result($connection->connection)) {
while ($row = mysqli_fetch_row($result)) {
$this->data[sizeof($this->data)] = $row;
}
mysqli_free_result($result);
}
} while (mysqli_next_result($connection->connection));
}
$connection->close_connection();
}

PHP code mysql query isnt working

I created a mysql query to check if user is banned or not and if he's the system give him return false. But it wont get the information.
public static function checkban($username)
{
if(LOGINCHECKBAN == false)
{
$vusername = engine::securyt($username);
$getIdBYname = "SELECT id FROM players WHERE username='".$vusername."' LIMIT 1";
$getNOW = mysql_query($getIdBYname);
$IDbyNAME = mysql_free_result($getIdBYname);
$queryforban = mysql_query("SELECT * FROM bans WHERE data = '".$IDbyNAME."' LIMIT 1");
$query = mysql_num_rows($queryforban);
if($query == 0) {
return true;
} else {
return false;
}
}
}
Note: engine::securyt($username) is the form type to get his username when he try to login.
What can be wrong on my code?
edit: I belive that "mysql_free_result" can be the problem, but im not sure what i need to put on replace of it.
mysql_free_result() frees a mysql result set. It does not actually retrieve data from the result.
You will want something like:
$getIdBYname = "SELECT id FROM players WHERE username='".$vusername."' LIMIT 1";
$result = mysql_query($getIdBYname);
$row = mysql_fetch_assoc($result);
if($row) { //a user was found
//$row['id'] is the found user
$result = mysql_query("SELECT COUNT(*) cnt FROM bans WHERE data = '". $row['id'] ."' LIMIT 1");
$row = mysql_fetch_assoc($result);
return ($row && $row['cnt'] == 0);
} else {
// no user; return something appropriate
}
However, if all you need is to determine is whether a particular user name is banned (and not actually get their user id), you can do that directly in the database with one query:
SELECT COUNT(*)
FROM players p
INNER JOIN bans b ON b.data = p.id
WHERE p.username = $username;
WARNING: Note that using mysql_* functions is strongly discouraged for new code (since mysql_* has been removed in PHP 7), and directly including variables in your query strings is a pretty major security vulnerability. You should look into using prepared statements/parameterized queries with mysqli or PDO.

Couldn't get data from another table in MySQL

I am currently trying to get a data(M_Name) from a table called Merchant.
Following are my codes:
<?php
$response = array();
$link = mysql_connect('localhost','root','') or die ('Could not connect: '.mysql_error());
mysql_select_db('ichop') or die ('Could not connect to database');
$result = mysql_query("select * from offer") or die(mysql_error());
if(mysql_num_rows($result) > 0){
$response["offers"] = array();
while($row = mysql_fetch_array($result)){
$offer = array();
$offer["offer_id"] = $row["Offer_ID"];
$offer["start_date"] = $row["Start_Date"];
$offer["end_date"] = $row["End_Date"];
$offer["o_desc"] = $row["O_Desc"];
$offer["short_desc"] = $row["Short_Desc"];
$offer["merchant_ID"] = $row["Merchant_ID"];
$offer["m_name"] = mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'");
array_push($response["offers"], $offer);
}
$response["success"] = 1;
echo json_encode($response);
} else {
//no offer found
$response["success"] = 0;
$response["message"] = "No offer found";
echo json_encode($response);
}
?>
When I run this PHP file using web browser, I couldn't get the desired name for the merchant even though the data is there in the database...it would just return me "null".
{"offers":[{"offer_id":"1","start_date":"2013-05-17","end_date":"2013-05-18","o_desc":"AAA","merchant_ID":"2","m_name":null}],"success":1}
What have I done wrong or what am I still missing? Please help..thanks!
I would rather use LEFT JOIN mysql function and get all relevant data at first query from both of your tables
SELECT * FROM offer a LEFT JOIN MERCHANT b ON a.Merchant_ID = b.MERCHANT_ID
so you won't have to make any extra query and you can store your value directly in your array
$offer["m_name"] = $row['M_Name'];
Then I would like you to remember that mysql_* functions are deprecated so i would advise you to switch to mysqli or PDO
The mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'"); does not return a value from the DB, you need to follow it up with for example mysql_fetch_array like you did with the other query to the DB.
There is a solution more simple: use a JOIN, which combines two tables.
SELECT offer.*, MERCHANT.M_Name
FROM offer
LEFT JOIN MERCHANT ON(MERCHANT.MERCHANT_ID = offer.merchant_ID)
look like you have to return an result from query instead of while,
mysql_fetch_array(mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'"));
but had better you make some error hadling first
You can use below one
$resMerchant = mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'");
$rowMerchant = mysql_fetch_assoc($resMerchant);
$offer["m_name"] = $rowMerchant['M_Name'];
$offer["m_name"] = mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'")
mysql_query() does not return a string but a resource. You'll have to fetch the result.
Also, don't forget that mysql_* is now deprecated.
[edit]
As stated by Fabio, you'd rather use JOIN on your query. At the moment, you are making a request in your loop. That's useless (INNER JOIN or LEFT JOIN are what you want) and very resource consumming.

php functions within functions

ihave created a simple project to help me get to grips with php and mysql, but have run into a minor issue, i have a working solution but would like to understand why i cannot run this code successfully this way, ill explain:
i have a function,
function fetch_all_movies(){
global $connection;
$query = 'select distinct * FROM `'.TABLE_MOVIE.'` ORDER BY movieName ASC';
$stmt = mysqli_prepare($connection,$query);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt,$id,$name,$genre,$date,$year);
while(mysqli_stmt_fetch($stmt)){
$editUrl = "index.php?a=editMovie&movieId=".$id."";
$delUrl = "index.php?a=delMovie&movieId=".$id."";
echo "<tr><td>".$id."</td><td>".$name."</td><td>".$date."</td><td>".get_actors($id)."</td><td>Edit | Delete</td></tr>";
}
}
this fetches all the movies in my db, then i wish to get the count of actors for each film, so i pass in the get_actors($id) function which gets the movie id and then gives me the count of how many actors are realted to a film.
here is the function for that:
function get_actors($movieId){
global $connection;
$query = 'SELECT DISTINCT COUNT(*) FROM `'.TABLE_ACTORS.'` WHERE movieId = "'.$movieId.'"';
$result = mysqli_query($connection,$query);
$row = mysqli_fetch_array($result);
return $row[0];
}
the functions both work perfect when called separately, i just would like to understand when i pass the function inside a function i get this warning:
Warning: mysqli_fetch_array() expects
parameter 1 to be mysqli_result,
boolean given in
/Applications/MAMP/htdocs/movie_db/includes/functions.inc.php
on line 287
could anyone help me understand why?
many thanks.
mysqli_query failed to run your query:
Returns FALSE on failure. For
successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will
return a result object. For other
successful queries mysqli_query() will
return TRUE.
Before running mysqli_fetch_array test $result... Something like:
if ($result !== false)
$row = mysqli_fetch_array($result);
else
return false;
Seems like a variable scope issue within your SQL statement. Outputting the SQL should show you the "true" error.
You may want to try using classes with your functions, for example:
class getInfo {
function fetch_all_movies(){
global $connection;
$query = 'select distinct * FROM `'.TABLE_MOVIE.'` ORDER BY movieName ASC';
$stmt = mysqli_prepare($connection,$query);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt,$id,$name,$genre,$date,$year);
while(mysqli_stmt_fetch($stmt)){
$editUrl = "index.php?a=editMovie&movieId=".$id."";
$delUrl = "index.php?a=delMovie&movieId=".$id."";
echo "<tr><td>".$id."</td><td>".$name."</td><td>".$date."</td><td>".get_actors($id)."</td><td>Edit | Delete</td></tr>";
}
}
function get_actors($movieId){
global $connection;
$query = 'SELECT DISTINCT COUNT(*) FROM `'.TABLE_ACTORS.'` WHERE movieId = "'.$movieId.'"';
$result = mysqli_query($connection,$query);
$row = mysqli_fetch_array($result);
return $row[0];
}
}
$showInfo = new getInfo;
//fetch all movies
$showInfo->fetch_all_movies();
//List actors from movie 1
$showInfo->get_actors("1");
In case of an error mysqli_query will return false. You have to handle the error a simple way to do this might be:
$result = mysqli_query($connection,$query);
if (!$result) {
die(mysqli_error($connection));
}
$row = mysqli_fetch_array($result);
Please note that terminating (by doing die() ) usually is no good way to react on an error, log it, give the user anice error page etc. It's alsonogood practice to give the low level error message toauser, this might motivate users to try to exploit a possile security issue.
Last remark: you were writing
$query = 'SELECT DISTINCT COUNT(*) FROM `'.TABLE_ACTORS.'` WHERE movieId = "'.$movieId.'"';
you should properly escape the movieId there.

How can I store the result of an SQL COUNT statement in a PHP variable

I want to get the number of rows in my MySQL table and store that number in a php variable. This is the code I'm using:
$size = #mysql_query("SELECT COUNT(*) FROM News");
$size ends up being "Resource ID #7." How do I put the number of rows directly into $size?
mysql_query returns a query resource id. In order to get values from it you need to use mysql_fetch_assoc on the resource id to fetch a row into an array.
$result = mysql_query("SELECT COUNT(*) FROM News");
$row = mysql_fetch_assoc($result);
$size = $row['COUNT(*)'];
You need to call mysql_fetch_row or one of its sister functions.
<?php
// untested
$result = #mysql_query("SELECT COUNT(*) FROM News");
// error handling
$row = mysql_fetch_row($result);
$count = $row[0];
?>
try the following:
$size = #mysql_query("SELECT COUNT(*) AS `total` FROM News");
$query = mysql_fetch_array($size);
echo $query['total'];
On a related note you can use the mysql_num_rows() function to obtain the number of rows from a given query. This is handy if you need to grab the data but also know the number of rows.
<?php
$result = #mysql_query("SELECT * FROM news");
$count = #mysql_num_rows($result);
?>

Categories