php hash function checking database - php

When inserting a new user into a database i want to hash the password. this is what i have got.
static function getLastId(){
global $database;
$sql = 'SELECT ID from users ORDER BY id DESC LIMIT 1' ;
$result = $database->query($sql);
return $result;
}
static function create_user($username,$password ){
global $database;
$lastID = self::getLastId() + 1;
$ePassword = $database->escape_value($password);
$hash = hash('sha256', $lastID . $ePassword);
$sql = "INSERT INTO ". self::$table_name . " (username, password, first_name, last_name, power ) VALUES ";
$sql .= "('{$database->escape_value($username)}', '{$hash}', 'asd' , 'asd', 'user') ";
$query = $database->query($sql);
return ($query)? true : false;
}
when i do a print or var dump of $lastID I get 13. however looking a the database i only have 1 user me, with an ID of 1. I even truncated the table, but i am still getting 13. not sure why.
basically the idea is that i want to append $lastID to the password, so that it is much harder to reverse. I need to know what the next ID is going to be, for login purposes.

$result = $database->query($sql);
return $result;
You're returning the result resource instead of actual data (i assume so, unless your $database module automatically does this), you might want to:
$result = $database->query($sql);
$data = mysql_fetch_array($result);
return $data['ID'];

Related

Can't execute else in conditional logic

I have this code which is supposed to insert some data if certain conditions are met. The first 3 parts of the conditional logic work perfectly bu the else seems not to be executing if the data is a string.
In summary, if the $USSD_STRING is is an integer is(12345) the query executes perfectly. But if there is a letter at the beginning of the value i.e. (AA12345) the else seems not to be working.
I have tried this:
elseif (is_string("$USSD_STRING")) {
$sql = "INSERT INTO userlevel SET phone_number = '$MSISDN', ussd_string = '$USSD_STRING', user_level = '$level', session_id = '$SESSION_ID', mno_id = '$MNOID', partner_id = '$PartnerId'";
$result=mysql_query($sql);
}
but its not working either.
if ( $USSD_STRING <=0) {
}
elseif ( $USSD_STRING ==1) {
$sql = "INSERT INTO userlevel SET phone_number = '$MSISDN', ussd_string = '$USSD_STRING', user_level = '$level', session_id = '$SESSION_ID', mno_id = '$MNOID', partner_id = '$PartnerId'";
$result=mysql_query($sql);
}
elseif ( $USSD_STRING ==2) {
$sql = "INSERT INTO userlevel SET phone_number = '$MSISDN', ussd_string = '$USSD_STRING', user_level = '$level', session_id = '$SESSION_ID', mno_id = '$MNOID', partner_id = '$PartnerId'";
$result=mysql_query($sql);
}
else {
$sql = "INSERT INTO userlevel SET phone_number = '$MSISDN', ussd_string = '$USSD_STRING', user_level = '$level', session_id = '$SESSION_ID', mno_id = '$MNOID', partner_id = '$PartnerId'";
$result=mysql_query($sql);
}
Any workarounds?
I will bet that you are declaring your variable in quotes, something you did not post in your question.
However, I could be wrong. But nonetheless, you have a few options for you below.
The following (and as an example)
$USSD_STRING = "12345";
or
$USSD_STRING = $_POST['var'];
Even though that is technically an integer (being set in quotes), it will still be interpreted as a string using the is_string() function.
"Any workarounds?"
Yes, you have a few.
Using the following will qualify as not being a string using the is_string() function.
$USSD_STRING = 12345;
You would be best using ctype_digit() for this.
$USSD_STRING = "a12345"; // fail
The following will pass as an integer even though it is inside quotes
$USSD_STRING = "12345"; // pass as an integer
if (ctype_digit($USSD_STRING)) {
...
}
while the following will fail if a letter is introduced
$USSD_STRING = "a12345"; // fail. It contains a letter
if (ctype_digit($USSD_STRING)) {
...
}
Another option available for you to use, would be FILTER_VALIDATE_INT.
if(filter_var($USSD_STRING, FILTER_VALIDATE_INT))
Where it will fail with
$USSD_STRING = "a12345";
but pass as (and even inside quotes):
$USSD_STRING = "12345";
References:
http://php.net/manual/en/function.ctype-digit.php
http://php.net/manual/en/function.filter-var.php

How to get response from MySQL database using PHP

I'm working with a system that assigns files to users. Problem is, that the response, userid, is always 0.
$user = htmlentities($_SESSION['username']);
$sql = "INSERT INTO `files`(
`userid`,
`filename`,
`filesize`,
`filetype`,
`filepath`
)
VALUES
(\"". get_user_id($user). "\",\"".
$_FILES['userfile']['name']. "\",\"".
$_FILES['userfile']['size']. "\",\"".
$_FILES['userfile']['type']. "\",\"".
$fileadress.
"\")";
Function get_user_id
function get_user_id($user){
mysql_connect(HOST, USER, PASSWORD)
or die(mysql_error());
$sqlinit = "USE secure_login";
mysql_query($sqlinit);
$sql = "SELECT `id` FROM `members` WHERE `username` = '". $user."'";
$result = mysql_query($sql);
//mysql_fetch_array($result);
echo mysql_error();
$userid = $result;
return $userid;
}
No errors, no warnings, everything else is working fine, only userid is showing always 0, even when id in members is 1,2 etc. Am I missing something? In both tables, userid and id are int.
mysql_query() returns you a mysql object, you put this object in the result variable. So if you do $userid = $result; you just duplicate the array to a new variable.
You're not accessing correctly to the element, you should write instead : $userid = $result['id'];
Take the habit to employ var_dump($result); to see what's exactly in you're variable (here result)
EDIT:
$sql = "SELECT id FROM members WHERE username = '". $user."'";
$queryRes = mysql_query($sql);
$result = mysql_fetch_array($queryRes);
$userid = $result['id'];
I believe you have to use $userid=$result['id']
As per your table, the right index would be userid
i.e:
$userid = $result['id'];

How to insert where condition in mysql query

I will pass the query into this function query("SELECT * FROM table_name");
And the function is
public function query($sql) {
$resource = mysql_query($sql, $this->link_web);
if ($resource) {
if (is_resource($resource)) {
$i = 0;
$data = array();
while ($result = mysql_fetch_assoc($resource)) {
$data[$i] = $result;
$i++;
}
mysql_free_result($resource);
$query = new stdClass();
$query->row = isset($data[0]) ? $data[0] : array();
$query->rows = $data;
$query->num_rows = $i;
unset($data);
return $query;
} else {
return true;
}
} else {
trigger_error('Error: ' . mysql_error($this->link_web) . '<br />Error No: ' . mysql_errno($this->link_web) . '<br />' . $sql);
exit();
}
}
I want to add tenent_id = '1' in SELECT query also for INSERT query. Likewise I need to do it for UPDATE.
I want to bring the query like this
SELECT * FROM table_name WHERE tenent_id = 1 and user_id = 1
INSERT INTO table_name('tenant_id, user_id') VALUE('1','1')
UPDATE table_name SET user_id = 1 WHERE tenant_id = '1'
Can anyone give me the idea about how to insert tenant_id in select, insert and update
Thanks in advance
It's better practice to use the correct mysql functions rather than just a query function.
For example, if you want to cycle through many items in a database, you can use a while loop:
$query = mysql_query("SELECT * FROM table WHERE type='2'");
while($row = mysql_fetch_array($query)){
echo $line['id'];
}
This would echo all the IDs in the database that have the type 2.
The same principle is when you have an object, using mysql functions, you can specify how you want the data to return. Above I returned it in an array. Here I am going to return a single row as an object:
$query = mysql_query("SELECT * FROM table WHERE id='1'");
$object = mysql_fetch_object($query);
echo $object->id;
echo $object->type;
echo $object->*ANY COLUMN*;
This would return as:
1.
2.
Whatever the value for that column is.
To insert your data, you don't need to do "query()". You can simple use mysql_query($sql).
It will make life much easier further down the road.
Also, its best to run one query in a function, that way you can handle the data properly.
mysql_query("INSERT...");
mysql_query("UPDATE...");
mysql_query("SELECT...");
Hope this helps.
The simple answer is: just add the condition to your query. Call query("SELECT * FROM table_name WHERE tenant_id = 1 and user_id = 1").
If you're concerned about escaping the parameters you pass to the SQL query (which you should be!), you can either do it yourself manually, e.g.
$query = sprintf("SELECT * FROM table_name WHERE tenant_id = %d", intval($tenant_id));
query($query);
Or better use prepared statement offered by mysqli extension (mysql_query is deprecated anyway):
$stmt = $mysqli->prepare("SELECT * FROM table_name WHERE tenant_id = ?");
$stmt->bind_param("i", $tenant_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
// ...
}
If I still haven't answered your question, you can use a library to handle your queries, such as dibi:
$result = dibi::query('SELECT * FROM [table_name] WHERE [tenant_id] = %i', $id);
$rows = $result->fetchAll(); // all rows
The last option is what I would use, you don't need to write your own query-handling functions and get query parameter binding for free. In your case, you may utilize building the query gradually, so that the WHERE condition is not part of your basic query:
$query[] = 'SELECT * FROM table_name';
if ($tenant_id){
array_push($query, 'WHERE tenant_id=%d', $tenant_id);
}
$result = dibi::query($query);

PHP Variable in Select Statement

I've written this PHP-Script which is working, and now I want to change the row name into a variable to (not sure if row is correct), I mean the "name" from the select name...
I've tried nearly everything, but nothing gave me the right result.
I know that the normal thing how I can use variables in a statement like ("'. $var .'") won't work.
<?php
require_once 'config.php';
$id = $_GET["id"]; //ID OF THE CURRENT CONTACT
$user = $_GET["user"]; //ID OF THE CURRENT USERS
$query = mysql_query("SELECT name FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
$retval = mysql_fetch_object($query)->name;
$retval = trim($retval);
echo $retval;
?>
This is much easier isn't it?
$sql_insert =
"INSERT INTO customers (
`name`,
`address`,
`email`,
`phone`
)
VALUES (
'$name',
'$address',
'$email',
'$phone'
)";
Is it this you're looking for? Even your question in German isn't that clear to me :
$field = 'name';
$query = mysql_query("SELECT $field FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
$retval = mysql_fetch_object($query)->$field;
You can usi it something like this. Currently i assume you get only one row back and want to use only one field.
<?php
require_once 'config.php';
$id = $_GET["id"]; //ID DES DERZEITIGEN KONTAKTES
$user = $_GET["user"]; //ID DES DERZEITIGEN USERS
//Use variable inside closures `` and just in case escape it, depends how you get variable
$query = mysql_query("SELECT `".mysql_real_escape_string($variable)."` FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
if (!$query) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($query); //Retriev first row, with multiple rows use mysql_fetch_assoc
$retval = $row['0']; //Retriev first field
$retval = trim($retval);
echo $retval;
?>
Please post in English. Everyone else does.
Try using a different fetch method - fetch an associative array, then use the dynamic parameter to retrieve whatever column it is you need.
Have you considered using PDO?
I believe you are confusing matters (unintentionally) due to your use of the word 'row'. Judging by your example you mean field/column. It sounds like you wish to specify the fields to select using a variable which can be done by any of these methods...
$fields = "name, age";
$sql = "SELECT $fields FROM table";
$sql = "SELECT {$fields} FROM table";
$sql = "SELECT ".$fields." FROM table";
NB it is important that you have secure date in the $fields element, I would suggest using a whitelist of allowed values i.e.
// assuming $_POST['fields'] looks something like array('name','age','hack');
$allowed = array('name', 'age');
$fields = array();
foreach ($_POST['fields'] as $field) {
if (in_array($field, $allowed)) {
$fields[] = $field;
}
$fields = implode(', ', $fields);
Wouldn't this work?
$result = mysql_fetch_array($query);
echo trim($result['name']);
You should never put a variable into field list.
If want a variable field name, select *
and then use your variable to fetch particular field
<?php
require_once 'config.php';
$id = mysql_real_escape_string($_GET["id"]); //ID DES DERZEITIGEN KONTAKTES
$user = $_GET["user"]; //ID DES DERZEITIGEN USERS
$query = "SELECT * FROM contacts WHERE contact_id='$id' and user_id='1'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_array($result);
//and finally
$fieldname = "name";
$retval = $row[$fieldname];
echo $retval;
?>

Drupal: PHP field for allowed values

I'm working in Drupal 6 with CCK. Under each text field there is a PHP section where you can run some PHP code to get allowed values. I'm running into trouble using an "if" statement to change the allowed values based on user type
So to start, I do a query to determine current users user type. -1 is default user, which is employees and user type id "1", is for site users. What I want is to restrict the site user to only the allowed values they need to see, while allowing employees to edit that value when on the node edit screen with all choices.
The first part of the if statement works. However, the "else" part doesn't work. Is this field set up to deal with control structures?
global $user;
$sql1 = "SELECT user_type_id FROM user_types_user WHERE uid = ".$user->uid." ";
$res1 = db_query($sql1);
if($res1 == '1'){
$sql = "SELECT account FROM users WHERE uid = ".$user->uid." ";
$res = db_query($sql);
while($row = db_fetch_array($res)){
$rows[] = $row['account'];
}
$rows = drupal_map_assoc($rows);
return $rows;
}
else {
$sql2 = "SELECT title FROM node WHERE type = 'accounts' ";
$res2 = db_query($sql2);
while($row2 = db_fetch_array($res2)){
$rows2[] = $row2['title'];
}
$rows2 = drupal_map_assoc($rows2);
return $rows2;
}
The choices are type=accounts in nodes, however, when a user is created one of the choices is selected and stored in the user table, under a column I created named "account"
If by 'the "else part does not work' you mean that it is never executed, even if user_type_id does not equal 1, it might be the missing db_fetch_array() on $res1. You're comparing your result object directly to the string '1', not the field value.
Here is the working code for this. There may have been a quicker/shorter way to do this.
global $user;
$sql1 = "SELECT user_type_id FROM user_types_user WHERE uid = ".$user->uid." ";
$res1 = db_query($sql1);
while($type = db_fetch_array($res1)){
$types[] = $type['user_type_id'];
}
$resType = $types[0];
if($resType == "1"){
$sql = "SELECT account FROM users WHERE uid = ".$user->uid." ";
$res = db_query($sql);
while($row = db_fetch_array($res)){
$rows[] = $row['account'];
}
$rows = drupal_map_assoc($rows);
return $rows;
}
else {
$sql2 = "SELECT title FROM node WHERE type = 'accounts' ";
$res = db_query($sql2);
while($row2 = db_fetch_array($res)){
$rows2[] = $row2['title'];
}
return $rows2;
}

Categories