fields and bind_param / ajax post request - php

I am trying to create a PHP login system. I am at the point where I have logged the user data into session variables, as well as into a user database using mysqli. When a user creates an account they get redirected to a profile page. On this page I am trying to display the user's email, and the user's username. I have no problem displaying the username as I stored it in a session variable. However, I can't seem to figure out how to get the email displayed. I did not store the email in a session variable. I am trying to retrieve it from the user database (not the session database). Here is some code:
showuser.php (profile page):
<?php
session_start();
$host="localhost"; // Host name
$uname="root"; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="users"; // Table name
// Connect to server and select database.
$mysqli = mysqli_connect($host, $uname, $password, $db_name);
$stmt = $mysqli->prepare("SELECT email FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($em);
$stmt->fetch();
?>
<h2>Username - Email</h2>
<div id="userinfo"><? echo $_SESSION["username"] ?> - <? echo $em ?></div>
<?
$stmt->close();
mysqli_close($mysqli);
?>
storeuser.php
<?php
session_start();
$host="localhost"; // Host name
$uname="root"; // Mysql username
$password=""; // Mysql password
$db_name="itit"; // Database name
$tbl_name="users"; // Table name
// Connect to server and select database.
$mysqli = mysqli_connect($host, $uname, $password, $db_name);
// Get values from form
$username=$_POST['username'];
$pw=$_POST['pw'];
$email=$_POST['email'];
$_SESSION["timeout"] = time();
$_SESSION["username"] = $_POST['username'];
$_SESSION["password"] = $_POST['pw'];
$_SESSION["loggedIn"] = true;
// Insert data into mysql
$sql = "INSERT INTO $tbl_name(username, password, email)VALUES(?,?,?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("sss", $username, $password, $email);
$stmt->execute();
?>
<?php
// close connection
mysqli_close($mysqli);
?>
application.js
$("#signupform").submit(function(e) {
e.preventDefault();
$.post('storeuser.php', $(this).serialize(), function(data){
$("#showuser").load("templates/showuser.php");
$("#userinfo").text(data);
$("#signupform").remove();
});
});
It was pointed out to me in a previous question I had (regarding PDO) - that for the email to get displayed on the profile page, I need to pass a "data" variable to my ajax $.post() call. Where does "data" get set? And, what is in "data"?
One weird thing is that if I replace this line:
$stmt->bind_param("s", $email);
to this:
$stmt->bind_param("s", $_SESSION["email"]);
the email gets displayed...but I never store the email in the session anywhere! There isn't even an email field! Why would the latter work, and not the former?

You are looking for an e-mail (using an undefined variable $email) instead of the user, you probably want this:
$stmt = $mysqli->prepare("SELECT email FROM users WHERE username = ?");
$stmt->bind_param("s", $_SESSION["username"]);
instead of this:
$stmt = $mysqli->prepare("SELECT email FROM users WHERE email = ?");
$stmt->bind_param("s", $email);

Related

Displaying a post issue php

So, I have this system where you can make a post. So, how it works is, there is an input field, whatever you type in the input field, and click post, it will send to the database as en entry and get posted. The post will be displayed. However, with my current system, after entering something in the input field, and clicking post, the entry gets sent to the database, but the post doesn't actually display. For it to display, you need to refresh the page again, which it displays then, and two entries go to the database.
I don't want this to happen. Right when the user enters text into the input field and clicks post, the post should display on the go, you shouldn't have to refresh for the post to be displayed, and only one entry should be sent to the database, not two. Now, I won't include my database connection and my insert statements, but here is the code to display the post:
<div class="textPost">
<?php
$sql = "SELECT * FROM posts";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<div class="textpostFormat">
// all the displayed post content
</div>
<?php
}
}
?>
</div>
Insert Statement (post.php):
<?php
session_start();
// Making Connection To The Database
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "root";
$database = "feed";
$connection = mysqli_connect($dbHost, $dbUser, $dbPass, $database) or die ("Sorry, we could not connect to the database");
// Posting System
if (!empty($_POST['postContent'])) {
$post = $_POST['postContent'];
$firstname = $_SESSION['firstname'];
$lastname = $_SESSION['lastname'];
$sql = "INSERT INTO posts (firstname, lastname, body, date_posted) VALUES (?, ?, ?, NOW())";
$stmt = mysqli_stmt_init($connection);
// nested if statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "";
} else {
mysqli_stmt_bind_param($stmt, "sss", $firstname, $lastname, $post);
mysqli_stmt_execute($stmt);
}
} else {
echo "";
}
?>
What should I do to resolve this issue? Please help.
table.php
queries the database and delivers a table - the "textPost" file
lets the user add another row and sends it to post.php
post.php
inserts the data into the database
uses require_once to include table.php which will display the updates. require_once 'table.php';

display database info on next page after loggin in using session

I'm new to PHP and I'm going to try to explain it the way I could :D. I'm trying to accomplish when the user logged in (using username and password), it opens a new page with the users name, address etc.
In my database table, I have a username, password, name and address.
I was able to accomplish the login page using session but would like to how to get/fetch those information like name and address to the new page it opens.
Thank you,
MD :)
correct me if i'm wrong.
Here is how u fetch the information from a certain table by using PHP and MySQL(PhpMyAdmin) database.
$conn = mysqli_connect("localhost", "root", "", "hotel"); //Connecting to the database
if($conn){
$sql = "SELECT USER_NAME, USER_PASS FROM USER"; //SELECT statement
$result = $conn->query($sql); //Executing the statement
if(mysqli_query($conn, $sql)){ //If query success
while($row = $result->fetch_assoc()){ //While loop to retrieve all data
$user = $row["USER_NAME"]; //Assign Column USER_NAME in database to $user
$pass = $row["USER_PASS"]; //Assign Column USER_PASS in database to $pass
echo $user."</br>".$pass."</br>"; //Displaying the content
}
}else{
echo "Query failed";
}
}else{
die("Fatal Error");
}
$conn->close(); //Close the database connection

Mysql 5.7 checking user credentials via PHP

i am beginner in PHP and MySQL. I am trying validate user inputs (Username and Password) in MySQL 5.7 DB but no chance. Let me explain my problem;
I created a user in firstdb with username: firstuser password: firstpassword via phpMyAdmin page.
CODE (check_user-pass.php)
<?php
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="rootpassword"; // Mysql password
$db_name="firstdb"; // Database name
$tbl_name="mysql.user"; // Table name
$conn = new mysqli($host, $username, $password, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Define $username and $password
$myusername=$_POST['EMail'];
$mypassword=$_POST['Password'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = mysqli_real_escape_string($conn,$_POST['EMail']);
$mypassword = mysqli_real_escape_string($conn,$_POST['Password']);
$sql="SELECT * FROM $tbl_name WHERE user='$myusername' and authentication_string='$mypassword'";
$result = $conn->query($sql);
$count = 0;
// Mysql_num_row is counting table row
if ($result = mysqli_query($conn, $sql)) {
/* determine number of rows result set */
$count = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $count);
/* close result set */
mysqli_free_result($result);
}
// If result matched $username and $password, table row must be 1 row
if ($count==1) {
echo "Success! $count";
} else {
echo "Unsuccessful! $count";
}
ob_end_flush();
?>
Code return: Connected successfullyResult set has 0 rows. Unsuccessful! 0
If i remove this line: and authentication_string='$mypassword'Code return: Connected successfullyResult set has 1 rows. Success! 1
I succesfully retrieve user inputs from index.php to check_user-pass.php but there is no clear password column in mysql.user table for matching in database.
I search over net and find; password column changed to authentication_string in 5.x but this column carry the hashed thing. So i can't match the user password with this.
Question 1
Should i create a table and store the username and clear password for every user in DB for validating?
Question 2
If question1 answer is NO, how can achieve this validation problem?
I've done so many logins for people I just wrote a class for myself, its on github if you're interested
https://github.com/wazimshizm/secure-login
for easiest out of the box authentication, use this for storing & comparing passwords:
password_hash($passwordVariable, PASSWORD_DEFAULT);
password_verify($inputPassword, $storedPassword);

link database and stmt and prepare

I want to write a mysql php code
if I put the ID and passwd it will check with database
and link to the login success or login fail.
but my code it failed to go to the login success even though id and passwd is correct
$mysqli = new mysqli('localhost', 'root', '', 'project');
$username = $_POST['username'];
$password = $_POST['password'];
//to check whether the username exists or not
$stmt = $mysqli->stmt_init();
$stmt->prepare("select pid, password from person where pid = '$username' and passwd = '$password'");
$stmt->bind_param('ss', $username, MD5($password));
$stmt->bind_result($result,$result2);
$stmt->execute();
Im not sure my prepare statement and the bind_param is in the right position.
it should compare the MD5(password) (encrypted) password with input password
**
if ($stmt->fetch())
{
session_start();
$_SESSION['pid'] = $username;//login id
header('Location: Login Successfully.php');
exit();
}else{
$_SESSION['pid'] = $username;
header('Location: Failed to login.php');
}
**
and this is my fetch. but it always go to the failed to login.php
this is my login.php before execute above code. it get the input id and passwd and pass it to the fetch code.
Login:
Enter your username and password below:
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value="Submit" />
When using prepare(), you need to use placeholders ? instead of the actual variables. Also it looks like passwd should be password. So you will want to change
$stmt->prepare("select pid, password from person where pid = '$username' and passwd = '$password'");
to
$stmt->prepare("select pid, password from person where pid = ? and password = ?");

login authentication script error

I'm trying to write a login authentication for a web based MIS. Below is the code i use.however, this doesn't login when given the username "admin" and the password "12345" even though that record was put in the data table.
This is the SQL code for the table:
CREATE TABLE accounts (
id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL UNIQUE,
password CHAR(32) NOT NULL,
last_login DATETIME NOT NULL
);
When I put echo $stmt->num_rows; 0 is returned, so I guess it means it found no matches in the database. Can anyone help me out?
Here is my code:
<?php
// Sanitize incoming username and password
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
// Connect to the MySQL server
$db = new mysqli("localhost", "root", "qwerty", "MIS");
// Determine whether an account exists matching this username and password
$stmt = $db->prepare("SELECT id FROM accounts WHERE username = ? and password = md5(?)");
// Bind the input parameters to the prepared statement
$stmt->bind_param('ss', $username, $password);
// Execute the query
$stmt->execute();
// Store the result so we can determine how many rows have been returned
$stmt->store_result();
if ($stmt->num_rows == 1) {
// Bind the returned user ID to the $id variable
$stmt->bind_result($id);
$stmt->fetch();
// Update the account's last_login column
$stmt = $db->prepare("UPDATE accounts SET last_login = NOW() WHERE id = ?");
$stmt->bind_param('d', $id);
$stmt->execute();
session_start();
$_SESSION['username'] = $username;
// Redirect the user to the home page
header('Location: http://localhost/');
}
?>
You code appears to be okay
When you enter a new record, make sure you don't enter the plain password string, you should enter the md5 hash value of the password since your code looks for the hash value and not the
original string.

Categories