Mysql not connecting to server through php - php

I have been trying to connect to the mysql server through php code, but was unable to. Please help me solve this problem.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$bool = true;
mysql_connect("localhost", "root","rot_darshan") or die("Cannot connect to server"); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$query = mysql_query("Select * from users"); //Query the users table
while($row = mysql_fetch_array($query)) //display all rows from query
{
$table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
if($username == $table_users) // checks if there are any matching fields
{
$bool = false; // sets bool to false
Print '<script>alert("Username has been taken!");</script>'; //Prompts the user
Print '<script>window.location.assign("register.php");</script>'; // redirects to register.php
}
}
if($bool) // checks if bool is true
{
mysql_query("INSERT INTO users (username, password,fname,lname,email) VALUES ('$username','$password','$fname','$lname','$email')"); //Inserts the value to table users
Print '<script>alert("Successfully Registered!");</script>'; // Prompts the user
Print '<script>window.location.assign("register.php");</script>'; // redirects to register.php
}
}
?>

Please avoid the native mysql_* functions. These are depricated and will be removed:
http://php.net/manual/en/function.mysql-connect.php
Try to follow (mysqli_*):
https://www.w3schools.com/php/php_mysql_connect.asp
$servername = "localhost";
$username = "root";
$password = "rot_darshan";
$database = "first_db";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//Query example
$result = $conn->query("SELECT * FROM users")
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["username"]);
}
If these don't work, check your database credentials (username, password, database name and/or port)

Check for username,password by externally connecting .also replace localhost with 127.0.0.1 or your lan ip.
Check SELECT User, Host FROM mysql.user;

Related

My PHP login system still Logging in even if the password or username is incorrect

Still loggin in even if the username and password is incorrect and also logins even if the value is null
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "login";
$conn = mysqli_connect($hostname, $username, $password, $dbname);
if (!$conn) {
die ("unable to connect");
}
if ($_POST) {
$uname = $_POST ["username"];
$pass = $_POST ["password"];
$sql = "SELECT * FROM users WHERE username = '$uname' AND password = '$pass' LIMIT 1 ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1){
include("graph.php");
} else {
echo "Incorrect";
}
}
?>
First of all and very important it that you are open to SQL Injection attack, so you should use prepared statements, here is how should use your code, but instead of echo "Incorrect"; you should render different answer for each case:
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "login";
$conn = mysqli_connect($hostname, $username, $password, $dbname);
if (!$conn) {
die ("unable to connect");
}
if (isset($_POST["username"]) && isset($_POST["password"])) { // Check if you have posted data via POST
$uname = $_POST["username"];
$pass = $_POST["password"];
$sql = "SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1 ";
if($stmt = $conn->prepare($sql)) { // Check for MySQL errors
$stmt->bind_param('ss', $uname, $pass);
if ($stmt->execute()) {
$stmt->close();
include("graph.php");
} else { // There is a problem with your SELECT // bind params
echo "Incorrect";
}
} else { // You should handle mysql errors here
echo "Incorrect";
}
} else { // You don't have POST data
echo "Incorrect";
}
?>
Prepared statements
Like #Kuya notice you have and many other problems, there is a lot of tutorials in Google about implementation of login system.
You must check the post request with isset() in php like this :
<?php
if (isset($_POST["username"] && isset($_POST["password"]))) {
//..... Your code here
}else {
echo "Incorrect password or username";
}
?>

Checking already existing username or not MySQL, PHP

I Cannot Check whether the username already exist in database. I gone through existing questions that were answered here. None of them solved my problem. When i executes, it displays "Cannot select username from table", which i given inside die block. Code Is given below.
<?php
$username = $_POST['user_name'];
$password = $_POST['pass_word'];
$host = "localhost";
$db_username = "root";
$db_password = "";
$db_name = "my_db";
//create connection
$conn = #new mysqli($host, $db_username, $db_password, $db_name);
if (isset($_POST["submit"]))
{
# code...
//check connection established or not
if ($conn->connect_error)
{
die("Not Connected to DB");
}
else
{
$query = "SELECT 'usernamedb' FROM 'registration' WHERE usernamedb='$username'";
$result = mysqli_query($conn, $query) or die('Cannot select username from table');
if (mysqli_num_rows($result)>0)
{
$msg.="This username already exist. try Another !!";
}
else
{
$insert = "INSERT INTO 'registration'('id', 'usernamedb', 'password') VALUES ([$username],[$password])";
$insert_result = mysqli_query($conn,$insert) or die('INSERTION ERROR');
}
}
$conn->close();
}
?>
Hope someone will answer me.
First of all you should not use those unescaped queries.
But regarding your question you have an SQL error on your queries. You quoted table name. "FROM 'registration'" should be "FROM registration".

My code does not write anything on the database

This is my CODE, id do not know where is the mistake but this code does not create any information on the database.
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db($dbhandle);
if(isset($_POST['user']) && isset($_POST['pass'])){
$user = $_POST['user'];
$pass = $_POST['pass'];
$query = mysql_query("SELECT * FROM users WHERE Username='$user'");
if(mysql_num_rows($query) > 0 ) { //check if there is already an entry for that username
echo "Username already exists!";
}else{
mysql_query("INSERT INTO users (Username, Password) VALUES ('$user', '$pass')");
header("location:begin.html");
}
}
mysql_close();
?>
Forget database name here.
change this:
$selected = mysql_select_db($dbhandle);
With
$selected = mysql_select_db($dbname,$dbhandle);
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db($dbhandle);
In above code you are not passing any database name to use, you should pass a database name instead of connection link to mysql_select_db($dbhandle);
like
$db_selected = mysql_select_db('foo', $link);
For reference
http://php.net/manual/en/function.mysql-select-db.php
Hi first of all Please use mysqli or PDO as mysql is depreciated and completely removed from PHP7.
Now your problem . You are not included database name in your mysql_select_db. It should be
$selected = mysql_select_db($dbhandle , $databasename) or die(mysql_error($dbhandle));
Always remember try to echo error after any query this will solve your problem in many cases

php delete record using id

This program is meant to delete a record when given the id.
php:
if ($_GET['type']=="file"){
$servername = "localhost";
$username = "****";
$password = "****";
$dbname = "****";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_error($conn)) {
die("Connection failed: " . mysqli_connect_error($conn));
}
$sql = "SELECT id,user, FROM CreationsAndFiles WHERE id =".$_GET['id']." LIMIT 1";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_assoc($result);
if ($row['user'] == $login_session){
$sql = "DELETE FROM CreationsAndFiles WHERE id=".$_GET['id'];
if(mysqli_query($conn, $sql)){echo "deleted";}
}
mysqli_close($conn);
//header("location: index.php?page=CreationsAndFiles");
}
the header is type=file&id=9
there is a record where id=9
It for no apparent reason will not work.
Your SQL syntax is wrong;
SELECT id,user, FROM CreationsAndFiles...
^ extra comma
should be simply
SELECT id,user FROM CreationsAndFiles...
You may want to sanitize your input though, for example simply entering type=file&id=id will most likely do bad things.

Trouble connecting data to MySQL

I can't seem to find out why my PHP code won't allow me to store the info in MySQL when I click the submit button. Can someone tell me whats wrong with the code below?
I want to get it to the point where users submit their registration form and their info can get moved over to a MySQL database. Then, I want the users to be taken to my index.html file.
Any help is appreciated.
Thanks
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$mysql_database = "21st";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Could not connect database");
mysqli_select_db($conn, $mysql_database) or die("Could not select database");
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
if ($password == $password2) {
$sql = "INSERT INTO members (username, email, password) VALUES ('$userrname','$email','$password')";
} else {
echo "Your passwords must match";
}
?>
Try this using mysqli_query to actually run the query. When you set $sql all that did was set a variable named $sql to the query. Also note you set the variable $userrname in the query when it should be $username as set from the $_POST directly above. My adjusted version of your code below:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$mysql_database = "21st";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Could not connect database");
mysqli_select_db($conn, $mysql_database) or die("Could not select database");
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
if ($password === $password2) {
// Set the query.
$sql = "INSERT INTO members (username, email, password)"
. " VALUES (?, ?, ?)"
;
// Bind the values to the query.
mysqli_stmt_bind_param($sql, 'sss', $username, $email, $password);
// Run the query.
mysqli_query($conn, $sql);
// Free the result set.
mysqli_free_result($sql);
// Close the connection.
mysqli_close($conn);
}
else {
echo "Your passwords must match";
}

Categories