PHP echo all data from database based on input - php

I want to find out how to output data from database based on a single key,for example my database column are :
kodeDosen(PrimaryKey),namaDosen,email,telepon,password
and my login screen the user can only input kodeDosen and password,and i want to show the other data exept password,this is my register php:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$namaDosen = $data["namaDosen"];
$email = $data["email"];
$telepon = $data["telepon"];
$password= $data["password"];
$message = array("message"=>"Success");
$failure = array("message"=>"Failure,kodeDosen already used");
$sql = "INSERT INTO tbl_dosen (kodeDosen, namaDosen, email, telepon, password) VALUES ('$kodeDosen', '$namaDosen', '$email', '$telepon','$password')";
if (mysqli_query($conn, $sql)) {
echo json_encode($message);
} else {
echo json_encode($failure) ;
}
?>
and this is my login php:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$password = $data["password"];
$message = array("message"=>"Data found");
$failure = array("mesage"=>"Data not found");
if ($stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen =? and password = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $kodeDosen,$password);
/* execute query */
mysqli_stmt_execute($stmt);
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) > 0) {
echo json_encode($row);
}else {
echo json_encode($failure);
}
}
?>

It's not a good idea to insert a variable directly into an SQL query because of SQL injection.
I would suggest to use prepared statements on both of the queries. To pull the result from the db with prepared statements it's something like:
OOP style:
$stmt = $db->prepare("SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen = ? and password = ?");
$stmt->bind_param('ss', $kodeDosen, $password);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
//result is in row
var_dump($row);
}
Procedural style:
$stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen = ? and password = ?");
mysqli_stmt_bind_param($stmt, 'ss', $kodeDosen, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = $result->fetch_assoc()) {
//result is in row
var_dump($row);
}

You can change in sql SELECT statement in login.php
$sql = "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen ='$kodeDosen' and password = '$password'";
in SELECT * means return all columns.

I think you want echo json_encode($row); rather than echo json_encode($message);
Try:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$password = $data["password"];
$message = array("message"=>"Data found");
$failure = array("mesage"=>"Data not found");
if ($stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen =? and password = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $kodeDosen,$password);
/* execute query */
mysqli_stmt_execute($stmt);
/* store result */
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc( $result );
if(mysqli_num_rows($result) > 0) {
echo json_encode($row);
}else {
echo json_encode($failure);
}
}
?>

Related

CSS and nav bar issue when logged into live server

My site looks like this after login, without any navigation bar or css.
It should have included my header2.php file, which contains my nav bar and my css should be working.
Below is my code for login.php:
<?php
ob_start();
if (!isset($_POST['submit'])) {
header("Location: /../index.php?login=error");
exit();
} else {
include_once __DIR__.'/dbh.php';
include_once __DIR__.'/../header2.php';
$uid = strip_tags($_POST['uid']);
$pwd = strip_tags($_POST['password']);
$date = date("Y-m-d H:i:s");
$sql = "UPDATE users
SET user_session = ?
WHERE user_uid = ?;
";
$stmt = mysqli_stmt_init($conn);
//Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "ss", $date, $_SESSION['u_uid']);
//Run parameters inside database
mysqli_stmt_execute($stmt);
// include error handlers:
// Check to see if the inputs are empty
//Check to see if user has activated his or her account before logging in
$user_activate = 0;
if(empty($uid) || empty($pwd)) {
echo "<meta http-equiv='refresh' content='0;url=../signup.php?signup=empty'>";
exit();
} else {
// Check to see if user has activated his or her account
$sql = "SELECT * FROM users WHERE user_activate = ? AND user_uid= ?;";
$stmt = mysqli_stmt_init($conn);
//Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "is", $user_activate, $uid);
//Run parameters inside database
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0) {
echo "<meta http-equiv='refresh' content='0;url=/../index.php?signup=notactivated'>";
exit();
} else {
// Check to see if the username exists in the database
$sql = "SELECT * FROM users WHERE user_uid = ? OR user_email = ?";
$stmt = mysqli_stmt_init($conn);
//Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "ss", $uid, $uid);
//Run parameters inside database
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck < 1) {
echo "<meta http-equiv='refresh' content='0;url=/../index.php?login=notsignup'>";
exit();
} else {
// Does the password match the password in the database?
// while($row = mysqli_fetch_assoc($result));
if ($row = mysqli_fetch_assoc($result)) { // insert database results into an array
// De-hasing the password
$hashedPwdCheck = password_verify($pwd, $row['user_password']);
if ($hashedPwdCheck == false) {
$login_attempts = $row['login_attempts'];
$login_attempts += 1;
$sql2 = "UPDATE users
SET login_attempts = ?
WHERE user_uid = ?;
";
if (!mysqli_stmt_prepare($stmt, $sql2)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "is", $login_attempts, $uid);
//Run parameters inside database
mysqli_stmt_execute($stmt);
if ($row['login_attempts'] == 5) {
$login_attempts = 0;
$user_activate = 0;
$token = 'qqewreqreqwsdfdfdafcbvcQERFGHFGHGFHRETERTDF!##$%^^()';
$token = str_shuffle($token);
$token = substr($token, 0, 10);
$sql3 = "UPDATE users
SET user_activate = ?, user_token = ?, login_attempts = ?
WHERE user_uid = ?;
";
if (!mysqli_stmt_prepare($stmt, $sql3)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "isis", $user_activate, $token, $login_attempts, $uid);
//Run parameters inside database
mysqli_stmt_execute($stmt);
$company = "pianocourse101#hotmail.com";
$subject = "Account temporary deactivated due to fail login attempts";
$mailTo = $row['user_email'];
$headers = "From: ".$company;
$txt = "Dear".$row['user_first']."".$row['user_last'].", \n\nYour account has been temporary deactivated because either you or someone claiming to be you has failed to log into your account on more than 5 occasions! \n\n You can use the following information to reactivate your account: \n\n Your new token: ".$token."\n\nYou can either copy and paste the token into the relevant section or click on the following link: http://localhost/loginsystem/includes/activate.php?email=".htmlspecialchars($row['user_email'])."&activatetoken=".htmlspecialchars($token);
mail($mailTo, $subject, $txt, $headers);
}
}
echo "<meta http-equiv='refresh' content='0;url=/../index.php?login=passwordfailed'>";
exit();
}
} elseif ($hashedPwdCheck == true) {
// Log in the user here
$_SESSION['u_id'] = $row['user_id'];
$_SESSION['u_first'] = $row['user_first'];
$_SESSION['u_last'] = $row['user_last'];
$_SESSION['u_email'] = $row['user_email'];
$_SESSION['u_uid'] = $row['user_uid'];
$_SESSION['u_permission'] = $row['admin'];
$_SESSION['u_moderator'] = $row['moderator'];
$_SESSION['u_session'] = $row['user_session'];
$_SESSION['freelesson'] = $row['freelesson'];
$_SESSION['datejoined'] = $row['datejoined'];
$_SESSION['premium'] = $row['premium'];
// Insert into reward points when login
// Select names from rewards
$sql2 = "SELECT * FROM rewards WHERE user_uid = ?;";
$stmt = mysqli_stmt_init($conn);
//Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql2)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "s", $uid);
//Run parameters inside database
mysqli_stmt_execute($stmt);
$result2 = mysqli_stmt_get_result($stmt);
$resultCheck2 = mysqli_num_rows($result2);
while ($row2 = mysqli_fetch_assoc($result2)) {
$_SESSION['u_reward_points'] = $row2['reward_points'];
$points = 100;
$_SESSION['u_reward_points'] += $points;
$sql = "UPDATE rewards
SET reward_points = ?
WHERE user_uid = ?;
";
$stmt = mysqli_stmt_init($conn);
//Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "is", $_SESSION['u_reward_points'], $_SESSION['u_uid']);
//Run parameters inside database
mysqli_stmt_execute($stmt);
echo "<meta http-equiv='refresh' content='0;URL=/../header2.php?login=success' />" ;
exit();
}
}
}
}
}
}
}
}
}
}
}
}
ob_end_flush();
enter image description here
Make sure the CSS files are loaded properly if loaded from external files.
Always debug your scripts with enabled PHP Error Reporting!
The final output in the browser you can see the Source code - usually Ctrl+U, or you can debug with Developers tools - usually right click the page and do Inspect element Ctrl+Shift+I - Network tab might show you some errors, same in Console tab etc.
Both should help you to identify the problematic part of your coding.
it's seems like your css files aren't loaded.
you can check through your network tab if they do loaded.

MYSQLI Object oriented, what's wrong with my script?

I'm trying to do an execution of a query and see if it goes well, but right now it doesn't enter the IF or ELSE.
I had it on mysqli procedural and all worked flawlessy now I'm trying to change it to object oriented and it won't enter inside if/else.
if(isset($_POST['submit']))
{
$email = $_POST["email"];
$password = md5($_POST["password"]);
$query = "SELECT * FROM Users WHERE Email=? AND Password=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('ss', $email,$password);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1)
{
?>
<script type="text/javascript">
alert("INSIDE");
</script>
<?php
$row = $result->fetch_assoc();
if(isset($_POST['remember']))
{
$_SESSION["remember"] = "1";
}
$_SESSION["username"] = $row['Username'];
$_SESSION['check'] = "1";
$_SESSION['ID'] = $id;
$_SESSION['permission'] = $row['Admin'];
header("Location: dashboard.php");
exit;
}
else
{
?>
<script type="text/javascript">
alert("Credentials Are Wrong!");
</script>
<?php
exit;
}
$stmt->close();
}
Thank you all.
You should be using
$stmt->bind_result($col1, $col2 ...);
and
$result = $stmt->fetch();
in order to access the data from the query, rather than
$conn->query($stmt);
(an example is provided at https://secure.php.net/manual/en/mysqli-stmt.fetch.php). Note that for this to work you will need to specify the column names you want to fetch from the database, rather than using * in your SQL query, and for each column data is fetched from in the query, you should have a variable for in the fetch() parameters, so for example, something as follows should work (note these may not match the names of your database columns):
$email = $_POST["email"];
$password = md5($_POST["password"]);
$stmt = $conn->prepare("SELECT ID, Name FROM Users WHERE Email=? AND Password=?");
$stmt->bind_param('ss', $email, $password);
$stmt->execute();
$stmt->bind_result($id, $name);
$stmt->fetch();
$stmt->close();
echo $id . ': ' . $name;
Updated Answer
You are very close. Use $result = $stmt->get_result(); instead of $result = $stmt->query; to check to see if the query returned a result or not.
$email = $_POST["email"];
$password = md5($_POST["password"]);
$query = "SELECT * FROM Users WHERE Email = ? AND Password = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('ss', $email, $password);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows !== 0){
if(isset($_POST['remember'])){
$_SESSION["remember"] = "1";
}
$_SESSION['check'] = "1";
$_SESSION['ID'] = $row['ID'];
header("Location: dashboard.php");
exit();
}else{
echo
'<script type="text/javascript">
alert("Credentials Are Wrong!");
</script>';
exit();
}
$stmt->close();
As several have already stated in their comments do not use MD5 for password hashes. PHP has it's own built in functions for handling passwords. Please research Password_has() and Password_verify(). Spend the time to research and implement these now instead of later. It will save you time.

PDO insert not working correctly

When I login it's suppose to insert, but instead does nothing.. On my register php it inserts data to accounts, but when i insert data into online it won't work..
PS- I'm new to PDO so I don't know what i'm doing wrong
<?php
session_start();
if(isset($_SESSION['users']) != ""){
echo '<script type="text/javascript">','index();','</script>';
}
include('../php/dbConnect.php');
$username = $_POST['username'];
$password = $_POST['password'];
$query = 'SELECT * FROM `accounts` WHERE username = ?';
$queryprepare = $conn->prepare($query);
$queryprepare->bindParam(1, $username, PDO::PARAM_STR);
$queryprepare->execute();
$row = $queryprepare->fetch();
if($row['password'] == md5($password))
{
$_SESSION['online'] = true;
$_SESSION['users'] = $username;
$_SESSION['userid'] = $row['id'];
$_SESSION['name'] = $row['name'];
$_SESSION['age'] = $row['age'];
$_SESSION['image'] = $row['image'];
$check_row = 'SELECT * FROM `online` WHERE username = ?';
$check_row_fetch = $conn->prepare($check_row);
$check_row_fetch->bindParam(1, $username, PDO::PARAM_STR);
$check_row_fetch->execute();
$number_of_rows = $check_row_fetch->rowCount();
if($number_of_rows != 0) {
echo '<script type="text/javascript">','redirect();','</script>';
}
else{
$online_insert = 'INSERT INTO online (username, name, age, image) VALUES (?, ?, ?, ?)';
$online_insert_fetch = $conn->prepare($online_insert);
$online_insert_fetch->bindParam(1, $SESSION['users'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(2, $SESSION['name'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(3, $SESSION['age'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(4, $SESSION['image'], PDO::PARAM_STR);
$online_insert_fetch->execute();
echo '<script type="text/javascript">','redirect();','</script>';
}
}
else{
echo("Wrong Credentials");
}
?>

Check if already a user then insert into the database php

My code works, if I wish to insert into the database, but my checking whether the user already exists doesn't work.
*I thought the idea was to check if a row exists already with that username, if so don't add that user to the database, else
$email = $_POST['email'];
$password= password_hash($_POST['password'], PASSWORD_BCRYPT, $options);
$username= $_POST['username'];
$result = mysqli_query($mysqli, "SELECT username FROM users WHERE username = '$username'");
$row_count = $result->num_rows;
if($row_count == 1){
echo'User exists';
}else{
$query = "INSERT INTO users (username, email, password) VALUES(?, ?, ?)";
$statement = $mysqli->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('sss', $username, $email, $password);
if($statement->execute()){
print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
}
You have mixed the Procedural style & Object oriented style for executing the query.
When using,
1) Procedural Style
$result = mysqli_query($mysqli, "Your Query");
use this, $row_count = mysqli_num_rows($result);
2)Object oriented style
$result = $mysqli->query("Your Query");
Use this, $row_count = $result->num_rows;
So, According to your code, You are using Object Oriented Style. So, you need to change
$result = mysqli_query($mysqli,"SELECT username FROM users WHERE username = '$username'");
to
$result = $mysqli->query("SELECT username FROM users WHERE username = '$username'");
Edited Code.
$email = $_POST['email'];
$password= password_hash($_POST['password'], PASSWORD_BCRYPT, $options);
$username= $_POST['username'];
$result = $mysqli->query("SELECT username FROM users WHERE username = '$username'");
$row_count = $result->num_rows;
if($row_count == 1)
{
echo 'User exists';
}
else
{
$query = "INSERT INTO users (username, email, password) VALUES(?, ?, ?)";
$statement = $mysqli->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('sss', $username, $email, $password);
if($statement->execute())
{
print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />';
}
else
{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
}
For more info, check this mysqli_num_rows vs ->num_rows
$db = ("SELECT username FROM userlist WHERE username='$username'");
$query = $conn->query($db);
if(mysqli_fetch_array($query) > 0 ) { //check if there is already an entry for that username
echo "Username already exists!";
}

PHP Prepared Statements - MySQL Check if user exists

I don't know why my code doesn't seem to be working. I want to check if an email exists in the database, and if it doesn't exist proceed with registration. Here's the code:
if (empty($errors)) { //Using Prepared Statements
// Connect to the database:
$dbc = mysqli_connect ('localhost','root', 'pass', 'book_store');
$q = "SELECT user_id FROM users WHERE email=?";
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt, 'i', $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$num_rows = mysqli_num_rows($result);
if ($num_rows == 0) { //Check if email exists
$q = 'INSERT INTO users(first_name, last_name, state, email) VALUES (?, ?, ?, ?)';
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt,'ssss', $fn, $ln,$state, $email);
mysqli_stmt_execute($stmt);
// Closee statement:
mysqli_stmt_close($stmt);
// Close the connection:
mysqli_close($dbc);
} else {
echo '<h1>email exists</h1>';
}
}
else {
echo '<p>The Errors Occurred:<br />';
foreach ($errors as $msg) {
echo " - $msg<br />\n";
}
echo '</p><p>Please Try Again.</p>';
}
}
You have given i, which represents variable of type int. Try replacing that with s as given below.
$q = "SELECT user_id FROM users WHERE email=?";
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt, 's', $email);

Categories