Can someone please explain to me why I keep getting the following error when I use the mysqli_num_rows() function?
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator to inform of the time the error occurred and of anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
Here is my php script:
<?php
//stores user input as variable
$username = $_POST['username'];
$password = $_POST['password'];
//selects from users table
$sql = "SELECT * FROM Members WHERE username='$username' and password='$password'";
$results = mysqli_query($con,$sql);
$count = mysqli_num_rows($results);
/*//starts session and sets cookie if count is true
if($count>=1)
{
session_start();
$_SESSION['username'] = ' ';
$_SESSION['password'] = ' ';
header("location: index.html");
}
//returns message if user input does not match database
else
{
echo "Invalid username or password";
}*/
?>
I get this error at the mysqli_num_rows() function everything before it works fine. I am using Plesk on a Godaddy server by the way.
You need to learn how to read php and mysqli errors
You need to learn how to use mysqli properly
You don't heed this function at all
How to get mysqli error in different environments? for the first
and How can I prevent SQL injection in PHP? for the second
just fetch your data and use it as a flag for the last
As far as I can see there is no function as mysqli_num_rows().
Is the $con variable declared elsewhere? I don't see it being declared. Also, you are subject to injection attacks with this current code. Make sure you escape your parameters before using this publicly.
Related
This is the code for my log in forum. The problem with it is that it only accepts as correct credentials the first username and password (basically only the first row) any ideas as to how i could change it ?!
<?php
session_start();
include_once("connect.php");
$token = "";
if($con->connect_error){
die("Connection failed: ".$con->connect_error);
}
$sql = "SELECT * FROM authme";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
while(mysqli_num_rows($result)>0){
while($row = $result->fetch_assoc()){
if(isset($_POST['realname']))
$username = $_POST['realname'];
if($result->num_rows>1){
if(mysqli_num_rows($result)>1){
$_SESSION['uid'] = $row['id'];
$_SESSION['realname'] = $row['realname'];
}
$password = '$SHA$'.substr($row['password'],5,16).'$'.hash('sha256', hash('sha256',$_POST['password']).substr($row['password'],5,16));
if($password == $row['password'] ){
header("Location: index.php");
exit();
}
else {
echo "INVALID INFORMATION, PLEASE RETURN!";
// header("location: index.php");
session_destroy();
exit();
}
}
}
}
?>
?
I decided to try to make a log in forum that uses a database which encrypts the passwords it receives through a register form. This code only takes as correct the first username and password i give in and its not enough, as you could imagine.
Welcome to programming with PHP. I'm going to try to share a few principles that may help you solve your problem.
1.) One of the best features in PHP is the print_r() function. Using this function you can output almost anything to text in the browser. So in this case you may want to insert a print_r($result) immediately following this line "$result = mysqli_query($con, $sql) or die(mysqli_error($con));". This will output the results of the query that PHP is receiving. This can be used to help you troubleshoot and determine why your code isn't working. Once you're done troubleshooting delete that line.
2.) You seem to have multiple checks for the number of rows inside the while loop. I'm not sure why you have thoose there, but you may want to check if those are causing your trouble by using echo or print to display to values in the browser for troubleshooting. Once you're done troubleshooting delete that line.
3.) Another overall concept for the data you are querying. It is inefficient to send a query that gets the entire table and returns it to the program, that then loops through every row looking for the data. Instead you should write an SQL query to return only the row of data the you want. Make sure you do use prepared statements.
4.) Your coding standards could use some improvement, if you clearly tabbed your statements it would be easier to read. Consider reading PSR-2. For example this code seems to be missing {}'s.
if(isset($_POST['realname']))
$username = $_POST['realname'];
Took the plunge into Android development (mostly for fun). I do have programming experience but not in Java.
Working on an activity where the user is pre-assigned a password they have to change when they first login. I basically duplicated the Login PHP and tweaked it to do an update (instead of checking for a valid username/pw). The php returns an error BUT, the password is actually updated in the database. Which does me no good since Android thinks there was an error.
Here's my PHP:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$username = $_POST['username'];
$password = $_POST['password'];
$con=mysqli_connect(“server”,”user”,”pw”,”db”);
$sql ="UPDATE coaches SET coach_pw = '$password' WHERE (((coach_id)='$username'))";
$check = mysqli_query(mysqli_query($con,$sql));
if(isset($check)){
echo "success";
}else{
echo "Invalid Username or Password";
}
}else{
echo "error try again";
}
?>
The error I get back from PHP (from AS debug): html markup & "PHP Error Message" & html markup.
The last thing I changed that I thought was the problem was the mysqli_ function I was using (_fetch_array instead of _query). But that didn't fix the issue.
Any guidance will be greatly appreciated!
Well as Bang said in his comment, the double use of the mysqli_query function explains why the script returns an error.
Your query is correctly executed by the inner mysqli_query(), wich returns TRUE. This return value is then executed by the outer mysqli_query() wich, of course, returns an error.
That is why the query is successfully executed but an error is sent.
I know this is duplicate with this question. but I received the same error. I searched a lot for similar questions like : PHP not working on HTML file, PHP script not working in HTML file, Cannot run a simple PHP file on the server and many more but could not find any solution.
I created a very simple login html file, then I wrote the php scripts to do the login action in a separate php file. (in the same folder with html file). My problem is that when I type localhost/filename.php in browser, it returned me nothing. (I mean an empty html page without any error messege). Also, when I press the login button in my html login form, it asked me to save file while I expected to run the php file.
I checked the error log, this is the error:
script '/var/www/connectivity.php' not found or unable to stat [Wed
May 07 17:51:28 2014] [notice] caught SIGTERM, shutting down [Wed May
07 17:51:29 2014] [notice] Apache/2.2.22 (Ubuntu)
PHP/5.3.10-1ubuntu3.11 with Suhosin-Patch configured -- resuming
normal operations [Wed May 07 19:25:34 2014] [error] [client
127.0.0.1] PHP Warning: mysql_connect(): Access denied for user 'root'#'localhost' (using password: NO) in /var/www/connectivity.php
on line 7
this is the php script:
<?php
$host="localhost";
$user="root";
$pass="xxxxx";
$db="test";
$con=mysql_connect($host,$user,$pass) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db($db,$con) or die("Failed to connect to MySQL: " . mysql_error());
if(isset($_POST['userId'])){
$userId = $_POST['userId'];
$password = $_POST['password'];
$sql = "SELECT * FROM User where userId = '$userId' AND password = '$password'" or die(mysql_error());
$res = mysql_fetch_array($sql) or die(mysql_error());
if(mysql_num_rows($res) > 0) {
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
exit();
}
else
{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
exit();
}
}
?>
could someone kindly help me to solve it?
Thanks
where is your mysql_query()?
I think you should add the mysql_query() and try again.
$sql = "SELECT * FROM User where userId = '$userId' AND password = '$password'";
$query=mysql_query($sql) or die(mysql_error()); **// You didn't add this line**
$res = mysql_fetch_array($query) or die(mysql_error());
your all other code goes here.................. hop your problem is fixed
There are a few issues with the code presented above. The first issue with nothing appearing on the screen is most likely due to PHP throwing errors and crashing OR that you don't have userId set in the HTTP Header for POST data. To make sure you are sending the POST data to the server, you can check the Developer tools of your web browser or on the top of the PHP script use the following code.
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
?>
As for the PHP errors, the first one I notice is that you fail to use the function mysql_query($sql) and you directly insert the SQL variable into mysql_fetch_array(). This is not the proper way to do this.
$sql = "SELECT * FROM User where userId = '$userId' AND password = '$password'";
$res = mysql_query($sql);
if(!$res) {
// Failed to perform SQL Query
echo 'Mysql Query Failed';
exit();
}
$row = mysql_fetch_array($res);
if(mysql_num_rows($res) > 0) {
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
exit();
}else {
echo "SORRY... YOU ENTERED WRONG ID AND PASSWORD... PLEASE RETRY...";
exit();
}
The other PHP issue is you don't check if $_POST['password'] isset, which you do check for the userId. This is a simple fix by changing one line of code.
if(isset($_POST['userId'])) {
// Changes To
if(isset($_POST['userId'],$_POST['password'])) {
My next note are security features you should really follow. The first main issue is your lack of parsing variables before inserting them into your SQL variable. Never insert variables that users can modify directly into your query. If you stick with the mysql_ functions, you will want to first run the command mysql_real_escape_string() on all variables you pass.
$userId = mysql_real_escape_string($userId);
$password = mysql_real_escape_string($password);
$sql = "SELECT * FROM User where userId = '$userId' AND password = '$password'";
The next security issue is that you are not encrypting passwords. Alwasy encrypt passwords with unique salts for each user. When the user changes their password the salt should also change.
$salt = generate_salt(); // You need to create this function. Generate a lot of random characters.
$password = hash('sha512',$password.$salt);
Using the above method, you do not want to use mysql_real_escape_string() on the password variable until after you generate it. If you do use it before hashing the password, the user will most likely have trouble logging in in the future since the password may not match.
The next fatal flaw in your code is that you are using the mysql_ functions which is now unsupported and deprecated. As you can see from the quote on the PHP website for all the mysql_ functions.
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
I highly suggest PDO as apposed to MySQLi, but it is just personal preference.
This is for an Android application and I am using web-services written in php. I have 3 php scripts - dbconnect.php(this has all the db variables), login.php(this validates the user credentials and open a session) and showCases.php(which will return a list of tickets from the userID variable obtained from the login.php script)
However, for some reason I have: "Access denied for user 'ODBC'#'localhost' (using password: NO)" when I am requesting information showCases.php. I am not quite sure if the session is being used correctly.
Here is the login.php script:
//Displaying the error if sql query is incorrect
if(!$result){
die(mysql_error());
}else{
$row = mysql_fetch_assoc($result);
$first_name = $row['first_name'];
$id = $row['id'];
}
//If found, number of rows must be 1
if($num_rows==0){
$success = 0;
}else{
//creating session
session_start();
session_register("$username");
session_register("$password");
$success = 1;
}
$arr = array(
array('username' => $username, 'id'=>$id,'success'=>$success, 'first_name'=>$first_name));
#array('success'=> $success));
echo json_encode((array('Username'=>$arr)));
mysql_close();
?>
The script would return the username array to the android application for it to process the validation. Upon validation, the android application would request tickets from this php script.
session_start();
#require('dbconnect.php');
require_once('login.php');
$response=array();
$response['infos'] = array();
//execute the SQL query and return records
$result = mysql_query("SELECT cases.id, cases.account_id.... casesvisibility.user_id = '$id'......";
//Displaying the error if sql query is incorrect
if(!$result){
die(mysql_error());
}
$num_rows = mysql_num_rows($result);
$arr = array();
if($num_rows!=0){
while ($row = mysql_fetch_assoc($result)) {
$arr['cases_id']=$row['cases.id'];
$infos[]=$arr;
}
}else{
#$arr['existingCases']=$row['0'];
$arr['cases_id']=0;
$infos[]=$arr;
}
#Echoing a JSONArray
print(json_encode(array('Cases'=>$infos)));
//close the connection
mysql_close();
?>
I am not too sure this is well-written code for the functionality I want it to achieve. When I call this script from android application, I first get the JSON_array from the login script and it tells me:
{"Username":[{"username":"","id":null,"success":0,"first_name":null}]}id is
Warning: mysql_query() [function.mysql-query]: Access denied for user 'ODBC'#'localhost' (using password: NO) in E:\wamp\www\mobile.dcl.mu\webserver\showCases.php on line 18
Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in E:\wamp\www\mobile.dcl.mu\webserver\showCases.php on line 18
Access denied for user 'ODBC'#'localhost' (using password: NO)
I understand that I'm trying to use a variable from another php script.
Can you help me some this issue please?
Thank you
Where you create $num_rows? Probably you want to put this code in top login.php:
//Displaying the error if sql query is incorrect
if(!$result){
die(mysql_error());
}else{
$num_rows = mysql_num_rows($result);
if ($num_rows) {
$row = mysql_fetch_assoc($result);
$first_name = $row['first_name'];
$id = $row['id'];
}
}
I think you are mixing up session and db connection (if I understand your code snippets correctly).
Keep in mind, that for the server, each request is a completely new process. You can share variables via session, but you can not share process bound resources like the db connection.
as your server is telling you, on the second request there is no password and maybe even the wrong (default?) db user given.
So, what you need to do is simply this:
Provide the db connection information in every possible execution path. i.e. if your android app calls http://your.server/showCases.php directly, include dbconnect.php in showCases.php, too.
I think you had it once:
in your second script you have this line:
#require('dbconnect.php');
try uncommenting this again, it may bring you a step closer to your goals.
P.S. the pure mysql_* functions are deprecated, read the php.net docu (or other questions here) for the security concerns regarding these functions. Upgrade your scripts to use PDO or mysqli
Most likely issue with your database connection call, you are either not providing correct username and or password. i suspect missing password . check your database connection
$db_host = "localhost"; // database host
$db_name = "test"; // database name
$db_login = "root"; // database user
$db_pass= "*****"; // database password
$db = mysql_connect($db_host, $db_login, $db_pass);
mysql_select_db($db_name,$db);
this is just sample code to indicate what i am referring to. Also, make sure you include this db connection file on each php file. There are various ways to make db connection available to different php files( where sql calls gets make)
Can anyone see anything wrong with this login script:
public function login($username, $pass, $remember) {
// check username and password with db
// else throw exception
$connect = new connect();
$conn = $connect->login_connect();
// check username and password
$result = $conn->query("select * from login where
username='".$username."' and
password=sha1('".$pass."')");
if (!$result) {
throw new depException('Incorrect username and password combination. Please try again.');
} else {
echo $username, $pass;
}
To explain:
At the moment the script is allowing anything through. In other words the query is returning true for any username and password that are passed to it.
I've put the echo statement just as a check - obviously the script would continue in normal circumstances!
I know that the connect class and login_connect method are working because I use them in a register script that is working fine. depException is just an extension of the Exception class.
The function login() is part of the same class that contains register() that is working fine.
I know that the two variables ($username and $pass) are getting to the function because the echo statement is outputting them accurately. (The $remember variable is not needed for this part of the script. It is used later for a remember me process).
I'm stumped. Please help!
UPDATE
Thanks for those responses. I was getting confused with what the query was returning. The complete script does check for how many rows are returned and this is where the checking should have been done. Everything is now working EXCEPT for my remember me function. Perhaps someone could help with that?!?! Here is the full script:
public function login($username, $pass, $remember) {
// check username and password with db
// else throw exception
$connect = new connect();
$conn = $connect->login_connect();
// check username and password
$result = $conn->query("select * from login where
username='".$username."' and
password=sha1('".$pass."')");
if (!$result) {
throw new depException('Incorrect username and password combination. Please try again.');
}
if ($result->num_rows>0) {
$row = $result->fetch_assoc();
//assign id to session
$_SESSION['user_id'] = $row[user_id];
// assign username as a session variable
$_SESSION['username'] = $username;
// start rememberMe
$cookie_name = 'db_auth';
$cookie_time = (3600 * 24 * 30);*/ // 30 days
// check to see if user checked box
if ($remember) {
setcookie ($cookie_name, 'username='.$username, time()+$cookie_time);
}
// If all goes well redirect user to their homepage.
header('Location: http://localhost/v6/home/index.php');
} else {
throw new depException('Could not log you in.);
}
}
Thanks very much for your help.
UPDATE 2!
Thanks to your help I've got the main part of this script working. However, the remember me bit at the end still doesn't want to work.
Could someone give me a hand to sort it out?
$username, $pass and $remember are all short variable names that I assigned before passing them to the function to save writing $_POST['username'] etc. everytime. $remember refers to a checkbox.
What does $conn->query() return, a MySQL resource object like mysql_query() does? If so then it'll always compare "true". mysql_query() only returns FALSE if the query completely fails, like it has a syntax error or a table doesn't exist.
To check if you got any results you need to try to fetch a row from the result set and see if you get anything, via whatever your equivalent of mysql_fetch_row() is.
Important: Your script is vulnerable to SQL injection attacks, or even just odd usernames like o'neil with an apostrophe. You should escape all variables in a query with mysql_real_escape_string() (or equivalent) to make sure your query doesn't get messed up by special characters. Or, even better, use prepared statements which look like
select * from login where username=? and password=sha1(?)
Re: UPDATE
Variables from a form are available via either $_GET or $_POST, depending on which method was used to submit the form. Try if (isset($_POST['remember'])) to see if that check box was checked.
Important: I see that you tried to use a bare $remember to see if the check box was checked. That suggests to me that you are trying to take advantage of the register_globals feature in PHP which makes your GET and POST variables accessible via regular variable names. If that is the case you should heed the warning in the PHP manual!
WARNING
[register_globals] has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.
Use $_GET and $_POST instead. I could tell you how to make if ($remember) work, actually, but given the inherent evil-ness of register_globals I'm not gonna! ;-)
Your query is open for sql-injections...
SELECT * FROM users WHERE
username = '' OR 'a' = 'a'
AND password =
sha1('guessAnyPassword')
I'd also check your result, and base the action on how many records were returned.
if (mysql_num_rows($result) > 0)
In php most queries only return False if there was an error executing them. Your query is returning a value, probably an empty array of values. This is not a false value as far as your if statement is concerned.
Check how many rows are returned. The function to do this will depend on your abstraction layer (connect class etc...)