mysql_num_rows() expects parameter 1 to be resource, php error - php

I am getting this error accessing my site. I have used the same files for three different servers, including my local server and it's running fine. Can someone shed some lights?
$stringIp = $_SERVER['REMOTE_ADDR'];
$intIp = ip2long($stringIp);
$inDB = #mysql_query("SELECT 1 FROM av_whoIsOnline WHERE ip=".$intIp);
if(!mysql_num_rows($inDB)) //CODE IN QUESTION <---------
{
if($_COOKIE['geoData'])
{
list($city,$countryName,$countryAbbrev) = explode('|',mysql_real_escape_string(strip_tags($_COOKIE['geoData'])));
}
else
{
$xml = file_get_contents('http://api.hostip.info/?ip='.$stringIp);
$city = get_tag('gml:name',$xml);
$city = $city[1];
$countryName = get_tag('countryName',$xml);
$countryName = $countryName[0];
$countryAbbrev = get_tag('countryAbbrev',$xml);
$countryAbbrev = $countryAbbrev[0];
setcookie('geoData',$city.'|'.$countryName.'|'.$countryAbbrev, time()+60*60*24*30,'/');
}
$countryName = str_replace('(Unknown Country?)','UNKNOWN',$countryName);
if (!$countryName)
{
$countryName='UNKNOWN';
$countryAbbrev='XX';
$city='(Unknown City?)';
}

Take out the # sign before #mysql_query. This obviously suppresses errors. If you do get an error, $inDB will not be a valid resource, so you will get the error you are getting. Your problem is most likely in the line before.
Also note that the mysql library has been deprecated in favour of mysqli and PDO. Consider changing your code to use one of the newer libraries since they are safer

It's working now. Thanks for the replies.
This was an online script I grabbed from the net awhile back. I've changed host using the same script and got this error. After I uploaded the db, I've deleted any entries in 'av_whoIsOnline'. Then the error occurred. Inserted back the entries and error is gone.
My db connection is located in another file.

Related

mysqli_affected_rows return -1 but update query is successful

I have a page of php code take user's new password string to change user password and after some validation code send to process page for update record in users table. after sending new password string to process page and doing the update query, mysqli_affected_rows return -1 but update query was successful and password was changed Or If previous password string was the same previous password, update query does not make any changes but still returns -1.
I use mysqli functions in all of my codes.
db_conncet_fnc(),db_query_func(),db_fetch_assoc_func(),... These functions include the same mysqli functions.
my proccess page code is this:
$link_con=db_conncet_fnc();
require_once("PassHash.php");
$query = "SELECT * FROM mdr WHERE m_id='$md_id'";
$result = db_query_func($query);
$affecteds= mysqli_affected_rows($link_con);
$_SESSION["affecteds"]=$affecteds; //this is for test before UPDATE query
$_SESSION["affected-s-oop"]=$link_con->affected_rows; //this is for test before UPDATE query
$rec = db_fetch_assoc_func($result);
$p_hasher = new PassHsh(25, FALSE);
$ans = "2"; //answer without error is 2
if($rec)
{
if ($pass != "" && $newpsw != "" && $check = $p_hasher->checkpss($newpsw, $rec["userpass"])) {
if ($chngpsw_err < 2) {
$_SESSION["chngpsw_err"] = "has";
}
$_SESSION["pass_nwpass_is_equal"] = "yes";
header("location:index.php?page=chngpass");
exit();
} elseif ($check = $p_hasher->checkpss($pass, $rec["userpass"])) {
$hashed_psw = $p_hasher->HashPassword($newpsw);
$query = "UPDATE `mdr` SET `userpass`='$hashed_psw' WHERE m_id='" . $md_id . "' ";
$result = db_query_func($query);
$affect_upd = mysqli_affected_rows($link_con);
$_SESSION["affect_upd"] = $affect_upd; //by function
$_SESSION["affect_upd-oop"] = $link_con->affected_rows; //by object
if ($affect_upd == 0) {
$_SESSION["update_result"] = "err0";
header("location: index.php?page=chngpass");
exit();
}
if ($affect_upd == -1) {
$_SESSION["update_result"] = "err-1";
header("location: index.php?page=chngpass");
exit();
}
if ($affect_upd > 0) {
$_SESSION["update_result"] = "ok";
header("location: index.php?page=chngpass");
exit();
}
} else {
$ans = "1";
header("location: index.php?page=chngpass&ans=$ans");
}
}
I found some questions about this in stackoverflow and google and discussed about bug in mysqli with xdebug like this https://bugs.php.net/bug.php?id=67348 but I dont use $connect->stat and some pages wrote about bug in mysqli for every where xdebug is enabled, So I disable xdebug in php.ini but mysqli_affected_rows return -1 in all states and events, and all positions yet.
I used Google Chrome for debugging with phpstorme before.
Should I disable something in Chrome?
update:(2018/08/01):
After a few days searching on various sites by Google and searching in stackoverflow and doing the steps and suggestions written, I couldnt solve it.
A person named "siddharaj solanki" wrote in this question:
mysqli_affected_rows creates new connection (read details)
wrote:
Now the problem is I don't understand how to pass database link
($link) in mysqli_affected_rows() function. I tried above, but it
seems to create a new database connection, so mysqli_affected_rows
returns 0 instead of 1.
So I think the bug will not easily solve for this function based on my research and this link:
https://www.google.com/search?q=bug+mysqli_affected_rows
please guide me whats solution or what is good or best way instead of mysqli_affected_rows to check update query?
good time
Please help me to resolve that.
thanks.
The comments above do explain what's wrong, but I'll summarize here and mark this a community wiki answer.
Your code creates a connection to the database, but you said your db_query_func() function creates a separate connection to the database to run the query.
The affected-rows count can only report the rows affected by a query in the same connection. But you executed the UPDATE in a different connection.
Consider this analogy: you open two separate ssh sessions to a remote server. You run a command in one shell, and then in the other shell you use !! to repeat the command. The second shell has no idea of the command history from the first shell, so it can't repeat the same command.
You need to use the same database connection to execute the query and then report the rows-affected. Maybe the comments above did not make this clear, but you can solve this by passing the connection to your query function:
$result = db_query_func($link_con, $query);
Within that function, do not create a new mysqli connection, but use the connection that you passed as an argument.
Then when it returns, it has the proper context so you can get the mysqli_affected_rows($link_con) from the same connection.
There are other alternative solutions possible:
It's not clear why you need the db_query_func() at all. Perhaps you should just call mysqli_query() from your main code.
Or else db_query_func() should call mysqli_affected_rows() itself, and return the value.

Wordpress: 500 Internal Server Error, probable issue using $wpdb

I'm using Wordpress and I'm performing a query which gives me back this error:
Failed to load resource: the server responded with a status of 500
(Internal Server Error)
My query looks like:
global $wpdb;
$session_uid = isset($_POST["session_uid"]) ? trim(strip_tags($_POST["session_uid"])) : "";
$the_data = isset($_POST["the_data"]) ? trim(strip_tags($_POST["the_data"])) : "";
$ss = "select * from ".$wpdb->prefix."vp_pms_messages inner join ".$wpdb->prefix."vp_pms_group_users on ".$wpdb->prefix."vp_pms_messages.id = ".$wpdb->prefix."vp_pms_group_users.message_id and ".$wpdb->prefix."vp_pms_messages.group_id = ".$wpdb->prefix."vp_pms_group_users.group_id where ".$wpdb->prefix."vp_pms_group_users.from_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.from_del = '0' or ".$wpdb->prefix."vp_pms_group_users.to_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.to_del = '0' group by ".$wpdb->prefix."vp_pms_messages.group_id";
$check_last_conversation = $wpdb->get_results($ss);
$response = print $check_last_conversation;
I'm probably missing or misunderstanding something but if I comment out $check_last_conversation and I print something like "Hello", the error goes away.
This is ok:
global $wpdb;
$session_uid = isset($_POST["session_uid"]) ? trim(strip_tags($_POST["session_uid"])) : "";
$the_data = isset($_POST["the_data"]) ? trim(strip_tags($_POST["the_data"])) : "";
//$ss = "select * from ".$wpdb->prefix."vp_pms_messages inner join ".$wpdb->prefix."vp_pms_group_users on ".$wpdb->prefix."vp_pms_messages.id = ".$wpdb->prefix."vp_pms_group_users.message_id and ".$wpdb->prefix."vp_pms_messages.group_id = ".$wpdb->prefix."vp_pms_group_users.group_id where ".$wpdb->prefix."vp_pms_group_users.from_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.from_del = '0' or ".$wpdb->prefix."vp_pms_group_users.to_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.to_del = '0' group by ".$wpdb->prefix."vp_pms_messages.group_id";
//$check_last_conversation = $wpdb->get_results($ss);
$response = print 'hello';
So I suppose there is some problems on how I've written my query.
$ss = "select * from ".$wpdb->prefix."vp_pms_messages inner join ".$wpdb->prefix."vp_pms_group_users on ".$wpdb->prefix."vp_pms_messages.id = ".$wpdb->prefix."vp_pms_group_users.message_id and ".$wpdb->prefix."vp_pms_messages.group_id = ".$wpdb->prefix."vp_pms_group_users.group_id where ".$wpdb->prefix."vp_pms_group_users.from_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.from_del = '0' or ".$wpdb->prefix."vp_pms_group_users.to_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.to_del = '0' group by ".$wpdb->prefix."vp_pms_messages.group_id";
Said that, I can't see the error.
My apache_error.log and mysql_error_log.err don't report anything
about.
My tables are empty at now but should they print nothing than produce that error.
Can you please suggest something?
EDIT
I see this error in my console
MySQL table empty
My Wordpress Debug is active like:
My debug.log file (wp-content) is not showing any error in my code.
I've discovered that there is a fatal error in the same file of my query:
PHP Fatal error: Call to undefined function get_bloginfo()
I could check it trough the server php error log. Working on MAMP you can find it here:
MAMP/logs/php_error.log
In my case, Wordpress didn't report it in wp-content/debug.log. So you know. It takes me to the conclusion that my file.php doesn't recognise wordpress hooks and could happen for $wpdb too, throughout my query.
As OP mentioned that he is working on external wordpress script and is not able to access his wordpress functionality. To ensure that you retain your wordpress functionality on your external files, please put the following code, at the start of your external script page.
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
The above lines, will include all the wordpress functionality for your script. $path variable stores the path of your wordpress installation folder.
During the development always turn on the error reporting to be aware of warnings notice or fatal errors which can occur very easily if you forget something or miss place something. So better to be aware or errors and turn the error reporting on to see the errors and when in production do disable the error reporting.
go into wp-config.php file and search for : define('WP_DEBUG',false); and change it to define('WP_DEBUG',true);
Even if your query is okay , you will still result to an error , which you will be getting due to incorrect printing of an array:
function get_results of $wpdb , is an function that will return an array as result of multi rows , and for dumping it use :
print_r($check_last_conversation);
or
var_dump($check_last_conversation);
print 'hello; works because it is a string , and $check_last_conversation is an array. Don't wrap the print_r or var_dump or print or echo inside an variable. as they are supposed to print the data inside from variables.
so in case you have more errors , you can look at the errors , by turning the error reporting on.
Sort of going on from Ajit's answer. I was also having issues similar to this that was caused by character collation which was fixed by adding one extra line.
At the top of any php external file that used wpdb I was using the following:
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
You can then use the $charset_collate in your sql statement, e.g.
$sql = "CREATE TABLE `{$wpdb->base_prefix}my_nice_table` (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
) $charset_collate;";
Hope that helps!

Write to online SQL Database using PHP script

I need to save the data from android into an online SQL database. I made a PHP file for doing the task. I am trying to save the data using GET in a PHP file but it always returns false. Kindly have a look at my code and please help. The file is called using an android application. Tried testing though REST add-ons for browsers.
EDIT : Problem - When I send the data using HTTP GET all I get in return is the JSON result {"result":false}. This means my SQL query does not run properly. I tried running the same code directly in phpMyAdmin and it works.
EDIT : Code corrected.
<?php
$con = new mysqli("HOST","USERNAME","PASSWORD","DATABASE");
$rrequest_status = $_GET['request_status'];
$rstudent_name = $_GET['student_name'];
$rrequest_to = $_GET['request_to'];
$renrollment_no = $_GET['enrollment_no'];
$rout_date = $_GET['out_date'];
$rout_time = $_GET['out_time'];
$rin_date = $_GET['in_date'];
$rin_time = $_GET['in_time'];
$rrequest_time = $_GET['request_time'];
$rapproved_time = $_GET['approved_time'];
$rvisit_place = $_GET['visit_place'];
$rvisit_type = $_GET['visit_type'];
$rcontact_number = $_GET['contact_number'];
$squery = "INSERT INTO `gatepass_requests` (
`gatepass_number` ,
`request_status` ,
`student_name` ,
`request_to` ,
`enrollment_no` ,
`out_date` ,
`out_time` ,
`in_date` ,
`in_time` ,
`request_time` ,
`approved_time` ,
`approved_by` ,
`visit_place` ,
`visit_type` ,
`contact_number`
)
VALUES (
NULL ,
'".$rrequest_status."',
'".$rstudent_name."',
'".$rrequest_to."',
'".$renrollment_no."',
'".$rout_date."',
'".$rout_time."',
'".$rin_date."',
'".$rin_time."',
'".$rrequest_time."',
NULL,
'".$rapproved_by."',
'".$rvisit_place."',
'".$rvisit_type."',
'".$rcontact_number."',
)";
if(mysqli_query($con,$squery)){
$result['result'] = true;
}else{
$result['result'] = false;
}
echo json_encode($result);
mysqli_close($con);
?>
To set the record straight for future readers.
The fact of the matter here is that you have different/undefined variables for the following used in your VALUES:
$rrequest_status
$rrequest_to
$rrequest_time
But have declared them as, and with an extra "r" and assuming that is your real code and not just a bad paste in your question:
Sidenote: Assuming the GET requests as opposed to POST.
$request_status = $_GET['request_status'];
$request_to = $_GET['request_to'];
$request_time = $_GET['request_time'];
And error reporting would have have signaled undefined variables notices but failed to mention that.
http://php.net/manual/en/function.error-reporting.php
Then you stated this comment in an answer given:
"Thank You so much for your reply, I removed it for the time being, but it is not the problem. PHP does allow to have trailing commas so it doesn't matter. – Pradumn Kumar Mahanta"
Maybe for certain PHP operations, but we're dealing with MySQL here and that alone would have thrown you an exception about the trailing comma for:
'".$rcontact_number."', <<<
In regards to the SQL injection you're open to, use a prepared statement:
References:
https://en.wikipedia.org/wiki/Prepared_statement
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php (MySQLi_)
http://php.net/pdo.prepared-statements (PDO)
Error checking references:
http://php.net/manual/en/function.error-reporting.php (PHP)
http://php.net/manual/en/mysqli.error.php (MySQLi)
As you used $con = new mysqli("HOST","USERNAME","PASSWORD","DATABASE");. So you are following Object oriented style. So, you need to follow Object oriented style for executing query. Right now you mixed Object oriented style & Procedural style
Change
if(mysqli_query($con,$squery)){
$result['result'] = true;
}else{
$result['result'] = false;
}
To
if($con->query($squery)){
$result['result'] = true;
}else{
$result['result'] = false;
}
For more info, please have a look here Object Oriented Style & Procedural Style
Remove extra , from the insert query.
'".$rcontact_number."', <-- this one
To check what error comes, do following:
if(mysqli_query($con,$squery)) {
$result['result'] = true;
} else {
$result['result'] = mysqli_error($con); // instead of false, use mysqli_error($con)
}

Problems with variables set inside While Loop being undefined outside.

Okay, so i have created a new support ticket system, but in my ticket search page it keeps giving me errors like undefined variable in line 197. the weird thing is that the variable is defined right above it. Please assist me in this here is a link to the code: http://pastebin.com/AMzRLDK4
I'm trying to make it possible for me to view the support tickets that are open and mark them as read or change the status and to reply to them by going to the pm system. I had it working last night but i must have changed something without realizing its effect.
Thanks in advance,
Matt.
It looks like this is the first time you use $Sid or $Sname in your code. They are inside a code block for the while, which means that is the only place they exist. Also, I think you want to use mysql_fetch_assoc(). It'll actually work with the column names, instead of the indexes. (And probably best off to use the newer MySQLi for several reasons)
while($raw = mysql_fetch_array($ret)){ $Sid = $raw['id']; $Sname = $raw['username']; }
Quick Fix:
$Sid = null; //or 0 whichever makes sense for you
$Sname = null; //or ''
while($raw = mysql_fetch_assoc($ret)){ $Sid = $raw['id']; $Sname = $raw['username']; }
However, with the LIMIT 1 in the MySQL Query, you could drop the WHILE all together
$raw = mysql_fetch_assoc($ret);
if($raw === false)
{
//Error Condition
}
$Sid = $raw['id'];
$Sname = $raw['username'];

Replacing $_HTTP_GET_VARS with $_GET

This is a question about setting up variables in an array for a personal memory aid project analogous to the old paper-based flash cards, which I now want to dust off. A PHP programmer at my old work 5 years ago helped write the page - alas I have long since lost contact, and my PHP skills are rudimentary at best.
Current Code (PHP4)
<?php
# Setting up Variables
reset($HTTP_GET_VARS);
while(list($key,$value) = each($HTTP_GET_VARS))
{
$$key = $value;
}
#set query string, current_id and current_index
$query_string = "sound=$sound&hint=$hint&type=$type";
if(!isset($current_id)) $current_id = "";
if(!isset($current_index)) $current_index = "";
#connect to MySQL
$conn = #mysql_connect( "localhost","xxxx","xxxx" )
or die( "Sorry - could not connect to MySQL" );
#select the specified database
$rs = #mysql_select_db( "xxx", $conn )
or die( "Sorry - could not connect to specified Db" );
# create the query to select the records and then …
Attempts to find solution
Initially I tried a simple substitution as recommended elsewhere. But in the case of this page's code it did not work. I also looked at Replaced $HTTP_GET_VARS with $_GET, but not working and it too did not solve the issue (see below attempt)
Attempted New Code (PHP5)
Assuming a single table Db, with multiple columns, say 'alpha', 'bravo' and 'charlie', then rows of data in the table cells. The now depreciated $HTTP_GET_VARS used to work fine:
<?php
# Setting up Variables
unset($alpha, $bravo, $charlie);
while(list($key,$values) = each($alpha = $_GET['alpha'], $bravo = $_GET['bravo'], $charlie = $_GET['charlie']))
{
$$key = $value;
}
#set query string, current_id and current_index
$query_string = "sound=$sound&hint=$hint&type=$type";
if(!isset($current_id)) $current_id = "";
if(!isset($current_index)) $current_index = "";
#connect to MySQL
$conn = #mysql_connect( "localhost","xxxx","xxxx" )
or die( "Sorry - could not connect to MySQL" );
#select the specified database
$rs = #mysql_select_db( "xxx", $conn )
or die( "Sorry - could not connect to specified Db" );
# create the query to select the records and then...
The error I get with this code is: Notice: Undefined index: alpha in C:\wamp\www\page2.php on line 4
that is not an error, it is a notice - telling you some $_GET array index might not exist where you use it. You might look into php's error_reporting() and possibly set it to error_reporting(E_ERROR) at the very beginngin of the script to avoid notices - in your case that would probably suffice.
http://php.net/manual/en/function.error-reporting.php
4) If you want to have the keys available as local variables and (correctly) have register_globals disabled, what's wrong with extract($_GET);? – DaveRandom
From:
<?php
# Setting up Variables
unset($alpha, $bravo, $charlie);
while(list($key,$values) = each($alpha = $_GET['alpha'], $bravo = $_GET['bravo'], $charlie = $_GET['charlie']))
{
$$key = $value;
}
To:
# Setting up Variables
unset($alpha, $bravo, $charlie);
extract($_GET);
Seems to have done the trick.
Thanks DaveRandom
Because you unset variables that aren't set yet
I think you have in php4 register_globals on and in php 5 off
register_globals is a bad thing so don't put it on

Categories