I can't get the logged in user in the code, can you please help me to figure it out:
the code which is not working:
$result = mysql_query("SELECT * FROM clients WHERE user = '$_SESSION['user']['username']'")
or die(mysql_error());
but it is working for showing it thought, in here:
echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
thanks in advance for any help.
There are two solutions to this. The first is to define a new variable to contain the $_SESSION['user']['username'] value and the second is to enclose $_SESSION['user']['username'] in curly braces (see: Strings - variable parsing for more information).
Solution 1
$username = $_SESSION['user']['username'];
mysql_query("SELECT * FROM clients WHERE user = '$username'")
or die(mysql_error());
Solution 2
mysql_query("SELECT * FROM clients WHERE user = '{$_SESSION['user']['username']}'")
or die(mysql_error());
In addition to this, if one is only accessing the top-level of the array (e.g. $_SESSION['username'] rather than $_SESSION['user']['username']) one can simply remove the quotes around the key name:
mysql_query("SELECT * FROM clients WHERE user = '$_SESSION[username]'")
or die(mysql_error());
However, it should be worth pointing out that mysql functions are deprecated and that your code is vulnerable to SQL injection. You should look into using PDO or mysqli prepared statements.
You can try this, please avoid using mysql functions anymore, and this not a hackproof code. Pleae make it
$user = htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
mysql_query("SELECT * FROM clients WHERE user = '".$user."'")
or die(mysql_error());
Related
i know maybe this post will be marked soon as duplicate, because there are a lot of questions answered but i dont know why it is not working for me (as always) here is this part of code:
$conn->set_charset("utf8");
$query = mysqli_query($conn, "SELECT * FROM User WHERE Username='".$username."'");
if(mysqli_num_rows($query) > 0){
echo "exists";
}else{
if (!mysqli_query($conn,$query))
{
echo "free";
}
}
}
Problem is : I'm always getting "Free"
thanks
-Nick
Try fetching the values and then using the php count() function on the query result. If count is greater than 0 echo taken else free
Why do you use a password in this query if you only want to check is a username is available? Did you also dumped the $numrows var to see which data it contains?
I would use something like
SELECT id FROM users WHERE username='username' LIMIT 1
You want to know if a username is available, so stop looking after you found 1 (LIMIT 1). If I ask you to find me 1 spoon,
As many others suggest, stop using the deprecated mysql_* functions. Try reading the tutorials on https://phpdelusions.net/pdo (much more can be found via Google)
When using PDO I think you can use the following code. Forgive me if it contains errors, it has been ages since I just PDO directly:
<?php
$checkUser = $pdoConnection->prepare("SELECT id FROM users WHERE username = ? LIMIT 1");
$checkUser->execute([$username]);
if ( $checkUser->rowCount() == 1 )
{
return 'Username exists';
}
# Username is available, so continue with the rest of your code
Small tip from me, based on experience, which has nothing to do with your question; never use capitals in your database. It could lead to unnecessary problems.
Your Username and Password are in quotes, so it is taking them literally.
Try this:
$query = mysql_query("SELECT * FROM User WHERE Username='" . $usernameG . "' and Password='" . $passwordG ."'");//quotes
I'm looking for a simple php script that will look through my database for a username and echo a column. The column I want to echo is a date.
I'm making a script that checks if the date assigned to the user is todays date.
$datenow = date("Y-m-d");
$user = $_SESSION['username'];
$connection = mysql_connect('localhost', 'username', 'password');
mysql_select_db('database name');
$result = mysql_query("SELECT accessfrom FROM users WHERE username = $user");
// Now I need a simple way to check if the results date = $datenow(from above)
mysql_close(); //Make sure to close out the database connection
Don't use MySQL. It is deprecated. So, use mysqli_.
Presumably, username is a string. So, you have a mismatch in your comparisons. The naive solution is to add single quotes:
$result = mysql_query("SELECT accessfrom FROM users WHERE username = '$user'");
The correct solution is to use mysqli_ and use parameters for passing in values. This not only solves your problem. It also prevents SQL injection attacks, and teaches you how to correctly write queries.
First you should use pdo or something.
foreach($result as $v){
if ($v['date'] === $datenow){
//your have a hit
}
}
but you should do it in your query (where date = $datenow) or something
Wampserver. in phpmyadmin i have added users db and user_data table. but my code doesn't work
<?php
include_once("sql_connect.php");
session_start();
$_SESSION['currentuser']=$_POST['usernameinput'];
$uname = $_POST['usernameinput'];
$pass = $_POST['passwordinput'];
$sql = "SELECT * FROM 'user_data' WHERE(
username='".$uname."' and password='".$pass."')";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
if($result[0]>0)
{
header ("location: Ghome.php");
}
else
{
header ("Location: loginform_er_incorrectlogpass.php");
}
?>
When i wrote correct username and password it doesn't work. maybe something wrong with my code?
<?php
session_start(); # Starts the session
session_unset(); #removes all the variables in the session
session_destroy(); #destroys the session
include ("LoginForm.php");
echo "<p align='center'><font color='red'>Неправильно указан Логин или Пароль.</font></p>";
?>
To fix your current problem, remove the quotes around the table name and get used to using back ticks instead.
SELECT * FROM `user_data` ...
Not this:
SELECT * FROM 'user_data' ...
(Technically, you don't even need the back ticks here, but using them is a good practice and will help catch a variety of typos down the road.)
Some additional pointers:
Never store passwords as plain text; this is extremely bad security practice. Use hashing and salting. Specifically, use bcrypt.
Please don't use mysql_*; the mysql_* functions are outdated, deprecated, and insecure. Use MySQLi or PDO instead.
You are wide open to SQL injection.
You were incorrectly using single quotes around the table name in your sql - you should use backticks instead. Also, there was no check for POSTed variables. Ideally though, to avoid heartache in the future, look at migrating to use either mysqli or PDO. At the very least try some basic filtering of provided POST data
<?php
session_start();
include_once("sql_connect.php");
if( isset( $_POST['usernameinput'] ) && isset( $_POST['passwordinput'] ) ){
$uname = mysql_real_escape_string( $_POST['usernameinput'] );
$pass = mysql_real_escape_string( $_POST['passwordinput'] );
$_SESSION['currentuser']=$uname;
$sql = "SELECT * FROM `user_data` WHERE `username`='".$uname."' and `password`='".$pass."';";
$query = mysql_query( $sql );
$result = mysql_fetch_array( $query );
header('location: ' .( $result[0]>0 ) ? 'Ghome.php' : 'loginform_er_incorrectlogpass.php' );
}
?>
replace this
$query = mysql_query($sql)
with the following
$query = mysql_query($sql) or die(mysql_error());
and see what error you are getting
The code below is supposed to check if there is a person in the database with a row in the database with the username it gets from the cookie login.And if there is it is supposed to include a page and if there isn't a person in the database with this user_id it is supposed to echo.Here is my code so far please tell me how I would do this.I also already know before someone tells me that mySQL statements like I have it are becoming depreciated.Here is My code:
<?php
include("dbconnect.php");
mysql_select_db("maxgee_close2");
$username = $_COOKIE['maxgee_me_user'];
$result = mysql_query("select user_id from users where username = '$username'");
$row = mysql_fetch_array($result);
mysql_free_result($result);
$check = mysql_query("SELECT * FROM events_main WHERE user_id ='$row['user_id']'") or die(mysql_error());
if(1==1){
if (mysql_num_rows($check)>0)
{
include("example.php");
}
else
{
echo "example";
}
}
?>
In the double-quoted string, your array variable $row['user_id'] is being incorrectly parsed due to the fact that you have quoted the array key without surrounding the whole thing in {}. It is permissible to omit the {} in a double-quoted string if you don't quote the array key, but the {} adds readability.
check = mysql_query("SELECT * FROM events_main WHERE user_id ='{$row['user_id']}'") or die(mysql_error());
//-------------------------------------------------------------^^^^^^^^^^^^^^^^^^
// Also acceptable, but not as tidy, and troublesome with multidimensional
// or variable keys - unquoted array key
check = mysql_query("SELECT * FROM events_main WHERE user_id ='$row[user_id]'") or die(mysql_error());
//-------------------------------------------------------------^^^^^^^^^^^^^^^^^^
As mentioned above, $_COOKIE is never considered a safe value. You must escape its values against SQL injection if you continue to use the old mysql_*() API:
$username = mysql_real_escape_string($_COOKIE['maxgee_me_user']);
2 Things right off the bat, like Waleed said you're open to SQL injection, not very nice thing to have happen to you. I would look into reading tutorials about MySQLi and PDOs, from there try and dive into a better way or running queries.
Also you are choosing to use cookies instead of sessions to store the username? Cookies can be modified client-side to say anything a smart user with firebug would want them to be. Sessions are stored server-side and the client (end-user) is only given an id of the session. They cannot modify the username if you send it as a session. (They could try and change the session id to another random bunch of numbers but thats like pissing into the wind, pardon my french.
Heres some pseduo code that will get you on your way I think
<?php
include("dbconnect.php");
$database = "maxgee_close2"; //Set the database you want to connect to
mysql_select_db($database); //Select database
$username = $_SESSION['maxgee_me_user']; //Grab the username from a server-side stored session, not a cookie!
$query = "SELECT user_id FROM `users` WHERE `username` = '" . mysql_real_escape_string($username) . "' LIMIT 1"; //Note the user of mysql_real_escape_string on the $username, we want to clean the variable of anything that could harm the database.
$result = mysql_query($query);
if ($row = mysql_fetch_array($result)) {
//Query was ran and returned a result, grab the ID
$userId = $row["user_id"];
mysql_free_result($result); //We can free the result now after we have grabbed everything we need
$query_check = "SELECT * FROM `events_main` WHERE `user_id` = '" . mysql_real_escape_string($userId) . "'";
$check = mysql_query($query_check);
if (mysql_num_rows($check)>0) {
include("example.php");
}
else {
echo "example";
}
}
?>
That code may/may not work but the real key change is that fact that you were running
mysql_free_result($result);
before your script had a chance to grab the user id from the database.
All in all, I would really go back and read some more tutorials.
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.