PHP&MySQL signin form-error with accessing database table - mysql

I want my users to be able to sign in using their accounts, so I created an html form and a php file that will communicate with mySQL database.
The php code is supposed to check whether the username and password are correct and exist in the database. If so the user is granted access. I am thinking such algorithm:
<?php
//connection_start
$mysqli = new mysqli('mysql3.000webhost.com','a4305565_os','******','a4305565_users');
//check_connection
if($mysqli->connect_error){
die("Connection error (check_connection): " . $mysqli->connect_errno . " : " . $mysqli->connect_error );
exit();
}
//check_if_account_exists
$query = mysql_query("SELECT * FROM `users` where `username` = '$_POST[form_username]' AND `password` = '$_POST[form_password]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
//verification
if(!empty($row['username']) AND !empty($row['password'])){
echo "SUCCESSFULLY SIGNED IN.";
}else{
die("Your are not registered yet.");
}
//Connection_end
$mysqli->close();
?>
But when I test the code on my web host, it is giving me an error on line 14 saying that I
do not have access to the database "a4305565_users" with password=NO
or something like that.
Any help please?

Your user don't have any rights on a4305565_users schema.
Edit your user privileges to give him the rights to use this schema.
Also it's kind of weird that you are creating a schema named "users", this sounds more like a table name.
And, as a word of advice, you should hash your users password, it's a very bad practice to store them in plain text.
Also, you can salt your hashes.
Look at this : https://en.wikipedia.org/wiki/Salt_(cryptography)

Related

Admin panel - Creating an edit users button

I've created an admin panel on my website so when the admin logs in he can edit users. I'm trying to get it to create a table that displays a list of all the users on the database, however, when I run it I get the error:
No database selected
Here is the code in my editusers.php:
<?php
include 'adminpage.php';
include 'connection.php';
$sql = "SELECT * FROM Users";
$result = mysql_query($sql)or die(mysql_error());
echo "<table>";
echo "<tr><th>UserID</th><th>First Name</th><th>Last Name</th><th>Email</th><th>D-O-B</th></tr>Username</th><th>Password</th><th>";
while($row = mysql_fetch_array($result)){
$userid = $row['UserID'];
$firstname = $row['FirstName'];
$lastname = $row['LastName'];
$email = $row['Email'];
$dob = $row['DateofBirth'];
$username = $row['Username'];
$password = $row['Password'];
// Now for each looped row
echo "<tr><td style='width: 200px;'>".$userid."</td><td style='width: 200px;'>".$firstname."</td><td>".$scale."</td><td>".$lastname."</td><td>".$email."</td></tr>".$dob."</td></tr>".$username."</td></tr>".$password."</td></tr>";
} // End our while loop
echo "</table>"
?>
First of all it looks like you are using mysql which isn't a wise move. This is because Mysql is actually deprecated and was improved to mysqli. Your problem may be to do with your database connection. You also haven't set a database. Like I said you can set an active database in your connection script. It should or could look something like this.
<?php
$conn = mysqli_connect("localhost", "root", "password", "database");
// Evaluate the connection
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
?>
After that, your sql query is correct by selecting all from you table 'users' but in order to proceed I recommend creating a query where you use mysqli_query an select the $sql and $conn as parameters. In all honesty it is much advised to stop and continue once you have adapted to mysqli. Alternatively you can use PDO which in some cases can be seen as better to use rather than mysqli but the choice is yours. I personally would get to grips with mysqli and then look at some answers on Stack Overflow to decide whether you should use PDO or not. Visit the PHP manual here. Enter all the mysql functions you know and it will show you how to use the new mysqli version of the functions. Don't think that it is as simple as just adding and 'i' to the end of a mysql function. That's what I initially thought but there is alot to do with extra parameters etc. Hope this helps :-)

Login with url paramaters

I'm creating a login system of sorts that uses parameters from the URL.
The parameters are set no problem. I dont know what the issue is.
Here's my code:
<?php
require_once("db_const.php");
$mysqli = new mysqli("dont", "try", "to login to", "my database");
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$username = filter_input(INPUT_GET,"username",FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_GET,"password",FILTER_SANITIZE_STRING);
$sql = "SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1) {
echo "failed";
} else {
echo "success";
}
?>
There are a few problems with your code.
The problem is the use of the LIKE function. Your usage is
SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1
Like requires additional specification to find match positions and such, for example :
SELECT ... WHERE username LIKE '%{$username}%'
In the form you used, the WHERE clause if equivalent to
SELECT ... WHERE username = '{$username}'
In addition, LIKE is not recommended even (especially) with the wildcards, as 'tom' will match users 'tom' and 'tommy', and the count will certainly not be == 1.
I'll also urge you to test the query for errors
if (!$result) {
echo 'An error occurred : $mysqli->error;
}
Others have already mentioned the risk in passwing username and passwords on the URL, Please take note of their comments.
In addition, storing the password in plain form the database is not recommended for security reasons. There are plenty of resources explaining how to encrypt passwords and authenticate using the encrypted values.
Try:
$sql = "SELECT * from users WHERE username='$username' AND password='$password'";
CAUTION
Even if the above code solves your problem, It's still very dangerous as it's vulnerable for SQL injection on both username and password parameters and it can be exploited in a manner that a malicious user can bypass the login check by breaking out of the quotes and adding a condition that evaluates to true.
You can use a mysqli::prepare to get over that.
$stmt = mysqli->prepare("SELECT * from users WHERE username=? AND password=?");
$stmt->bind_param("ss", $username,$password);
$stmt->execute();

php/mysql:what's the idea to active/inactive a code from being executed

i have a php code to show online users,my question is that how to make an option(yes,no) in the admin panel to control the appearance of enabling or disabling the code
just i want to know the idea for making something like that?what are the fields required?what are the queries to do that?
or an article discuss the process of activate or in activate some code from being executed according the state of selected option(y,n)
and a practical snippet for that.......
session_start();
$session=session_id();
$time=time();
$time_check=$time-600; //SET TIME 10 Minute
$host="localhost"; // Host name
$username="advphp_advphp"; // Mysql username
$password="112233"; // Mysql password
$db_name="advphp_download"; // Database name
$tbl_name="user_online"; // Table name
// Connect to server and select databse
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name WHERE session='$session'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count=="0"){
$sql1="INSERT INTO $tbl_name(session, time)VALUES('$session', '$time')";
$result1=mysql_query($sql1);
}
else {
"$sql2=UPDATE $tbl_name SET time='$time' WHERE session = '$session'";
$result2=mysql_query($sql2);
}
$sql3="SELECT * FROM $tbl_name";
$result3=mysql_query($sql3);
$count_user_online=mysql_num_rows($result3);
echo "المتواجدون الان : "; echo $count_user_online + 30;
// if over 10 minute, delete session
$sql4="DELETE FROM $tbl_name WHERE time<$time_check";
$result4=mysql_query($sql4);
mysql_close();
You can think of the list of online users as a module that you can configure from a back end.
Keep a XML file with the list of all the modules and their statuses (enabled/disabled) and allow the user to disable/enable the module from the back end by setting the right value for the module name in the XML file.
When you need to check the module you can either load the XML file and check the status or just keep a session variable with the statuses of the modules and decide according to that variable weather to show it or not.
For each user add an extra field called privilege which stores if user has admin, special privilege
Write a php page like admin.php
if the logged in user has admin privilege then include the admin.php page in their homepage or else do not include the admin.php
admin,php will contain the additional features for an admin user
query
select username, status from tableName
where loginName='$user' and password='$password';
then in code
if(row['status'] == 'admin')
{
include_once('admin.php');
}

Issues gathering SMS messages into MySQL

I am currently learning web development and trying to put together a simple application in PHP that stores SMS messages from phones of all mobile types, both smart and the non, into a MySQL database hosted on a webserver. I will do some other things later with these strings once stored, but struggling right now to get this whole thing working.
I have been trying to use this here platform:
http://www.txtweb.com/
which allows delivery to web apps of a message, a "location key" in the form of an # keyword, and the number of the texter. It then returns information to user with an html request, where all thats in the body tags gets returned. They don't have any direct examples of MySQL interfacing, nor any discussion in the forums. Here I have followed one of their code samples, can get the return text to work, but fail to get any action in the database. Does anyone out there perchance have advice of either a better method for gathering SMS messages into a MySQL database or perhaps some obvious flaws in my code? I will put what I am trying below, and much appreciate the help.
<?php
define("DB_SERVER", "...");
define("DB_USER", "...");
define("DB_PASS", "...");
define("DB_NAME", "...");
=$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database connection failed: " . mysql_error()); }
$db_select = mysql_select_db(DB_NAME,$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
} ?>
<html>
<head>
<meta name=\"txtweb-appkey\" content=\"VALUE ASSIGNED BY PLATFORM\">
</head>
<?php if(isset($_GET['txtweb-message'])) $message = $_GET['txtweb-message'];
if(isset($_GET['txtweb-mobile'])) $number = mysql_prep($_GET['txtweb-mobile']);
if(isset($_GET['txtweb-location'])) $location = mysql_prep($_GET['txtweb- location']);
$query = "INSERT INTO ... (
`Number`, 'Message', 'Location' )
VALUES (
'{$message}', '{$number}', '{$location}' )";
mysql_query($query, $connection); ?>
<body>
"message to user, yet to be determined"
</body>
</html>
<?php mysql_close($connection); ?>
You are using single quotes (') to encase your column names. MySQL won't like that. You should be using backticks (`) to encase column names.
Notice that Number uses backticks and Message and Location use single quotes.
`Number`, 'Message', 'Location'
try:
`Number`, `Message`, `Location`
Might be worth making a call to mysql_error ?
print mysql_error();
Call that after
mysql_query($query, $connection);
When you do this, any errors from the query are shown on the page.

'ODBC'#'localhost' error while updating

Im getting this error when Im trying to update data in the database.
this is my database.php file
<?php
$db_name = "db";
$db_server = "localhost";
$db_user = "xxxx";
$db_pass = "zzzzzzzzz";
$mysqli = new MySQLi($db_server, $db_user, $db_pass, $db_name)
or die(mysqli_error());
?>
update.php
<?php
require 'database.php';
$title = mysql_real_escape_string($_POST['title']);
$id = mysql_real_escape_string($_POST['id']);
$update_query = "UPDATE photos SET title = '$title' WHERE id='$id'";
$result = $mysqli->query($update_query) or die(mysqli_error($mysqli));
if ($result) {
echo "Success!";
echo "The title of this photo has been changed to: <strong>$title</strong>";
}
?>
The error message:
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'ODBC'#'localhost' (using password: NO) in C:\wamp\www\myPhotosWebsite\changePhotoTitle.php on line 5
You are mixing procedural and object-oriented style calls.
Try:
$title = $mysqli->escape_string(_POST['title']); /* Call as a method */
instead of:
$title = mysql_real_escape_string($_POST['title']);
real_escape_string requires a valid connection handle, as it needs to know the connection character set.
If you call it as a procedure, you should pass the connection handle as a first param:
mysql_real_escape_string($connection_handle, $string_to_escape)
or just call it as a method as described above.
See mysqli_real_escape_string for more detail
In your mysql connect() it seems that your user name/password combination is being denied access to mysql, you might want to check your details and try again.
mysql_real_escape_string requires a database connection to operate on. Unless you pass one explicitly, that means you have to call mysql_connect() first. But you're using a MySQLi() object to get the connection instead. I don't think using MySQLi() will set the default connection mysql_ family functions. Certainly,
(using password: NO)
implies it is not getting the $db_pass.
It's best to stick to either ‘mysql’ or ‘mysqli’, rather than try to mix both. If you're using MySQLi you might want to take advantage of parameterised statements to avoid having to call $mysqli->escape_string() explicitly.
PS.
echo "The title of this photo has been changed to: <strong>$title</strong>";
$title is SQL-escaped, but not HTML-escaped. It will have unwanted backslashes in whilst not preventing HTML-injection (XSS attacks). Instead:
echo 'The title of this photo has been changed to: <strong>'.htmlspecialchars($_POST['title']).'</strong>';