I have a script that updates/creates user from an iOS device. Now i want to have the script also check if the user already exists in the database. I am going to restrict this to username for now, so no more than ONE unique username may exist. I have an if-statement in my PHP but i cannot get it to work - help please :).
<?php
header('Content-type: application/json');
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
$db_name = 'dbname';
$db_user = 'dbuser';
$db_password = 'dbpass';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
$userexists = mysql_query("SELECT * FROM users WHERE username='$username'");
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
}
if(mysql_num_rows($userexists) != 0) {
echo '{"success":0,"error_message":"Username Exist."}';
}
else {
$stmt = $mysqli->prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
$password = md5($password);
$stmt->bind_param('sss', $username, $password, $email);
/* execute prepared statement */
$stmt->execute();
if ($stmt->error) {error_log("Error: " . $stmt->error); }
$success = $stmt->affected_rows;
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
error_log("Success: $success");
if ($success > 0) {
error_log("User '$username' created.");
echo '{"success":1}';
}
else {
echo '{"success":0,"error_message":"Username Exist."}';
}
}
}
else {
echo '{"success":0,"error_message":"Passwords does not match."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Username."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Data."}';
}
?>
You could SELECTthe table before trying to insert username. If it already exists (= you have a result) you dont simply insert.
Better yet, use ON DUPLICATE IGNORE or something like that.
Related
I coded this login system, but whenever I try to log in with the only username and password included in my database table, I get redirected to index.php?error=sqlerror. I checked the code for spelling mistakes but there are none. Could this be a problem with the database connection? I use MAMP. I have checked the database and it displays the Success message so it seems to be working. Do you know what I am doing wrong? Thank you!
DATABASE CONNECTION (file name: dbh.inc.php)
$servername = "127.0.0.1";
$dBUsername = "root";
$dBPassword = "";
$dBName = "gallerydatabase";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if (!$conn) {
echo "Error: Unable to connect to MySQL.";
}
echo "Success";
mysqli_close($conn);
?>
LOG-IN PHP CODE (file name: login.inc.php)
if (isset($_POST['login-submit'])) {
require 'dbh.inc.php';
$mailuid = $_POST['mailuid'];
$password = $_POST['pwd'];
if (empty($mailuid) || empty($password)) {
header ("Location: ../index.php?error=emptyfields");
exit();
}
else {
$sql = "SELECT * FROM users WHERE uidUsers=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header ("Location: ../index.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $mailuid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$pwdCheck = password_verify($password, $row['pwdUsers']);
if ($pwdCheck == false) {
header ("Location: ../index.php?error=wrongpwd");
exit();
}
else if ($pwdCheck == true) {
session_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
header ("Location: ../index.php?login=sucess");
exit();
}
else {
header ("Location: ../index.php?error=wrongpwd");
exit();
}
}
else {
header ("Location: ../index.php?error=nouser");
exit();
}
}
}
}
else {
header ("Location: ../index.php");
exit();
}
I think the problem is in your file dbh.inc.php, you create the connection $conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName); and later you close it as well mysqli_close($conn);.
So by the time you come to use $conn in login.inc.php your connection is closed. What you need to do is write a function in dbh.inc.php that returns a live connection (don't call close), use that to do your DB queries / insert and after that close the connection.
A reusable database class can be written (functional style) as follows
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
trait DBInfo {
protected $servername = "127.0.0.1";
protected $username = "root";
protected $password = "";
protected $dbname = "gallerydatabase";
}
class Database{
use DBInfo;
function __construct() {}
function connection(){
$conn = new mysqli($this->servername, $this->username,
$this->password, $this->dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else{
$conn->autocommit(FALSE);
return $conn;
}
}
function select($sql, $fn2bind_takestmt, $fn2process_row_return_result){
try{
$result = array();
$conn = $this->connection();
$stmt = $conn->prepare($sql);
$fn2bind_takestmt($stmt);
$stmt->execute();
$rowset = $stmt->get_result();
while ($row = $rowset->fetch_assoc()) {
$obj = $fn2process_row_return_result($row);
array_push($result, $obj);
}
}catch(Exception $e) {
$result = NULL;
throw $e;
}finally{
if(isset($rowset))$rowset->close();
if(isset($stmt))$stmt->close();
if(isset($conn))$conn->close();
}
return $result;
}
// You can introduce functions for insert, update and delete as well
}
?>
and then for database selects for example login check
<?php
function allow_login($user, $pwd){
$sql = "SELECT count(*) rec_count FROM users WHERE uidUsers=? and pwdUsers=?"
$db = new Database();
$result = $db->select($sql,
function($stmt) use($user, $pwd){
$stmt->bind_param("ss", $user, $pwd);
},
function($row){
if($row['rec_count'] > 0){// or whatever
return TRUE;
}
return FALSE;
}
);
if(isset($result)){
return $result[0];
}
return $result;
}
?>
Hi I'm trying to insert data in my database. But I keep on getting the same error for example:
Error: INSERT INTO users (username, password) VALUES ('fff', '$2y$10$YUd1AErIj4RGRnjkFkYlkOn.s9OV62sq8.HVGO2jeE8dSthpgp6ey');
without any details which is very frustrating. I'm new to PHP and SQL so it's not the best written code ever and I know I should use prepared statements.
<?php
require_once '../connection/connection.php';
/**
* Created by PhpStorm.
* User: ezrab
* Date: 3/14/2018
* Time: 5:40 PM
*/
$username = $_POST['username'];
$password = $_POST['password'];
//var_dump($hashed_password);
if (isset($_POST['submit'])) {
if (!empty($username) || !empty($password)) {
if (preg_match('/^[A-Za-z]?[A-Za-z ]*$/', $username) || preg_match('/^[A-Za-z]?[A-Za-z ]*$/', $password)) {
$hashPwd = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$hashPwd');";
if ($conn->query($sql) === TRUE) {
echo "Worked!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
echo "You can't use certain characters.";
}
} else {
echo "You have to fill in all fields.";
}
} else {
echo "THOU SHALL NOT PASS!";
}
$conn->close();
EDIT: Added my connection.php file for more information.
<?php
$servername = "-----";
$username = "-----";
$password = "------";
$dbname = "------";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
EDIT:
Take
$conn->close();
out of connection.php and problem should be solved
You were opening and then immediately closing the connection before a query could be made
This is the image of the warning I got
I am new and I really want to learn PHP.
<?php
include 'mysql.conf.php';
if(isset($_POST['submit']))
{
if(!empty($_POST['user']) && !empty($_POST['password']))
{
$user = $_POST['user'];
$password = $_POST['password'];
$select = "SELECT * FROM admin where user=$user && password=$password";
$sql=mysql_query($select) or die(mysql_error());
if($sql)
{
echo "Login";
}
else
{
echo "Cannot Login";
}
}
}
?>
Below is my code for the mysql.conf.php
<?php
$name = "localhost";
$user = "root";
$pass = "gasamul";
$connect = mysql_connect($name, $user, $pass) or die(mysql_error());
$db = "portfolio";
if($connect)
{
$db = mysql_select_db($db) or die(mysql_error());
if($db)
{
//echo 'Database Connect';
}
}
else
{
echo 'Database can\'t connect';
}
?>
The name of my database is portfolio. I also named my table admin.
Since the error is stating clear that mysql_* extension is already deprecated and it is suggesting that you use mysqli_* or PDO extension.
Lets try the first option - mysqli_*. We establish first the connection to your database in mysql.conf.php:
$connect = new mysqli("localhost", "root", "gasamul", "portfolio");
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
Then, we can proceed with logintest.php:
include 'mysql.conf.php';
if(isset($_POST['submit']) && !empty($_POST['user']) && !empty($_POST['password']))
{
if($stmt = $con->prepare("SELECT * FROM admin WHERE user = ? AND password = ?")){ /* PREPARE YOUR QUERY */
$stmt->bind_param("ss", $_POST['user'], $_POST['password']); /* BIND THESE TWO VARIABLES TO THE QUERY ABOVE RESPECTIVELY; s STANDS FOR strings */
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->store_result(); /* STORE THE RESULT */
$noofrows = $stmt->num_rows; /* GET THE NUMBER OF RESULT */
if($noofrows > 0){ /* CHECK IF RESULT IS MORE THAN 0 */
echo "Login";
} else {
echo "Cannot Login";
}
$stmt->close(); /* CLOSE THE PREPARED STATEMENT */
}
}
You can also check out password_hash() for securing your password in your database.
Morning All,
Im after a bit of advice/help with the below issue.
i have tried looking around and google'ing but I still don't understand where I'm going wrong. Please forgive me as I'm a complete noob at this.
some of you may have seem this code before but I'm want to adapt it. Once the user logs in i want to get the user ID from the MySQL Database and send that to swift in the JSON but i can't get it to work, i have tried putting the query in different places with no luck, JSON is completely new to me :(
Ideally > user logs in> swift sends JSON to verify>JSON-PHP verified by MySQL > PHP - JSON reply with success AND user id from the db.
Any Help would be amazing !!
<?php
header('Content-type: application/json');
require("conn.php");
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
$db_name = '***';
$db_user = '***';
$db_password = '***';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
if ($stmt = $mysqli->prepare("SELECT username FROM users WHERE username = ? and password = ?")) {
$password = md5($password);
/* bind parameters for markers */
$stmt->bind_param("ss", $username, $password);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($id);
/* fetch value */
$stmt->fetch();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
if ($id) {
error_log("User $username: password match.");
echo '{"success":1, "ID":0}';
} else {
error_log("User $username: password doesn\'t match.");
echo '{"success":0,"error_message":"Invalid Username/Password"}';
}
}
} else {
echo '{"success":0,"error_message":"Invalid Username/Password."}';
}
}else {echo '{"success":0,"error_message":"Invalid Data."}';
}
?>
I want to check if a user exists or not.
It keeps registering users even though I added a check inside. The echo does not give me a accurate feedback on how to fix this issue.
Edit:
Code edited due to comments. It does not exit or check for the existing user.
Here is my code:
if($_POST['username']) {
if ( $password == $c_password ) {
$db_name = '*';
$db_user = '*';
$db_password = '*';
$server_url = '*';
$mysqli = new mysqli($server_url , $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
$check="SELECT * FROM USER WHERE 'Name'='". $username."'";
$rs = mysqli_query($mysqli,$check) or die(mysqli_error($mysqli));
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if($data[0] > 1) {
echo "User Already in Exists<br/>";
exit;
}
else
{
$stmt = $mysqli->prepare("INSERT INTO USER (Name, Password) VALUES (?, ?)");
$password = md5($password);
$stmt->bind_param('ss', $username, $password);
/* execute prepared statement */
$stmt->execute();
if ($stmt->error) {error_log("Error: " . $stmt->error); }
$success = $stmt->affected_rows;
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
error_log("Success: $success");
if ($success > 0) {
error_log("User '$username' created.");
echo '{"success":1}';
} else {
echo '{"success":0,"error_message":"Username Exist."}';
}}
}
} else {
echo '{"success":0,"error_message":"Passwords does not match."}';
}
} else {
echo '{"success":0,"error_message":"Invalid Username."}';
}