Checking already existing username or not MySQL, PHP - 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".

Related

Retrieving value from database and checking it with PHP [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 5 months ago.
I am trying to retrieve some value from a column in the database.
The idea is to retrieve the IP of the person, then check their country, after that check the database if the country is blacklisted or not. There seems to be something wrong in the code, may you please give an advise?
This is the code:
<?php
//Get IP and country name
$ip=$_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("https://get.geojs.io/v1/ip/country/$ip.json"));
$country=$details->name;
$servername = "localhost";
$username = "My_Username";
$password = "My_password";
$dbname = "Database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT country_name FROM uni_country";
$result = $conn->query($sql);
if (strpos($result, $country) == true) {
echo $country ." " . "is banned";
} else {
echo "Your country is not banned";
}
$conn->close();
?>
When I run it, it shows "Your country is not banned" - when it should actually say that my country is banned (I added a country to the database to test this).
The issue seems to be with reading the data from the database.
If I do echo $country; --> It actually shows my country, so it is retrieving it correctly (from geojs.io). But the code is not pulling the data from the database and verifying it.
Update:
If I do echo $result; the page returns Error 500.
Update
tried this new code, now it's saying that the country is not in the database, although it is actually there.
<?php
$ip=$_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("https://get.geojs.io/v1/ip/country/$ip.json"));
$country=$details->name;
$conn = mysqli_connect("localhost", "database", "password", "username");
$query = mysqli_query("SELECT * FROM `uni_country` WHERE country_name = '$country'");
if(mysqli_num_rows($query)>0) {
echo "Country Is in the database";
}
else {
echo "Country is not in the database";
}
?>
After trying for hours, this is the correct code:
<?php
$ip=$_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("https://get.geojs.io/v1/ip/country/$ip.json"));
$country=$details->name;
// Create connection
$servername = "localhost";
$username = "MyUsername";
$password = "MyPassword";
$database = "MyDatabase";
$conn = new mysqli($servername, $username, $password, $database);
$sql = "SELECT * FROM uni_country WHERE country_name ='$country'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "You country is currently banned.";
}
} else {
echo "Your country is not banned!";
}
?>

How to use PHP SQL with where Clause? [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I want to select an email from the DB which needs to return the related Account_ID
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "connected accounts details";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT acc_id FROM users
WHERE
email = $user_email";
$result = $conn->query($sql);
echo "$result";
$conn->close();
This code returns nothing, just blank.
While using the same connection/db data is being inserted in db successfully.
Try this code
// Php Sql Select From DB....
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "connected accounts details";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `acc_id` FROM `users` WHERE `email` = ?";
$result->$conn->prepare($sql);
$result->bind_param('s',$user_email);
$result->execute();
$data = $result->get_result();
// Fetch all
$data->fetch_all(MYSQLI_ASSOC);
print_r($data);
$mysqli -> close();
// #link http://php.net/manual/en/mysqli-result.fetch-all.php
$sql = "SELECT acc_id FROM users
WHERE
email LIKE '%$user_email%' ";
$result = mysqli_query($conn, $sql);
$row = $result->fetch_assoc();
$id = $row['acc_id'];
echo "$id";
$conn->close();
Got the wanted Record, trying this way.
Thanks everyone answering on this post.

Mysql not connecting to server through 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;

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.

Categories