I am developing an adroid app and I faced some trouble about php web service.
I want to get user type information form database and according to the answer I will do some process in the background.
So in my authentication code there is a area like this to get usertype;
function getUserType(){
$sql = "SELECT `usertype` FROM `login_test` WHERE username = '". $this->username2."'
AND password = '".$this->password2."'";
$result = mysqli_query($this->DB_CONNECTION, $sql);
if(mysqli_num_rows($result)>0){
return (?);
}
}
and my in my login code the message will be send here;
if ($userStatus) {
// user existed
// So log him to main page
$json['success'] = 1;
$json['message'] = 'Access Granted';
$json['usertype'] = 'Client';
echo json_encode($json);
Here I dont know how to access a certain field called 'usertype' in my table (I am really new in php) and how to return the value that I got.
Any help will be apreciated
P.S = $userStatus returns ture.
You could try doing this:
$sql = "SELECT * FROM `login_test` WHERE username = '$this->username2' AND password = '$this->password2'";
$result = mysqli_query($this->DB_CONNECTION, $sql);
return $result->fetch_object()->userType;
While please do keep in mind to use prepared statements.
Related
Firstly, please forgive me if i don't give enough info in my question, i'm new to the developer scene after just landing myself an amazing opportunity as a junior software developer role a few weeks ago.
I have a project i'm working on which is a basic CRUD management system.
I have a login process and user accounts all setup but i would like certain things to require "Admin" privileges like deleting items from my inventory.
So currently everything works as is (just no admin checking)
i have made this function in my config.php (which is included on every page through the header)
function checkAdmin($conn)
{
$id = $_SESSION['member_id'];
$sql = "SELECT admin FROM members WHERE id = $id";
$query = mysqli_query($conn, $sql);
$rs = mysqli_fetch_array($query);
$admin = $rs['admin'];
if($admin == 1){
return true;
}else{
return false;
}
}
So my question is, how do i then pass that value "true/false" into my query.
Im using jQuery/Ajax to do my queries but i understand this would be handed on my "ajax.php" page where all my queries are.
my current code is:
if(isset($_GET['deleteID']))
{
if('checkAdmin' == true){
$id = $_GET['deleteID'];
$sql = "DELETE FROM members WHERE id=$id";
mysqli_query($conn, $sql);
recordLog($conn, "Members", "Removed user #$id");
$data = [
'success' => true
];
}else{
$data = [
'error' => 'Admin Privileges Required'
];
}
echo json_encode($data);
}
the actual code in itself works, without the If(checkAdmin == statement but i dont think i'm on the right lines with it.
Thanks in advance for any help :) please let me know if any more info is needed
Call the function in the if statement:
if(checkAdmin($conn) == true){
Alternately you could do:
$checkAdmin = checkAdmin($conn);
if($checkAdmin == true){
Be advised that you are at serious risk of SQL Injection. Implement this now: How can I prevent SQL injection in PHP? This is bad, bad, bad:
$id = $_GET['deleteID'];
$sql = "DELETE FROM members WHERE id=$id";
I have a customer table. Each customer has a specific ID.
In my project(ecommerce website) I want to store the ID of the user in a $_SESSION['user_id'] when he/she successfully login.
How do I do that? What do I need to add?
Here's my code:
<?php
// establishing the MySQLi connection
$con = mysqli_connect("localhost","root","","ecommerce");
// checking the user
if(isset($_POST['login'])){
$email = mysqli_real_escape_string($con,$_POST['c_email']);
$pass = mysqli_real_escape_string($con,$_POST['pass']);
$sel_user = "select * from customer where customer_email ='$email' AND customer_pass='$pass'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0){
$_SESSION['customer_email']=$email;
echo "<script>window.open('index.php','_self')</script>";
} else {
echo "<script>alert('Email or password is not correct, try again!')</script>";
}
}
?>
First, as #chris85 mentioned, call session_start() at the top of your script.
Then, you're almost there. First, you need to get the result object from the results.
$rows = array();
while ($row = mysql_fetch_assoc($run_user)) {
$rows[] = $row; // Same as array_push($rows, $row) but has better performance when pushing a single item.
}
Then, assuming we know there is only one row returned:
$customerData = $rows[0];
Cool. Now, set whatever SESSION variables you want:
$_SESSION["user_id"] = $customerData["user_id"];
...
Also, as has been noted in the comments, please please please do not ever store a user's password as plain text. You should hash and salt it. Here is a good starter post to read through: Best way to store password in database
I'm probably not using the best method to create a user system, but it doesn't need to be fancy. I also know that I'm not the most organized
The logins and everything are alright, but I'm having a problem updating the credentials.
For example, I'm allowing users to change their username. I have the "Change Username" (Not that name) form to submit to update-username.php.
I already have mysql_real_escape_string, in the function "cleanString" in another page. My textarea submitting already has the old text in it, so you can change and view it before hand.
$user_id = "";
if(isset($_POST['id']))
{
$user_id = $_POST['id'];
}
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if(!$results) { //Check to see if query failed
die(mysql_error());
}
$resultsfetch=mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = $_POST['usernameinput'];
if(isset($_POST['usernameinput'])) {
$usernamenew = cleanString($_POST['usernameinput']);
}
if($usernamenew !=$username){
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
mysql_query($submit);
if(!$submit) { //Check to see if query failed
die(mysql_error());
}
}
It's probably something stupid or simple that I missed, or something really huge. Mainly because I am absent minded.
$submit = sprintf("UPDATE users SET username = '%s' WHERE user_id = %d",mysql_real_escape_string($usernamenew),mysql_real_escape_string($user_id));
If the page is loaded, $user_id will be NULL so noting will be updated! Make sure that this page loads, by sending $_POST['id'] . if these things are correct, check this.
"Did the database user have any permission to update the table? "
I have re-arranged your code. added comments where i changed. Try this
if (isset($_POST['id'], $_POST['usernameinput'])) { // Check if both POST id and usernameinput is available
$user_id = (int)$_POST['id']; //assuming this is an integer
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if (!$results) {//Check to see if query failed
die(mysql_error());
}
if (mysql_num_rows($result) > 0) { //verify if there is really a user with such id
$resultsfetch = mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = cleanString($_POST['usernameinput']);
if ($usernamenew != $username) {
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
if (!mysql_query($submit)) {//Check to see if query failed
die(mysql_error());
}
}
}else{
die("no such user with userid=$user_id");
}
}
Warning: mysql_ function is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
So, I guess I figured it out. It's an issue with my code carrying over to the next page.
The code I had been shown only broke the page, whether it be missing an integer, or something else. I'm not 100% sure.
Thanks for all the help guys, but now I know the issue.
EDIT:
I had forgotten to echo the $user_id in my hidden field.
I'm try to get cookies on to a browser. It's giving me parameter 1 error and parameter 3. This code works elsewhere on my site but not here. Can someone help me?
if ((!isset($_POST["uname"])) || (!isset($_POST["password"])))
{
header ("Location: wddnt/clients/'. $tattoo_extern_acct . '/index.html");
exit;
}
$userpass = md5($_POST['password']);
#$db = mysqli_connect("$dbc_ser", "$dbc_usr", "$dbc_pwd", "$dbc_db");
$sql = "SELECT id, name, company, job_title, cell_num, office_num, office_email,
login_right, first_run, attempts, locked_out FROM login
WHERE email = '".$_POST["email"]."'
AND password = PASSWORD('$userpass')";
if (mysqli_connect_errno())
{
echo 'Cannot connect to database: ' . mysqli_connect_error();
}
else
{
$result = mysqli_query($db, $sql);
while ($info = mysqli_fetch_array($result))
{
$id = stripslashes($info['id_files']);
$u_acct = stripslashes($info['uname']);
$name = stripslashes($info['name']);
$job_title = stripslashes($info['job_title']);
$location = stripslashes($info['company']);
$cell_num = stripslashes($info['cell_num']);
$office_num = stripslashes($info['office_num']);
$office_email = stripslashes($info['office_email']);
$login_right = stripslashes($info['login_right']);
$first_run = stripslashes($info['first_run']);
$attempts = stripslashes($info['attempts']);
$locked_out = stripslashes($info['locked_out']);
$land_page = stripslashes($info['land_page']);
}
}
Try debugging some of the individual variables. What is in $sql, for example? Is it correct?
Is the "Cannot connect" clause executed, or does it get to the query and fail there? (I am not sure what "parameter 1 error and parameter 3" means).
Don't forget to escape the 'email' value by the way - this code has an SQL injection hole.
header ("Location: wddnt/clients/'. $tattoo_extern_acct . '/index.html");
This is not going to work the way you expect.
$sql = "SELECT id, name, company, job_title, cell_num, office_num, office_email,
login_right, first_run, attempts, locked_out FROM login
WHERE email = '".$_POST["email"]."'
You need to read up on SQL injection.
while ($info = mysqli_fetch_array($result))
You allow multiple accounts with the same email address / password?????
It's giving me parameter 1 error and parameter 3
Couldn't you post the actual error message you get?
$id = stripslashes($info['id_files']);
WTF? Smartquotes?
I'm not sure i understand your question but the last time i checked anyone who wants to use cookies uses the $_COOKIE global variable, either for setting them or accessing them. $_POST is made to get stuffs from forms, not cookies.
Please check the manual for more details about $_COOKIE
Regards
I want my php query to display the user name with a link to the user profile.
<?php
$get_items = "SELECT * FROM items WHERE category='test'";
$result = mysql_query($get_items);
while($item = mysql_fetch_array($result, MYSQL_ASSOC)){
$creator = $item['created_by'];
echo "<b>Seller: </b>"."<a href='userprof.php?id=$creator'>$creator</a>";
}
?>
Clicking on this link takes it to a user profile page that I created. But I want "userprof.php?id=$creator" to know which user to display the account information. Is this the best way to do this? How can I read the url and display the correct information?
<?php
$userId = $_GET['id'];
$sql = "SELECT * FROM user WHERE id = " . intval($userId);
$result = mysql_query($sql);
...
You are sending a GET variable.
$id = $_GET['id']; // Contains whatever was in $creator;
use $_GET for getting the variable from the URL.
like in your code you want to access the user profile then get the user id from url
like
http://localhost/test/user_profile.php?uid=2
here in the url uid is 2 thet is your userid.
you can get this id by using the code
$user_id = $_GET['uid'];
use this variable in your query.
OMG!! HORRIBLE PHP ABOUNDS! IT HURTS MY EYES!!
These people, none of them did both of the correct things:
ALWAYS FILTER USER INPUT!!
NEVER TRUST PHP ESCAPE FUNCTIONS, ESP NOT intval() and addslashes()!!
EVEN mysql_real_escape_string() HAS VULNERABILITIES AND SHOULD NEVER BE USED.
You should used prepared statements for everything in 2010.
Here it is the proper way:
<?php
if (!filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT))
{
trigger_error('Invalid User ID. It must be an integer (number).', PHP_USER_ERROR);
exit;
}
$userId = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$sql = "SELECT * FROM user WHERE id = ?";
$pdo = new PDO('mysql:host=localhost;db=mydb', $dbUsername, $dbPassWord);
$statement = $pdo->prepare($sql);
$statement->execute(array($userId));
$result = $statement->fetch(PDO::FETCH_ASSOC);
That is 100% secure. I hope people neither vote me down nor tone down my answer. Bad code is so systemic, we just have to shout from the rooftops until the new guys start learning it correctly, otherwise PHP as a professional language is seriously harmed.