im still developing android my android project i really need help, my problem is i couldn't get the user id of the user that login in my system so when they put a record a user id will attached to it data .. i want to do this to output their own data in my system. hope someone could help. its only php code thank you someone who would help.
<?php
// Connection Details altered to hide actual values.
$con = mysqli_connect("localhost", "db_user", "db_password", "db_name");
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM tbl_userinfo WHERE username = '$username' AND password='$password' LIMIT 1";
$res = mysqli_query($con,$sql);
$response = array();
$response["success"] = false;
$row = mysqli_fetch_array($res);
if(mysqli_num_rows($res)> 0){
$response["success"] = true;
session_start();
$_SESSION['user_id'] =$userID;
}
echo json_encode($response);
?>
thats for log in, here's for saving data..
<?php
session_start();
$userID ="";
// Connection Details altered to hide actual values.
$con = mysqli_connect("localhost", "db_user", "db_password", "db_name");
if(!isset($_SESSION['user_id'])){
$userID = $_SESSION['user_id'];
$checkdate = $_POST["checkdate"];
$checkno = $_POST["checkno"];
$datepaid = $_POST["datepaid"];
$clientname = $_POST["clientname"];
$bank = $_POST["bank"];
$amount = $_POST["amount"];
$status = "UNFINISHED";
$statement = mysqli_prepare($con, "INSERT INTO tbl_checkinfo (user_id,checkno, checkdate, datepaid, clientname, bank, amount, status) VALUES (?,?, ?, ?, ?,?,?,?)");
mysqli_stmt_bind_param($statement, "iissssis", $userID, $checkno, $checkdate, $datepaid, $clientname, $bank, $amount, $status);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = false;
if($statement){
$response["success"] = true;
}
echo json_encode($response);
}
?>
and for displaying user data.
<?php
// Connection Details altered to hide actual values.
$con = mysqli_connect("localhost", "db_user", "db_password", "db_name");
$checkdate = $_POST["checkdate"];
$checkno = $_POST["checkno"];
$datepaid = $_POST["datepaid"];
$clientname = $_POST["clientname"];
$bank = $_POST["bank"];
$amount = $_POST["amount"];
$status = "UNFINISHED";
$sql = "Select * from tbl_checkinfo";
$result = mysqli_query($con, $sql);
// $statement = mysqli_prepare($con, "Select * from tbl_checkinfo");
// mysqli_stmt_execute($statement);
// mysqli_stmt_store_result($statement);
// mysqli_stmt_bind_result($statement, $user_id, $checkdate, $checkno, $datepaid, $clientname, $bank, $amount, $status);
$response = array();
$info=array();
$flag = array();
$response["success"] = false;
if( mysqli_num_rows( $result ) > 0 ) {
while($row = mysqli_fetch_array($result))
{
$flag[checkdate]=$row[checkdate];
$flag[checkno]=$row[checkno];
$flag[datepaid]=$row[datepaid];
$flag[clientname]=$row[clientname];
$flag[bank]=$row[bank];
$flag[amount]=$row[amount];
$flag[status]=$row[status];
array_push($info, $flag);
}
$response["success"] = true;
$response["message"] = $info;
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "No entries yet";
echo json_encode($response);
}
?>
Firstly, when posting questions on public forums, please remove your host, DB name, password, etc from the code. :)
Secondly, try to print_r($row) and see on which index is the user id available, then in your code, add this line:
if(mysqli_num_rows($res)> 0){
$response["success"] = true;
$response["user_id"] = $row[USER_ID_INDEX];
session_start();
$_SESSION['user_id'] =$row[USER_ID_INDEX];
}
Where you defined $userID variable, You have to assign proper value to session variable,
if(mysqli_num_rows($res)> 0){
$response["success"] = true;
session_start();
$_SESSION['user_id'] =$row[USER_ID_INDEX];
}
$row['user_id_in_table'] should give you the id.
Related
I have the following code to connect between mysql database and android.
$conn = mysqli_connect($servername, $username, $password, $database);
//if there is some error connecting to the database
//with die we will stop the further execution by displaying a message causing the error
if ($conn) {
$response["Connection"] = 1;
}
else {
$response["Connection"] = 0;
}
$userID= $_POST['user_id'];
function recordExists() {
$query = "SELECT * FROM user_table";
$result = mysqli_query($conn, $query);
$response["found"] = "i am here";
while($row=mysqli_fetch_array($result)){
$response["found"] = $row['user_id'];
if($row['user_id']==$userID){
return true;
}
}
return false;
// $result_num_rows = mysqli_num_rows($result);
//
// if($result_num_rows>0) {
// return true; // The record(s) do exist
// }
// return false; // No record found
}
$exists=recordExists();
if ($exists) {
$query = "SELECT * FROM user_table WHERE $userID";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array ($result);
$Nickname = array();
if ($row['nickname'] == NULL){
array_push($response["nickname"], "False");
}else{
array_push($response["nickname"], $row["nickname"]);
}
$response["Sync"] = "Already Added";
echo (json_encode($response));
} else {
$UserToBeAdded= $_POST['user_id'];
$NameToBeAdded= $_POST['name'];
$EmailToBeAdded= $_POST['email'];
$UserToBeAdded2 = mysqli_real_escape_string($conn, $UserToBeAdded);
$NameToBeAdded2 = mysqli_real_escape_string($conn, $NameToBeAdded);
$EmailToBeAdded2 = mysqli_real_escape_string($conn, $EmailToBeAdded);
$sql_query = "insert into user_table (user_id, name, email) values ('$UserToBeAdded2', '$NameToBeAdded2', '$EmailToBeAdded2');";
mysqli_query($conn, $sql_query);
$response["ID"] = $UserToBeAdded2;
$response["Name"] = $NameToBeAdded2;
$response["Email"] = $EmailToBeAdded2;
$response["Sync"] = "Just Added";
$response["nickname"] = "False";
echo (json_encode($response));
}
mysqli_close($conn);
from the above code, i can receive responses from the php side. however the following response is not received.
$response["found"] = "i am here";
if u see from my code above, basically the function recordExists() will definitely be called. however the response " i am here" is not encoded in JSON when i emulate the android app. anything wrong?
try to declare the response variable above all functions. so add $response=array();on top of the file.
here you can read up about the scope of php variables:
https://secure.php.net/manual/en/language.variables.scope.php
You have a variable scope issue with the connection variable. Pass the connection variable as a parameter.
recordExists($conn);
Also use prepared statements to prevent sql injection attacks.
I am working on an Android App. I need to update a register, I didn't have issues with entries. But when I try to update the table, Doesn't work
this my PHP
<?php
require_once 'include/userupdate.php';
$username = "";
$name = "";
$movil="";
$email = "";
$password = "";
$fnac = "";
$calle_numero_piso ="";
$nom_urba = "";
$cod_postal ="";
$localidad="";
$observaciones="";
/////////////////
if(isset($_POST['username'])){
$username = $_POST['username'];
}
if(isset($_POST['name'])){
$name = $_POST['name'];
}
if(isset($_POST['movil'])){
$movil = $_POST['movil'];
}
if(isset($_POST['email'])){
$email = $_POST['email'];
}
if(isset($_POST['password'])){
$password = $_POST['password'];
}
if(isset($_POST['fnac'])){
$fnac = $_POST['fnac'];
}
if(isset($_POST['calle_numero_piso'])){
$calle_numero_piso = $_POST['calle_numero_piso'];
}
if(isset($_POST['nom_urba'])){
$nom_urba = $_POST['nom_urba'];
}
if(isset($_POST['cod_postal'])){
$cod_postal = $_POST['cod_postal'];
}
if(isset($_POST['localidad'])){
$localidad = $_POST['localidad'];
}
if(isset($_POST['observaciones'])){
$observaciones = $_POST['observaciones'];
}
// Instance of a User class
$userObject = new User();
// update user
$json_registration = $userObject->updateRegisterUser($username, $name, $movil, $email, $password, $fnac, $calle_numero_piso, $nom_urba, $cod_postal, $localidad, observaciones );
echo json_encode($json_registration);
}
?>
And this my update.php
<?php
include_once 'db.php';
class User{
private $db;
private $db_table = "users";
public function __construct(){
$this->db = new DbConnect();
}
mysqli_close($this->db->getDb());
return false;
}
public function updateRegisterUser($username, $name, $movil, $email, $password, $fnac, $calle_numero_piso, $nom_urba, $cod_postal, $localidad, $observaciones ){
$query = "UPDATE users SET name = '$name', movil = '$movil', email = '$email', password = '$password', fnac = '$fnac', calle_numero_piso = '$calle_numero_piso', nom_urba ='$nom_urba', cod_postal = '$cod_postal', localidad = '$localidad', observaciones = '$observaciones' WHERE username = $username;";
$updated = mysqli_query($this->db->getDb(), $query);
if($updated == 1){
$json['success'] = 1;
}else{
$json['success'] = 0;
}
mysqli_close($this->db->getDb());
return $json;
}
public function loginUsers($username, $password){
$json = array();
$canUserLogin = $this->isLoginExist($username, $password);
if($canUserLogin){
$json['success'] = 1;
}else{
$json['success'] = 0;
}
return $json;
}
}
?>
I believe I there is something wrong with both php, but I am not sure where.
try this , as obvious your username is a string so it should be kept inside single quotes
$query = "UPDATE users SET name = '$name', movil = '$movil', email = '$email', password = '$password', fnac = '$fnac', calle_numero_piso = '$calle_numero_piso', nom_urba ='$nom_urba', cod_postal = '$cod_postal', localidad = '$localidad', observaciones = '$observaciones' WHERE username = '$username'";
One advise for best practice is, always make some primary key recommended as int autoincrement which will help to enforce uniqueness because in this case you can have two users with same name which will be a problem when your database grows.
here is my code below that i use to register a user
<?php
header("Content-Type: application/json");
require_once("config.php");
if(isset($_POST["email"]) && isset($_POST["username"]) && isset($_POST["password"])){
$email = $_POST["email"];
$username = $_POST["username"];
$password = $_POST["password"];
}
$con = mysqli_connect(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME);
if($con){
echo "connection good";
}
$response = array();
$statement = mysqli_prepare($con, "SELECT * FROM accounts WHERE email = ? OR username = ?");
mysqli_stmt_bind_param($statement, "ss", $email, $username);
$result = mysqli_stmt_execute($statement);
$row = mysqli_num_rows($result);
if($row > 0){
$response["success"] = false;
$response["message"] = "Email or Username already exists.";
}else{
mysqli_stmt_close($statement);
$statement2 = mysqli_prepare($con, "INSERT INTO accounts (email, username, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement2, "sss", $email, $username, $password);
$result2 = mysqli_stmt_execute($statement2);
$row2 = mysqli_affected_rows($statement2);
if($row2 > 0){
$response["success"] = true;
$response["message"] = "Account created successfuly.";
}else{
$response["success"] = false;
$response["message"] = "Creation error.";
}
}
$output = json_encode($response);
echo $output;
mysqli_close($con);
?>
at the end of the file when i check the localhost it echos "good connection br" which i cant use it with json .. how to avoid it so i caan use the response in jsonobject later
I have a registration form that the user enters data in. Then after it is posted to the same page and checked for null fields, the variables are put in the $_SESSION array and the user is directed to another form to enter another set of data in a table. After posting those variables, the variables from the previous page are extracted from $_SESSION and the new values are checked for null entries. After they are checked in a for loop, php script mysteriously stops (die("<h1> GOT HERE! </h1>") no longer appears on the screen) and the page keeps loading. After waiting for a while the page reloads itself.
I've been using die() for a while now to find the error, but it just doesn't echo between the for-loop and the if statement, and there is no apparent reason why it shouldn't. Here have a look:
<?php
session_start();
function sanitize($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if($_SESSION["registering"] != 1){
die("This page is to be used only when registering. Go to home page and select the seminar you want and click Register");
}else if($_SESSION["registered"] == 1){
die("You have already registered. Thank you. You can no longer access this page. To view your registration report, click here. ");
}else{
$id = sanitize($_SESSION["id"]);
$attendees = sanitize($_SESSION["attendees"]);
$ref_code = sanitize($_SESSION["Ref_Code"]);
$email = sanitize($_SESSION["email"]);
$prefix = sanitize($_SESSION["prefix"]);
$first_name = sanitize($_SESSION["first_name"]);
$last_name = sanitize($_SESSION["last_name"]);
$company = sanitize($_SESSION["company"]);
$address1 = sanitize($_SESSION["address1"]);
$address2 = sanitize($_SESSION["address2"]);
$user_city = sanitize($_SESSION["city"]);
$phone = sanitize($_SESSION["phone"]);
$responsibility = sanitize($_SESSION["responsibility"]);
$who_referred = sanitize($_SESSION["who-referred"]);
$role = sanitize($_SESSION["role"]);
$server = "MYREAL_DATABASE_SERVER";
$username = "CORRECT_USERNAME";
$password = "CORRECT_PASSWORD";
$dbname = "DB_NAME";
$conn = new mysqli($server, $username, $password, $dbname);
$query = "
SELECT *
FROM Seminar_Detail
WHERE Detail_id = '". $id ."'
";
$result = $conn->query($query);
if($result->num_rows == 0 ){
header("Location: ManagementSeminars.php");
}
$seminar = $result->fetch_assoc();
$name = $seminar["Seminar_Name"];
$city = $seminar["City"];
$from = $seminar["From"];
$to = $seminar["To"];
$fee = '';
$query = "SELECT Value FROM Fee WHERE Seminar_Name = '". $name ."' AND Currency = 'GBP'";
$result = $conn->query($query);
if($result->num_rows > 0){
$row = $result->fetch_assoc();
$fee = $row["Value"];
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$terminate = 0;
for($i = 1; i < ($attendees + 1); $i++){
if(isset($_POST["prefix-".$i]) && isset($_POST["first_name-".$i]) && isset($_POST["last_name-".$i]) && isset($_POST["position-".$i])){
$terminate = 0;
}else{
$terminate = 1;
}
}
die("<h1>".$terminate."</h1>");
if($terminate != 1){
$server = "SERVER";
$username = "USERNAME";
$password = "PASSWORD";
$dbname = "DBNAME";
$conn = new mysqli($server, $username, $password, $dbname);
$query = "
INSERT INTO Registry (Seminar_Name, Number_Attendees, Email, Prefix, First_Name, Last_Name, Company, `Address 1`, `Address 2`, City, Phone, Responsibility, Role, Who_Referred, Ref_Code)
VALUES ('". $name ."', '". $attendees ."', '".$email."', '".$prefix."', '".$first_name."', '".$last_name."', '".$company."', '".$address1."', '".$address2."', '".$user_city."', '".$phone."', '".$responsibility."', '".$role."', '".$who_referred."', '".$ref_code."')
";
$conn->query($query);
//ignore this part please
/*$query = "SELECT Registry_ID FROM Registry WHERE Ref_Code = '". $_SESSION["Ref_Code"] ."'";
$result = $conn->query($query);
$row = $result->fetch_assoc();
$registry_id = $row["Registry_ID"];
$attendee_first_name = "";
$attendee_last_name = "";
$attendee_position = "";
$stmt = $conn->prepare("
INSERT INTO Attendee (First_Name, Last_Name, Position, Registry_ID)
Values (?, ?, ?, ?)
");
$stmt->bindParam("ssss", $attendee_first_name, $attendee_last_name, $attendee_position, $registry_id);
for($i = 1; $i < $_SESSION["attendees"] + 1; $i++){
$attendee_first_name = sanitize($_POST["first_name-".$i]);
$attendee_last_name = sanitize($_POST["last_name-".$i]);
$attendee_position = sanitize($_POST["position-".$i]);
$stmt->execute();
}*/
}else{
$errorMessage = "<div class='alert alert-danger alert-dismissable'>
<strong>Oops!</strong> You have not entered all values.
</div>";
}
}
}
?>
I am positive that it is not a syntax error. Any help is appreciated!
The problem might be in this line
for($i = 1; i < ($attendees + 1); $i++){
You missed $ sign in i. It should be:
for($i = 1; $i < ($attendees + 1); $i++){
Having used error reporting, would have signaled an undefined constant i notice.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
I am trying to secure my login form using mysqli prepared statement.
I am using the following code and I'm keep getting the wrong information entered error!
here is my code:
if (isset($_POST["email"]) && isset($_POST["password"])) {
$manager = $_POST["email"];
$password = sha1(sha1($_POST['password']).$_POST['password']);
$stores = $_POST["stores"];
// Connect to the MySQL database
include "config/connect.php";
$stmt = mysqli_prepare(
$db_conx,
"SELECT email, password, storeShop
FROM storename
WHERE email = ?
AND password = ?
AND storeShop = ?"
);
$manager = $_POST["email"];
$password = sha1(sha1($_POST['password']).$_POST['password']);
$stores = $_POST["stores"];
//after validation, of course
mysqli_stmt_bind_param($stmt, "sss", $manager, $password, $stores);
mysqli_stmt_execute($stmt);
if (mysqli_affected_rows($db_conx))
{
mysqli_stmt_close($stmt);//<-- CLEAN UP AFTER YOURSELF!
//update was successful
$id = mysqli_insert_id($db_conx);
}
$existCount = mysqli_num_rows($query); // count the row nums
if ($existCount == 1) { // evaluate the count
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$storeShop = $row["storeShop"];
}
$_SESSION["storeShop"] = $storeShop;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
$_SESSION['storeShop'] = $storeShop;
header("location: dashboard");
exit();
} else {
echo "wrong information entered";
exit();
}
}
but when I use this code, it works fine:
$sql = "SELECT * FROM storename WHERE email='$manager' AND password='$password' AND storeShop='$stores'";
$query = mysqli_query($db_conx, $sql);
could someone please tell me what I am doing wrong?
Thanks in advance.
EDIT, This still doesn't work.
if (isset($_POST["email"]) && isset($_POST["password"])) {
$manager = $_POST["email"];
$password = sha1(sha1($_POST['password']).$_POST['password']);
$stores = $_POST["stores"];
// Connect to the MySQL database
include "config/connect.php";
$stmt = mysqli_prepare(
$db_conx,
"SELECT email, password, storeShop
FROM members
WHERE email = ?
AND password = ?
AND storeShop = ?"
);
$manager = $_POST["email"];
$password = sha1(sha1($_POST['password']).$_POST['password']);
$stores = $_POST["stores"];
//after validation, of course
mysqli_stmt_bind_param($stmt, "sss", $manager, $password, $stores);
mysqli_stmt_execute($stmt);
if (mysqli_affected_rows($db_conx))
{
$existCount = mysqli_stmt_affected_rows($stmt);
mysqli_stmt_execute($stmt); // count the row nums
if ($existCount == 1) { // evaluate the count
while($row = mysqli_fetch_array($stmt, MYSQLI_ASSOC)){
$storeShop = $row["storeShop"];
}
$_SESSION["storeShop"] = $storeShop;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
$_SESSION['storeShop'] = $storeShop;
header("location: dashboard");
mysqli_stmt_close($stmt);
exit();
} else {
header("Location: data");
exit();
}
//<-- CLEAN UP AFTER YOURSELF!
//update was successful
}
}
SECOND EDIT:
if (isset($_POST["email"]) && isset($_POST["password"])) {
$manager = $_POST["email"];
$password = sha1(sha1($_POST['password']).$_POST['password']);
$stores = $_POST["stores"];
// Connect to the MySQL database
include "config/connect.php";
$stmt = mysqli_prepare(
$db_conx,
"SELECT email, password, storeShop
FROM members
WHERE email = ?
AND password = ?
AND storeShop = ?"
);
$manager = $_POST["email"];
$password = sha1(sha1($_POST['password']).$_POST['password']);
$stores = $_POST["stores"];
//after validation, of course
mysqli_stmt_bind_param($stmt, "sss", $manager, $password, $stores);
mysqli_stmt_execute($stmt);
if (mysqli_affected_rows($db_conx))
{
$existCount = mysqli_stmt_affected_rows($stmt); // count the row nums
if ($existCount == 1) { // evaluate the count
if (mysqli_stmt_affected_rows($stmt))
{
while($row = mysqli_fetch_array($stmt, MYSQLI_ASSOC)){
$storeShop = $row["storeShop"];
}
$_SESSION["storeShop"] = $storeShop;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
$_SESSION['storeShop'] = $storeShop;
header("location: dashboard");
mysqli_stmt_close($stmt);
exit();
} else {
header("Location: data");
exit();
}
}
//<-- CLEAN UP AFTER YOURSELF!
//update was successful
}
}
This works for me:
$stmt = $db_conx->prepare("SELECT email, password, storeShop
FROM storename
WHERE email = ?
AND password = ?
AND storeShop = ?");
$stmt->bind_param('sss', $manager, $password, $stores);
$stmt->execute();
$stmt->bind_result($manager, $password, $stores);
$stmt->store_result();
if($stmt->num_rows == 1) //To check if the row exists
{
while($stmt->fetch()) //fetching the contents of the row
{
$_SESSION["storeShop"] = $storeShop;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
$_SESSION['storeShop'] = $storeShop;
header("location: dashboard");
exit();
}
}
else {
header("Location: data");
exit();
}
$stmt->close();
You need to update this;
$existCount = mysqli_num_rows($query);
to
$existCount = mysqli_stmt_affected_rows($stmt);
Refer here for further details
Edit:
And in your code it should be ;
if (mysqli_stmt_affected_rows($stmt))
{
while($row = mysqli_fetch_array($stmt, MYSQLI_ASSOC)){
$storeShop = $row["storeShop"];
}
$_SESSION["storeShop"] = $storeShop;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
$_SESSION['storeShop'] = $storeShop;
header("location: dashboard");
mysqli_stmt_close($stmt);
exit();
} else {
header("Location: data");
exit();
}