How to get response from MySQL database using PHP - 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'];

Related

SQL request fails to retrieve data

I'm trying to retrieve the email field from my database using the id associated with it:
$query2 = mysql_query("SELECT email FROM `users` WHERE `id` = '".$userID."' ") or die(mysql_error());
This query is always returning NULL and I can't work out why.
Have tested using a var_dump that $userID is indeed correct.
But when I use it with the hardcoded value instead of $userID it works fine:
$query2 = mysql_query("SELECT email FROM `users` WHERE `id` = '85' ") or die(mysql_error());
Why isn't the $userID variable being passed to my query? Is there a way to pass this correctly?
Edit:
Declaration of $userID as requested. var_dump of this variable works OK the line before the query2.
// Fetch ID for matching details
$query = mysql_query("SELECT id FROM `users` WHERE `email` = '".$emailInput."' && `username` = '".$usernameInput."' ") or die(mysql_error());
// Successful query - ID stored
if(mysql_num_rows($query) > 0){
$userID = mysql_fetch_array($query);}
var_dump($userID);
Both var_dumps output the following on the page:
array(2) { [0]=> string(2) "85" ["id"]=> string(2) "85" } NULL
Id say the the fact that $userID is an array is your problem... Do $userID['id'] instead in the query.
$query2 = mysql_query("SELECT email FROM `users` WHERE `id` = '" . $userID['id'] . "' ") or die(mysql_error());
Its probably a concatenation problem , if the $userid is string its should be fine , but if its an integer or double..etc it will be dealt with as a string
if its an integer try :
$query2 = mysql_query("SELECT email FROM `users` WHERE `id` = ".$userID) or die(mysql_error());
or
$query2 = mysql_query("SELECT email FROM `users` WHERE `id` = ".$userID['0']) or die(mysql_error());
so, the problem is that your $userID is not 85 or a simple number but it's an array and you are still trying to concatenate it in the query.
The problem is somewhere else in your code, probably where you set $userID
Here goes the solution:
$sql = mysql_query("SELECT email FROM `users` WHERE `id` = " . $userID['id']) or die(mysql_error());
try removing either double quotes or single quotes. because id is usually of data type int you are using twice which makes it a string value..
also PHP is quite smart in recognizing variables and data types so u can use "$userID" or "{$userID}" without concatination..
Try this ....
$query2 = mysql_query("SELECT email FROM `users` WHERE `id` = $userID ") or die(mysql_error());

Doesn't work "SELECT COUNT(*) FROM..." in PHP script

My function should return number of rows with email like '$email'. But whey return 0 all the time, although in database i have rows with email like I insert in variable '$email'. What could be the reason?
function checkMail($email){
$email = mysql_real_escape_string($email);
$sql = "SELECT COUNT(*) FROM users WHERE email='$email'";
return mysql_query($sql);
}
You aren't returning a result, you're returning a query resource:
function checkMail($email){
$email = mysql_real_escape_string($email);
$sql = "SELECT COUNT(*) as emailCount FROM users WHERE email='$email'";
$query = mysql_query($sql) or die(mysql_error()); // show error if one happens
return mysql_fetch_assoc($query);
}
This will return an associative array containing your results (if it succeeds), and you should be able to access your count by:
$res = checkMail('your#email.com');
$count = $res['emailCount'];
Side note:
mysql functions are deprecated, you should use mysqli or PDO syntax:
https://stackoverflow.com/a/13944958/2812842
function checkMail($email){
$email = mysql_real_escape_string($email);
$sql = "SELECT COUNT(*) FROM users WHERE email='$email'";
$resource=mysql_query($sql);
$row=mysql_fetch_array($resource);
return $row[0];
}
To fetch the count use:
mysql_query($sql)
$row = mysql_fetch_assoc($result);
return($row[0]);
The funny thing is that mysql_query return 0, which indicates query fail. Check the corresponding error message with:
echo mysql_error();

php hash function checking database

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'];

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;
?>

How can I optimize or combine these MySQL queries?

I want to check for the username in the users table. If it's found, then I want to get the id. Otherwise, I want to insert the username as a new record, then get the id.
Here's my code:
<?PHP
$sql = "SELECT id FROM users where username = '$username'";
$query = mysql_query($sql) or die(mysql_error());
$result = mysql_num_rows($query);
if($result){
$row = mysql_fetch_array($query);
$userid = $row["id"];
}else{
$sql = "insert into users set username = '$username'";
$query = mysql_query($sql) or die(mysql_error());
$userid = mysql_insert_id();
}
?>
How can I optimize or combine these MySQL queries?
Can I select and insert in the same query?
and would it be better and faster?
If you want this to be fast make sure you index username.
It's better to INSERT first, with the assumption that the username does not exist. If any error is caused by a duplicate conflict, SELECT the existing row.
<?php
$sql = "INSERT INTO users SET username = '"
. mysql_real_escape_string($username) . "'";
$query = mysql_query($sql);
if ($query === true) {
$userid = mysql_insert_id();
} else {
if (mysql_errno() != 1022) { // this is the duplicate key error code
die(mysql_error());
}
$sql = "SELECT id FROM users where username = '"
. mysql_real_escape_string($username) . "'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($query);
if ($row !== false) {
$userid = $row["id"];
}
}
?>
The reason this is better is that if you select then insert, someone else might insert the username in the moment between your two SQL statements.
Of course you should have a UNIQUE constraint on users.username.
Re your comment: yes, it should be faster that your script. When there is no duplicate username (which is probably more common), you don't have to run the SELECT.
The best way to optimize an SQL query is not to run it at all.

Categories