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."}';
}
?>
Related
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.
I've been trying for a while now to get my loginscript working and i can't seem to find the issue, either im just blind or there's something else going on here.
It doesn't matter if i input the correct credentials or not into the form, i still end up getting a lovely error 500.
Any ideas?
The DB connect funtion:
function db_connect() {
if i move this column-->
$server = 'localhost';
$uname = 'root';
$passw = 'password';
$datab = 'database';
/* check connection */
try{
$conn = new PDO("mysql:host=$server;dbname=$datab;", $uname, $passw);
} catch(PDOException $e) {
die( "Connection failed: " . $e->getMessage());
}
<---
return $conn; /added this as suggested, still returns NULL.
}
The login file:
include('../lib/functions.php'); //This is correct!
db_connect();
<-- HERE, it works -->
Earlier had an issue where my password hash during register was faulty, so password_verify($_POST['password'], $results['passw'])had no effect, always returning false even with correct input.
if(!empty($_POST['username']) && !empty($_POST['password'])):
$records = $conn->prepare('SELECT uname,passw FROM users WHERE uname = :user AND passw = :pass');
$records->bindparam(':user', $_POST['username']);
$records->bindparam(':pass', $_POST['password']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0 && password_verify($_POST['password'], $results['passw']) && $_POST['username'] == $results['uname']) //Also tried removing the &&-->username area incase two and statements were wrong without any luck {
die('It works!');
} else {
die('OR NOT!');
}
endif;
Your db_connect() function defines $conn in it's own scope. So, variable $conn is local. And after db_connect() ends executing $conn just disappears.
Outside this function $conn is simply NULL.
Return $conn to outer scope from your function:
function db_connect() {
$server = 'localhost';
$uname = 'root';
$passw = 'password';
$datab = 'database';
/* check connection */
try{
$conn = new PDO("mysql:host=$server;dbname=$datab;", $uname, $passw);
} catch(PDOException $e) {
die( "Connection failed: " . $e->getMessage());
}
return $conn; // here
}
And in your script:
include('../lib/functions.php'); //This is correct!
$conn = db_connect();
// other codes
I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo 'Connected successfully';
}
catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim
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.
I have a code that checks if a username exists or not, but when I run the code and enter in a username i inserted into my database using phpmyadmin it says the username dosent exist, am wondering where i went wrong?
here is my php code:
<?php
require_once 'connect.php';
$conn = dbConnect();
if (isset($_POST['username']))
{
$sql = $conn->prepare("SELECT COUNT(id)
FROM users
WHERE username = :username");
$sql->execute(array(":username" => $_POST['username']));
$rows_number = $sql->fetchColumn();
if($rows_number ==0)
{
echo "Username doesn't exist";
exit;
}
else
{
echo "Username already exists";
exit;
}
}
?>
here is my php connect.php:
<?php
function dbConnect(){
$db = null;
$db_host = "localhost";
$db_username ="user";
$db_pass ="pass";
$db_name = "accounts";
try{
$db = new PDO('mysql:host='.$db_host.';dbname'.$db_name,$db_username,$db_pass);
}
catch (PDOException $e) {
echo '<p>Cannot connect to database !!</p>';
exit;
}
return $db;
}
?>
Seeing as I do not have 50+ rep I can't comment but post your connect.php code and exclude the username and password so I can see if its the connect.php that's giving the problem
Edit: your problem lye's here:
';dbname'.$db_name,$db_username,$db_pass);
it should be
';dbname='
and then append on your variable $db_name. Further explanation is the ';dbname is equal to the value you gave your variable.
You may not have initialized the query statement
/* create a prepared statement */
<?php
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>