This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How do i “echo” a “Resource id #6” from a MySql response in PHP?
I have a statement:
$query1 = mysql_query("SELECT COUNT(author) FROM userpages WHERE `author` = '" . $userid . "'") or die();
echo $query1;
Ignore the amazingly awful naming convention their, its just for testing it before i beef it up. Because im not actually getting data from the table i should just be able to echo the statement shouldnt i? However its giving me an error.
The error is: Resource id #4
Any advice?
Thanks.
mysql_query returns a resultset resource, you have to loop through the resultset using
mysql_fetch_array($query1)
(or similar) to retrieve each record. It doesn't matter whether the query returns 1 row or 100,000 rows, the principle is the same
please read the relevant sections of the manual that explain this in great detail before feeling the need to ask for help.... reading the manual is your friend!
EDIT
while ($row = mysql_fetch_array($res,MYSQL_ASSOC)) {
echo $row['COUNT(author)'];
}
or change your SQL query to
$query1 = mysql_query("SELECT COUNT(author) AS authorcount FROM userpages WHERE `author` = '" . $userid . "'") or die();
and then
$row = mysql_fetch_array($res,MYSQL_ASSOC))
will return an array with an index of 'authorcount'
echo $row['authorcount'];
http://www.php.net/manual/en/function.mysql-query.php
Returned values:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, mysql_query() returns a resource on success, or FALSE on
error.
And:
The returned result resource should be passed to mysql_fetch_array(),
and other functions for dealing with result tables, to access the
returned data.
I think, this will be helpfull
$query = "SELECT COUNT(author) as cnt FROM userpages WHERE `author` = '" . $userid . "'";
echo $query;
$res = mysql_query($query);
while ($row = mysql_fetch_array($res,MYSQL_ASSOC)) {
print_r($row);
}
Related
I am a novice when it comes to PHP but I don't understand if my syntax is wrong in this statement, or how would I grab an int from my MySQL server.
I know that my server credentials are working fine. How would I fix this statement to give me a returned integer of the number of reviews in the userinfo table?
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$amountofreviews = $numberofpreviousreviews + 1;
$query2 = mysql_query("ALTER TABLE userinfo ADD `amountofreviews` VARCHAR(10000)") or die(mysql_error()); //Make another column in database for the new review
You need to fetch your results after you run your query. There are several ways to do this but using mysql_fetch_assoc() will work for you.
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$row = mysql_fetch_assoc($numberofpreviousreviews);
$amountofreviews = $row['number_of_reviews'] + 1;
FYI, you shouldn't be using mysql_* functions anymore. They are deprecated and going away. You should use mysqli or PDO.
Assume you have a table userinfo which has the following structure and data :
Scenario #1 :
If you want to retrieve the all number_of_reviews, then do like this,
$query = "SELECT `number_of_reviews` FROM `userinfo`";
$result = mysqli_query($db,$query);
while ($row = mysqli_fetch_assoc($result)) {
echo "Number of reviews : " . $row['number_of_reviews'] . "<br/>";
}
It will give you,
Number of reviews : 20
Number of reviews : 40
Since, the result has many rows, it will display like above.
Scenario #2:
If you want to retrieve only the specific number_of_reviews for some user id (which is unique). I take id as 1 as a example here. Then do like,
$query2 = "SELECT `number_of_reviews` FROM `userinfo` WHERE `id` = 1";
$result2 = mysqli_query($db,$query2);
while ($row2 = mysqli_fetch_assoc($result2)) {
echo $row2['number_of_reviews'] . "<br/>";
}
This will print,
20.
Because, number_of_reviews is 20 for id 1.
I have some code which selects data from a row. It is working and prints the result correctly, but I have an error I can not figure out.
$rs=array();
$select=array ("system_name", "location", "alarmtype", "severity", "start_time", "end_time", "duration", "reason","shift_oparation", "system_oparation");
for ($i=0;$i<=9;$i++){
$SQL = "SELECT (".$select[$i].") FROM (".$is.") WHERE duration=('".$ic."') AND location=('".$id."')";
$result = mysql_query($SQL);
$db_field = mysql_fetch_array($result);
$rs[$i]=$db_field[$select[$i]];
echo $rs[$i];
}
Echo prints correctly, but there is an error:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given.
I think some of your queries dont return anything. In order to get rid of the warning you should check if the $result was in fact a resource.
Try this:
$rs=array();
$select=array ("system_name", "location", "alarmtype", "severity", "start_time", "end_time", "duration", "reason","shift_oparation", "system_oparation");
for ($i=0;$i<=9;$i++){
$SQL = "SELECT (".$select[$i].") FROM (".$is.") WHERE duration=('".$ic."') AND location=('".$id."')";
$result = mysql_query($SQL);
if($result){
$db_field = mysql_fetch_array($result);
$rs[$i]=$db_field[$select[$i]];
echo $rs[$i];
}
}
However, your code will be a lot more efficient if you use only one query.
You are doing something really strange. It looks like $select is a list of columns in a table, and you are fetching them one column at a time!
You can select them all at once, with this query:
$sql = "SELECT system_name, location, alarmtype, severity,
start_time, end_time, duration, reason, shift_oparation, system_oparation
FROM " . $is . " WHERE duration = '" . $ic . "' AND location = '" . $id . "'";
Note I've removed some extraneous parenthesis you had. Also be very careful with building SQL queries dynamically like this. I'm assuming you know the values of $is, $ic, and $id to be safe from SQL injection attacks,
Run the result, and then iterate over the row array
$result = mysql_query($sql);
if ($result)
{
$row = mysql_fetch_array($result); //fetches the first result row as an array
// Can be accessed like $row['system_name']
foreach ($row as $key => $value)
echo $key, " = ", $value;
}
else
die(mysql_error() . $sql);
If the result is false, it will perform the die statement and print out the error returned from MySQL and also the query we built, so you can see if it looks correct.
Warning: mysql_fetch_array() expects parameter 1 to be resource,
boolean given in.
This means that mysql query produced errors .
Return Values
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, mysql_query() returns a resource on success, or FALSE on
error.
Use mysql_error to display teh error and see why it happened.
e.g.
if(!$result){
echo mysql_error();
}
Protip: donlt use mysql libraries as noted in php manual
there is problem in select statement please check the select query or you can run individual select query and check the output
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How do i “echo” a “Resource id #6” from a MySql response in PHP?
Hey guys, I got an error when I try to run my code in PHP.
It displays resource id #53 in my screen. All I want is to count only the total of one of my field but I'm stuck with this error. Here's my code below:
$last_points = mysql_insert_id();
//echo $last_points , display like 12... no error
$fkid = $last_points; // no error....
$sql = "SELECT COUNT(*) FROM downline WHERE fkmember = {$fkid}";
$execute = mysql_query($sql) or die (mysql_error());
echo $execute; //display error why?
Help me guys please. I think it's my query.
First off, resource id #53 is not an error. You are displaying a resource, not the output of the query.
To show the output, use:
$last_points = mysql_insert_id();
//echo $last_points , display like 12... no error
$fkid = $last_points; // no error....
$sql = "SELECT COUNT(*) FROM downline WHERE fkmember = {$fkid}";
$execute = mysql_query($sql) or die (mysql_error());
print_r(mysql_fetch_array($execute)); //display error why?
Secondly, the mysql_* functions are deprecated. You should look into learning and utilising the mysqli or PDO libraries accordingly.
Instead of trying to echo a resultset(as received because of mysql_query) do this:
print_r( mysql_fetch_array($execute) );
$execute is an array so you need to print it among echoing it
print_r($execute);
By codeigniter way
In Model:
function getCount($fkid)
{
$Qry = "SELECT * FROM downline WHERE fkmember = $fkid};
$query = $this->db->query($Qry);
return $query->num_rows();
}
In controller:
echo $Count = $this->modelname->getCount($id);
I am trying to read in an XML file and compare it to fields in an existing database.
If the ID in the database doesn't exist in the XML file, then the whole row corresponding to the Id is no longer valid and will be deleted.
To do this I read in each line of the XML from start to finish in a while statement.
As step one I am trying to do a simple compare, and echo if it finds an Id in the database that doesn't exist in the XML.
I know there are some Ids in the database that don't exist in the XML, but the following code is not displaying them.
I've got three questions, firstly how would I display the Id that is pulled from the database, and secondly why isn't this code finding any ids that are not in the XML?
The final question is am I going about this completely the wrong way and is there a better way to do it!
$sql_result = mysql_query("SELECT id FROM `list` WHERE id = $id") or die(mysql_error());
if($sql_result)
{
// echo $id . " Id exists " . $sql_result["id"] . "\n";
}
else
{
echo "Id no longer exists" . $id . "\n";
}
Your code isn't finding what you expect because even though the id may not be found, $sql_result still holds a TRUE value because the query was successful. Instead, check if myqsl_num_rows() > 0
if($mysql_num_rows($sql_result) > 0)
{
// echo $id . " Id exists "\n";
//Now, to print the id, you need to fetch it from `$sql_result`,
//which is just a resource at this point:
$row = mysql_fetch_assoc($sql_result);
echo $row['id'];
}
This is the proper way to check:
$sql_result = mysql_query("SELECT `id` FROM `list` WHERE `id` = ".intval($id,10)." LIMIT 0,1");
if(is_resource($sql_result) && mysql_num_rows($sql_result) > 0 ){
$sql_result = mysql_fetch_assoc($sql_result);
echo $id . " Id exists " . $sql_result["id"] . "\n";
}
else{
echo "Id no longer exists" . $id . "\n";
}
You should check the number of rows returned using mysql_num_rows(). Otherwise, you are simply checking to see if the query executed without any error.
if($sql_result)
to
if(mysql_num_rows($sql_result))
You can use NOT IN() on your select with the IDs that exist on you XML like:
SELECT id FROM `list` WHERE id NOT IN($your_id_list)
With this you'll have a list of IDs that are not in the list.
Your IDs must be separated with a comma like:
SELECT id FROM `list` WHERE id NOT IN(123,654,987,45)
Question 1: how would I display the Id that is pulled from the database?
$sql_result = mysql_query("SELECT `id` FROM `list` WHERE `id` = $id") or die(mysql_error());
$sql_row = mysql_fetch_assoc($sql_result);
if(!empty($sql_row['id'])) {
echo "Id exists - " . $sql_row['id'] . "\n";
} else {
echo "Id no longer exists - " . $sql_row['id'] . "\n";
}
Question 2: why isn't this code finding any ids that are not in the XML?
I think in your code the if() condition will always return true irrespective if the Id exists in the database or not. And secondly as you might have guessed from my code above, you are missing to fetch the data from the SQL resultset
Question 3: am I going about this completely the wrong way and is there a better way to do it?
You are doing it the right way by browsing through the XML and checking each entry in the database for existence. A better way might be to first retrieve all IDs from the XML and then use them in the single SQL query:
SELECT `id` FROM `list` WHERE `id` NOT IN ($list);
Please note that this query might run slow if there are a very large number of IDs in the XML file, say a few hundreds.
mysql_num_rows()
Or
SELECT COUNT(*) [...]
I'm running the following query, expecting it to return an INTEGER, but it returns "Resource id #3"
What am I doing wrong?
$queryPlans = mysql_query("SELECT count(*) FROM infostash.rooms");
echo $queryPlans;
There are actually 15 rows in this table, and I would like to return the number 15.
Any suggestions?
mysql_query will return a php resource(see: http://www.php.net/manual/en/language.types.resource.php).
The returned resource should then be passed to mysql_fetch_assoc or similar.
Since you are only getting the count, you can use the following:
$queryPlans = mysql_query("SELECT count(*) FROM infostash.rooms");
$count = mysql_result($queryPlans,0,0);
echo $count;
You need:
$queryPlans = mysql_query("SELECT count(*) FROM infostash.rooms");
$row = mysql_fetch_array($queryPlans);
echo $row[0];
mysql_query() isn't returning the result. It's returning a resource you can loop across and interrogate for rows (as above).
This is actually expected behavior according to the documentation:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
It's a regular select that returns one row with one column and should be treated as such. You can call mysql_fetch_array on the result:
$row = mysql_fetch_array($resource);
$count = $row[0];
mysql_query() returns a result resource. You need another function the get "valuable information" from that resource. In this case mysql_fetch_array()/mysql_fetch_row()/mysql_fetch_object as cletus pointed out. Or (since it's only a single value) mysql_result().
Any sql query may fail for various reasons. You should always check the return value of mysql_query(). If it's FALSE something went wrong and mysql_error() can tell you more about it.
$mysql = mysql_connect(...) or die(mysql_error());
mysql_selecT_db(.., $mysql) or die(mysql_error($mysql));
$query = "SELECT count(*) FROM infostash.rooms";
$queryPlans = mysql_query($query, $mysql) or die(mysql_error($mysql));
$cRows = mysql_result($queryPlans, 0);
echo $cRows;
If you are planning on using the full query later (e.g. select , rather than count()), you can save yourself a database hit by using mysql_num_rows() on the full query. Example:
$queryPlans = mysql_query("SELECT * FROM infostash.rooms");
$results = mysql_fetch_array($queryPlans);
echo "There were " . mysql_num_rows($queryPlans) . " results";
while($row = mysql_fetch_assoc($queryPlans)){
// Do stuff here
}
$queryPlans = mysql_query("SELECT count(*) FROM infostash.rooms");
mysql_num_rows($queryPlans);
http://us.php.net/manual/en/function.mysql-num-rows.php