I'm fairly new to PHP/MySQL and I seem to be having a newbie issue.
The following code keeps throwing me errors no matter what I change, and I have a feeling it's got to be somewhere in the syntax that I'm messing up with. It all worked at home 'localhost' but now that I'm trying to host it online it seems to be much more temperamental with spaces and whatnot.
It's a simple login system, problem code is as follows:
<?php
session_start();
require 'connect.php';
echo "Test";
//Hash passwords using MD5 hash (32bit string).
$username=($_POST['username']);
$password=MD5($_POST['password']);
//Get required information from admin_logins table
$sql=mysql_query("SELECT * FROM admin_logins WHERE Username='$username' ");
$row=mysql_fetch_array($sql);
//Check that entered username is valid by checking returned UserID
if($row['UserID'] === NULL){
header("Location: ../adminlogin.php?errCode=UserFail");
}
//Where username is correct, check corresponding password
else if ($row['UserID'] != NULL && $row['Password'] != $password){
header("Location: ../adminlogin.php?errCode=PassFail");
}
else{
$_SESSION['isAdmin'] = true;
header("Location: ../admincontrols.php");
}
mysql_close($con);
?>
The test is just in there, so I know why the page is throwing an error, which is:
`Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in 'THISPAGE' on line 12`
It seems to dislike my SQL query.
Any help is much appreciated.
EDIT:
connect.php page is:
<?php
$con = mysql_connect("localhost","username","password");
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con);
?>
and yes it is mysql_*, LOL, I'll get to fix that too.
You should escape column name username using backtick, try
SELECT *
FROM admin_logins
WHERE `Username` = '$username'
You're code is prone to SQL Injection. Use PDO or MYSQLI
Example of using PDO extension:
<?php
$stmt = $dbh->prepare("SELECT * FROM admin_logins WHERE `Username` = ?");
$stmt->bindParam(1, $username);
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>
Sean, you have to use dots around your variable, like this:
$sql = mysql_query("SELECT * FROM admin_logins WHERE Username = '". mysql_real_escape_string($username)."' ");
If you use your code just like this then it's vulnerable for SQL Injection. I would strongly recommend using mysql_real_escape_string as you insert data into your database to prevent SQL injections, as a quick solution or better use PDO or MySQLi.
Besides if you use mysql_* to connect to your database, then I'd recommend reading the PHP manual chapter on the mysql_* functions,
where they point out, that this extension is not recommended for writing new code. Instead, they say, you should use either the MySQLi or PDO_MySQL extension.
EDITED:
I also checked your mysql_connect and found a weird regularity which is - if you use " on mysql_connect arguments, then it fails to connect and in my case, when I was testing it for you, it happened just described way, so, please try this instead:
$con = mysql_connect('localhost','username','password');
Try to replace " to ' as it's shown in the PHP Manual examples and it will work, I think!
If it still doesn't work just print $row, with print_r($row); right after $sql=mysql_query() and see what you have on $row array or variable.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Would you please help me sort this problem out. I don't know what I'm doing wrong. My connection to database working correct but I'm unable to login.
login.php
<?php
session_start();
$username= $_POST["username"];
$password= $_POST["password"];
include("/inc/connect.inc.php");
if(!isset($conn)){
$conn = null;
header('Location: index.php');
}
else{
$query = $conn->prepare("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$password'");
$query ->execute(array(':username' =>$username, ':password' =>$password)
);
if ( ($query->rowCount() == 0) && ( ($password == null) or ($username == null) ) ){
echo "<h3>Please enter your username and password</h3>";
$conn = null;
header("Refresh: 3;URL=index.php");
}
else if ($query->rowCount() == 1)
{
$_SESSION['user_logged'] = $_POST['username'];
unset($username);
unset($password);
echo "<h3>Your password is correct</h3>";
$conn = null;
header("Refresh: 3;URL=interface.php");
}
else {
echo "<h3>The username / password combination entered is incorrect!</h3>";
unset($username);
unset($password);
$conn = null;
header("Refresh: 3;URL=index.php");
}
}
?>
Previously I didn't understand stackoverflow rules. I hope this time my question is more accurate. I have done lot of work to get to this point and only have a problem with login to my database now. My $query = $conn->prepare not finding anything. It's jumping to The username / password combination entered is incorrect! at any time. If I leave username or/and password empty or putting correct username and password always the same result.
I am posting this because it is an answer that addresses the real issue as to why the OP's code isn't working.
Firstly, a typo in bname which should read as dbname in your connection.
Now, you are mixing MySQL APIs with mysql_ functions and PDO.
Those different APIs do not intermix with each other.
In comments you said:
"You are welcome to convert my code to PDO. I can understand that this code is mixed up but have no idea how to fix it."
I don't like coming off as or sounding like the "bad man" here, but that isn't our job to convert your mysql_ code to PDO, it's yours. We don't convert code on Stack, we help out with problematic code.
There are plenty of tutorials out there for you to learn and use.
Here are but a few, which you can further your research on Stack/Google:
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html
There is also the manuals on PHP.net
http://php.net/manual/en/ref.pdo-mysql.php
http://php.net/manual/en/pdo.query.php
On Stack:
How can I properly use a PDO object for a parameterized SELECT query
Regarding MD5 for passwords:
$password = md5($password);
MD5 is old and considered broken and no longer safe to use for password storage.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
"I'm getting blank screen. Any ideas?"
Regarding "a blank screen".
This means you have syntax errors.
Doing error_reporting(0); means "Turn off all error reporting"
As per the manual on PHP.net
http://php.net/manual/en/function.error-reporting.php
What you need to do is turn error reporting on, not off.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
If you look in the connection string there is a typo:
Take a look at the examples here http://php.net/manual/en/pdo.connections.php
Update: You seem to be totally lost so I'll step by step the code and the reason for things not working. The code I write will be filled with echo and print statements.
1.) You need to check your database connection but you have no code to do this. The connection might be fine but PHP does not throw an error.
try
{
$conn = new PDO('mysql:host=localhost;dbname=' . $database . 'charset=utf8', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(is_object($conn) && $conn != false)
{
echo "I'm connected. PDO is ready and willing";
}
else
{
echo "Sorry something went horribly wrong! Not connected to database";
{
}
catch(PDOException $e)
{
throw new pdoDbException($e);
echo die('Error Message:'.$e->getMessage());
}
2.) It will look like your connection is not working because none of functions is calling a connection. The connection object created is outside of the functions scope.
function user_exists($username)
{
global $conn; // bring the connection object into scope
$username = sanitize($username);
$query = $conn->prepare("SELECT COUNT(user_id) FROM users WHERE username = :username");
$query ->execute(array(
':username' =>$username
));
$user = $query->fetch(PDO::FETCH_ASSOC);
return $user. ' exists in database';
}
3.) there's lots of code but none of the functions looks like they are being called at runtime. Test for user exists and if database connection works at runtime in the init.php file
<?php
session_start();
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
$errors = array();
// call a function to check if user exists.
echo user_exists('user_123');
?>
1st step. Change
$conn = new PDO('mysql:host=localhost;bname='.$database.'charset=utf8',$username,$password);
to
$conn = new PDO('mysql:host=localhost;dbname='.$database.';charset=utf8',$username,$password);
2st. You use mysqli and pdo in one project. For what?
i have tried this code to insert value into database, but i don't Know why, the value was not send into the databases. The table i have created in the mysql :
<?php
require_once "connection.php";
$conn = connect();
$db = connectdb();
mysql_select_db($db,$conn) or die (mysql_error() . "\n");
$query_usr = "select * from soalselidik";
$usr = mysql_query($query_usr,$conn) or die(mysql_error()."\n".$query_usr);
$row_usr=mysql_fetch_assoc($usr);
//to insert in database
$a1=$_POST['a1'];
$a2=$_POST['a2'];
$a3=$_POST['a3'];
$a4=$_POST['a4'];
$b1=$_POST['b1'];
$b2=$_POST['b2'];
$b3=$_POST['b3'];
$b4=$_POST['b4'];
$c1=$_POST['c1'];
$c2=$_POST['c2'];
$c3=$_POST['c3'];
$c4=$_POST['c4'];
$d1=$_POST['d1'];
$d2=$_POST['d2'];
$d3=$_POST['d3'];
$d4=$_POST['d4'];
$e1=$_POST['e1'];
$f1=$_POST['f1'];
echo $query ="insert into soalselidik (a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4,d1,d2,d3,d4,e1,f1) values('$a1','$a2','$a3','$a4','$b1','$b2','$b3','$b4','$c1','$c2','$c3','$c4''$d1','$d2','$d3','$d4','$e1','$f1')";
$result = mysql_query($query);
echo "<script languange = 'Javascript'>
alert('thankyou ! Penilaian anda diterima ');
location.href = 'home.php';</script>";
?>
'$c4''$d1'
Find that in your query and fix it :) And please do some error checking, and please stop using MySQL_* for your own good. Why should people not run any error checking mechanism that's already provided in the language and expect others to debug typos?
In case you didn't get it, there's a comma missing
How can I prevent SQL injection in PHP?
So I use to program in PHP my own way and then someone told me to start using his way.
This of course caused me to do a few mistakes.
So this is the code:
<?php
function SignIn()
{
$con = mysqli_connect('localhost','root','avi1574','test');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
session_start();
if(!empty($_POST['user_w']))
{
$query = mysql_query($con, "SELECT * FROM `Users` where `User` = '$_POST[user_w]' AND Password = '$_POST[pass_w]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row['User']) AND !empty($row['Password'])){
$_SESSION['user_w'] = $row['Password'];
echo "Logged in.";
}
else{
echo "Sorry, wrong password."; } }}
if(isset($_POST['submit'])){
SignIn();
}
?>
<h1>My login page</h1>
<form action="tsql.php" method="POST" >
<input type="text" name="user_w" size="20"></input>
<input type="password" name="pass_w" size="20"></input>
<button type="submit" name="submit">Sumbit</button>
</form>
When I submit the form I get the following error:
Warning: mysql_query() expects parameter 1 to be string, object given in test-main/htdocs/test/tsql.php on line 10
Line 10 is: $query = mysql_query($con, "SELECT * FROMUserswhereUser= '$_POST[user_w]' AND Password = '$_POST[pass_w]'") or die(mysql_error());
Thank you in advance!
Many bad practice in there, let me point out a few things.
$_POST[pass_w]
This doesn't work as pass_w is not a constant. See this article. You must use quotes for the index: $_POST['pass_w'].
You are open to SQL injection and you should use prepared statements.
You also can't mix mysqli and mysql. Don't use mysql_ functions, they are not as secure and deprecated.
To your error message, you are simply trying to put a resource into mysql_query where function expects the query as a string, like SELECT.... You must switch the parameters.
When doing selects for password and username, ensure case sensitivity by using BINARY
and put LIMIT 1 at the end, to ensure only 1 record in return.
SELECT * FROM ... WHERE BINARY username = ... LIMIT 1
Also use some hashing function (not sha1 and not md5 please :-) for the password, with salt!
You should change the function you're using from mysql_query($con, "SELECT * FROMUserswhereUser= '$_POST[user_w]' AND Password = '$_POST[pass_w]'") to mysqli_query($con, "SELECT * FROMUserswhereUser= '$_POST[user_w]' AND Password = '$_POST[pass_w]'")
(mysqli_query instead of mysql_query).
While you're at it, you should also probably change mysql_fetch_array() to mysqli_fetch_assoc(), for two reasons:
you should use mysql and not mysqli since its deprecated
you're accessing $row's associative array keys, so you need the function to return associative array whild mysqli_fetch_array() returns numeric keys.
Many bugs
User = '$_POST[user_w]' should be User = ".$_POST['user_w']."
Here is some links which may be helpful
about mysql functions: http://php.net/manual/en/book.mysql.php
about mysqli functions: http://php.net/manual/en/book.mysqli.php
Mysql functions is the original function while Mysqli is the extension of Mysql functions
$query = mysql_query($con, "SELECT * FROM `Users` where User = '".$_POST['user_w']."' AND Password = '".$_POST['pass_w']."'");
but read the solution from DanFromGermany, because I gonna point out the same mistake, but as he already mention so no point,
Thanks
I have a "Windows Apache MySQL PHP" server on my laptop. I get absolutely no error messages, but when I send things to MySQL via PHP script, nothing happens in MySQL (I also sent something via the MySQL command prompt and it looks like it just made a test table and didn't put anything in it like I asked, but I'm not positive I did everything I should have in this case). I've rescripted my whole page a different way and it still doesn't work.
Here is a picture of my form and how the table looks in MySQL:
System:
Windows 7 Home Premium SP1 64 bit--
Apache 2.4.4 32 bit with ssl0.9.8--
PHP 5.4.11 32 bit VC9--
MySQL 5.5.31 64 bit with Navicat Lite
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'projectedin');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " .mysql_error());
function NewUser()
{
$userName = $_POST['username'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$password = $_POST['password'];
$birthday = $_POST['birthday'];
$gender = $_POST['gender'];
$query = "INSERT INTO users (username,firstname,lastname,password,birthday,gender) VALUES ('$username','$firstname','$lastname','$password','$birthday','$gender')";
$data = mysql_query ($query)or die(mysql_error());
if($data)
{
echo "YOUR REGISTRATION IS COMPLETED...";
}
}
function SignUp()
{
if(!empty($_POST['username'])) //checking the 'user' name which is from Sign-Up.html, is it empty or have some text
{
$query = mysql_query("SELECT * FROM users WHERE username = '$_POST[username]' AND password = '$_POST[password]'") or die(mysql_error());
if(!$row = mysql_fetch_array($query) or die(mysql_error()))
{
newuser();
}
else
{
echo "SORRY...YOU ARE ALREADY REGISTERED USER...";
}
}
}
if(isset($_POST['submit']))
{
SignUp();
}
mysqli_close ($con);
?>
There are a number of concerns here (more on that later), but this might be an issue for you:
You try to call your new user function like this:
newuser();
However it is named NewUser. This is case sensitive and will not work. Look at your error logs to see the errrs you are getting here.
Other issues:
You are using deprecated mysql_* functions. If you are learning PHP, learn the right way and use mysqli or PDO.
You are not escaping your input at all, and are therefore very prone to SQL injection attacks.
You are kind of randomly using functions when they don't really bring you any value.
You are kind of going outside of typical PHP coding standard when having your function names start with uppercase letter. This is a bit unusual for PHP, though this would actually work.
You have an error in your Signup query:
$query = mysql_query("SELECT * FROM users WHERE username = '$_POST['username']' AND password = '$_POST['password']'") or die(mysql_error());
I changed $_POST[username] to $_POST['username'] and $_POST[password] to $_POST['password']
Also, you are vulnerable for MySQL injections, you should use mysql_real_scape_string function to clean each $_POST var: $userName = mysql_real_scape_string($_POST['username']);
Finally, you should not use mysql* functions, they are deprecated.
I'm using a .Jquery autocomplete function and I'm tring to figure out where can put the mysql_real_escape_string() at. I've tried a few different ideas but I'm just not sure. I get an error of...
Warning: mysql_real_escape_string(): Access denied for user 'www-data'#'localhost'
When I use $ac_term = mysql_real_escape_string("%".$_GET['term']."%"); I'm not even sure if that the right way to use it.
Here's what I have...
<?php
if (!isset($_SESSION)) {
session_start();
}
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if ($conn)
{
$ac_term = "%".$_GET['term']."%";
$query = "SELECT
CONCAT_WS('', '(',User_ID,') ', UserName, ' (',AccessLevel,')') AS DispName,
User_ID, UserName, AccessLevel
FROM Employees
WHERE UserName LIKE :term
OR User_ID LIKE :term
OR AccessLevel LIKE :term
";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['value'] = $row['DispName'];
$row_array['User_ID'] = $row['User_ID'];
$row_array['UserName'] = $row['UserName'];
$row_array['AccessLevel'] = $row['AccessLevel'];
array_push($return_arr,$row_array);
}
}
$conn = NULL;
echo json_encode($return_arr);
?>
Any suggestions?
You don't have to add mysql_real_escape_string() to this query at all.
Just leave your code as is.
I believe that mysql_real_escape_string is not a right method to be used with PDO, for escaping purpose use PDO quote method.
As stated in documentation, escaping string is not necessary for prepare and execute statements:
Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.
Prepared statement parameters don't need to be escaped; it's one of the main reasons for them.
Some PDO drivers don't currently support repeating a named parameter. Depending on which version of PHP is installed, you may need to create a separate parameter for each value.
You need to create the connection first. mysql_real_escape_string() relies on an active MySQL connection; it's trying to assume your credentials will let you connect to localhost most likely.
create an active, authenticated mysql connection prior to using mysql_real_escape_string(), and at least that error message should go away.
Additionally, the best way to use it would be:
$ac_term = mysql_real_escape_string($_GET['term']);
with your query looking like
$query = "SELECT ... FROM ... WHERE column LIKE '%$ac_term%'";