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
Related
I have table user like:
user
=======
username
password
var
After login, I want to print variable var using username session like this, but have not had any success yet.
<?php
if(empty($_SESSION)){
header("Location: logout.php");
}
$username=$_SESSION['username'];
$link = mysql_connect("localhost", "root", "");
mysql_select_db("vhts", $link);
$var = mysql_query("SELECT var FROM user where username='$username'", $link);
echo $var;
?>
How can this be corrected?
mysql_query() returns a boolean or a resource. When the return value is a resource, the values can be fetched with a call to a function like mysql_fetch_assoc().
$result = mysql_query("SELECT var FROM user where username='$username'", $link);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$var = $row['var'];
echo $var;
?>
Important Note:
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_fetch_assoc()
PDOStatement::fetch(PDO::FETCH_ASSOC)
(Source: http://php.net/mysql_fetch_assoc)
So you should really consider using mysqli_query(), mysqli_fetch_array(), etc.
"SELECT var FROM user where username='$username'"
should work.., and the var would probably be in
$var['var']
and don't forget to add the fetch function
$var = mysql_fetch_assoc($var); // highly recommended to use mysqli / PDO
if(isset($_POST['submit'])){
$uname=$_POST['username'];
$pwd=$_POST['password'];
$acc_type=$_POST['acc_type'];
$_SESSION['user_type']=$acc_type;
if($acc_type=='Teacher'){
$sql="select userid,password from teacherinfo where userid='$uname'";
}
else if($acc_type=='Student'){
$sql="select userid,password from studentinfo where userid='$uname'";
}
else if($acc_type=='Admin'){
$sql="select userid,password from admininfo where userid='$uname'";
}
$query = mysql_query($sql);
$count = mysql_num_rows($query);
if($count>0){
$row_data = mysql_fetch_row($query);
if($row_data[1]==$pwd){
$_SESSION['userid']=$row_data[0];
$url="profile.php";
header("Location:$url");
}
else{
echo "Password Miss match!";
}
}
else{
echo "User not Found!";
}
}
Notice: Undefined variable: sql in C:\xampp\htdocs\MJ\index.php on line 39 Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\MJ\index.php on line 40
Looking at the code from the PHP website you are not linking your sql statement to the connection you made to your database. Look at the code below and you will see that a variable is create called $link this is then supplied the database to be used and then placed in as a second variable in the sql statement variable $result.
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
?>
You really do, as the comment state, need to stop using mysql and move over to PDO, this site should provide you with enough information to get your started and will secure the statements to the database - https://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Further to this you also need to look at hashing your passwords, currently you are using plain text, this is not secure. Using something like password_hash() - http://php.net/manual/en/function.password-hash.php - would provide a much more secure way of storing passwords. Once they are stored securing you can use password_verify() to check them against supplied passwords in the future.
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.
I need some help with echoing an SQL field but it keeps showing Resource #4 or does not show anything at all.
My code is
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
$myusername=$_POST['myusername'];
session_register("myusername");
$result = mysql_query("SELECT statsight from playerinfo WHERE username = 'myusername'") or die(mysql_error());
$row = mysql_fetch_array($result);
if(!session_is_registered('myusername')){
header("location:mainlogin.php");
}
echo $row['statsight'];
?>
<html>
<body>
Login Successful
<form name="form2" method="post" action="stat.php">
Stat1: <?php echo "<td>".$row['statsight']."<td>"?>
<input type="submit" value="+">
</form>
</body>
</html>
And it does not show anything. It only shows Stat1: with the + button.
The value of statsight in the database is 3 if it matters, and the myusername information comes from a form.
Got it working using
session_start();
$myusername=$_SESSION['myusername'];
username = 'myusername'
you are not suing variable here.
I am no PHP expert, but this might be the proper way
mysql_query("SELECT statsight from playerinfo WHERE username = ' ". $myusername."'") or die(mysql_error());
Although this is not a proper way, you should be using mechanism of Prepared statements while executing queries.
You will need to use mysql_fetch_assoc instead of mysql_fetch_array So that your field names are brought into the array as keys $row['statsight']
You have to put $ in here '$myusername'
$result = mysql_query("SELECT statsight from playerinfo WHERE username = '$myusername'") or die(mysql_error());
The mysql extension is not recommended anymore. We are meant to use mysqli instead now. While mysqli does support prepared statements, they are not necessary for a simple select like yours. Using the PHP function mysqli_real_escape_string() should be adequate. For an insert query, additional security is required.
The method you are using for sessions is completely deprecated. The proper method is shown in my sample code. I think your reference is so out of date that it is the source of your troubles. I recommend spending some time with a current copy of the official PHP manual.
There are several functions which can be used to handle results of a query which returns a resultset. Here is a partial listing of the
mixed mysqli_result::fetch_array ( [ int $resulttype = MYSQLI_BOTH ] )
// allows you to retrieve an array with numeric keys, an associative array or both
array mysqli_result::fetch_assoc ( void )
// returns an associative array of the current row
object mysqli_result::fetch_object ([ string $class_name [, array $params ]] )
// returns the current row as an object
Mysqli can be used in an object oriented(OO) or procedural way. Most programs now use the OO style. Here is an example (in the OO style).
$mysqli = new mysqli( $host, $username, $password, $dbname );
if ($mysqli->connect_errno)
{
printf( "Connect failed: %s\n", $mysqli->connect_error );
exit();
}
$_SESSION[ 'myusername' ] = $_POST[ 'myusername' ];
$result = $mysqli->query
( "SELECT statsight from playerinfo WHERE username = '".
$mysqli->real_escape_string('myusername' )."'";
$data_array = $result->fetch_assoc();
//$result is a mysqli_result object.
//$data_array is an array of field_name=>value pairs.
if( !isset( $_SESSION[ 'myusername' ])) header( "location:mainlogin.php" );
echo $data_array[ 'statsight' ];
$mysqli->close();
$result->free();
?>
<html>
<body>
Login Successful
<form name="form2" method="post" action="stat.php">
Stat1: <?php echo "<td>".$data_array[ 'statsight' ]."<td>"?>
<input type="submit" value="+">
</form>
</body>
</html>
this is probably the most basic question in the world, but I cannot figure it out.
I would like to simply display a users First name, and Email adress from my table. I have tried using a loop, but that was entirely worthless considering I am only selecting one row. I know this is a menial question but I could not find/remember how to do it. Thank you!
$db = mysql_connect("server","un", "pw");
mysql_select_db("db", $db);
$sql = "SELECT FirstName, EmailAddress"
. " FROM Student"
. " WHERE StudentID = '$student' ";
$result = mysql_query($sql, $db);
$num = mysql_num_rows($result);
$userinfo = mysql_result($result,$userinfo);
$student is a session variable. I want to echo the First name and email address somewhere in the page, but I cannot believe how much pain thats causing me. Thanks again!
mysql_fetch_assoc() turns a result row into an array.
$result = mysql_query($sql, $db);
$user = mysql_fetch_assoc($result);
echo $user['FirstName'];
echo $user['EmailAddress'];
It looks like you spelled address wrong, so it probably doesn't match your real column name. More importantly, your code appears vulnerable to SQL injection. You really need to use prepared statements (see How to create a secure mysql prepared statement in php?) or escaping.
To fetch a row, you must use one of the mysql_fetch functions (e.g. mysql_ fetch_ array, mysql_ fetch_ object, etc.)