Trying to echo out in this case the users username. I've had a friend help me, but he seems like he can't solve it either. So I'm asking you guys.
Basically, I'm right now trying to take the username from the person who logged in. The sessions which get set when you log in is called "user_id". Never mind, this is my code`
$user = $dbh->prepare("SELECT `username` FROM `users` WHERE `user_id` = ':user_id'");
$user->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_STR);
$user->execute();
while($row = $user->fetch(PDO::FETCH_NUM)){
$user_name = $row['1'];
}
?>
<h3>Welcome <p class="blue"><?php echo $user_name;?></p></h3><br/>`
With this, I get this error:
Undefined variable: user_name in
i know this is wrong, since it obviously doesn't work. But I've also tried setting sessions at that place in the while loop like this.
$_SESSION['user_id'] = $row['username'];
but then I get a blank result. Which means that there's no value of the session, or am I wrong?
You don't need quotes in the $row variable
while($row = $user->fetch(PDO::FETCH_NUM)){
$user_name = $row[0];
}
In your original code, its $row['1']. You don't have a field called 1 so remove the single quotes from around it.
Also, rows (when numerically indexed) start at 0, so the username field would be $row[0]
EDIT
And to touch on what #jeroen mentioned, in your SQL query, you shouldn't have quotes around your parameterized values:
$user = $dbh->prepare("SELECT `username` FROM `users` WHERE `user_id` = :user_id");
When there is no data returned, while won't be executed even once.
So, check your query.
To start you never checked if the user actually exists in the database, so what I personally would do is prepare the query and set a value to the default username- run the query and if no rows are returned then do nothing, if we actually have a row then fetch the corresponding column value in that row ('username') and set the variable to that.
$user = $dbh->prepare("SELECT `username` FROM `users` WHERE `user_id` = ':user_id'");
$user->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_STR);
$user->execute();
$UserName = "Unknown!";
while( $row = $user->fetch(PDO::FETCH_NUM) ){
$UserName = $row['username'];
}
echo '<h3>Welcome <p class="blue">{$UserName}</p></h3><br/>';
Related
I am new to PHP and have a really basic question.
If I know the result of a query is only a single value (cell) from a single row in MySQL how can I simplify the below without having to go through an array of results and without increasing the risk of SQL injection ?
In the example below I would just need to echo a single email as the result of the query.
I found a couple of posts suggesting different approaches with fetch_field for this but I am not sure what is the best way here since some of these seem to be pretty old or deprecated now.
My PHP:
$stmt = $conn->prepare("SELECT email FROM Users WHERE userName = ? LIMIT 1");
$stmt->bind_param('s', $userName);
$stmt->execute();
$result = $stmt->get_result();
$arr = $result->fetch_assoc();
echo $arr["email"];
Many thanks in advance.
You can avoid caring what the column is called by just doing this:
<?php
$stmt = $conn->prepare("SELECT email FROM Users WHERE userName = ? LIMIT 1");
$stmt->bind_param('s', $userName);
$stmt->execute();
$email = $stmt->get_result()->fetch_object()->email;
echo $email;
For some reason, the query when run through PHP will not return the results. I have tried both queries in the MySQL command line, and they work perfectly there. Here is the code (mysql_connect.php is working perfectly, to clarify).
<?php
error_reporting(-1);
// retrieve email from cookie
$email = $_COOKIE['email'];
// connect to mysql database
require('mysql_connect.php');
// get user_id by searching for the email it corresponds to
$id = mysqli_query($dbc,"SELECT user_id FROM users WHERE email=$email")or die('couldn\'t get id');
// get data by using the user_id in $id
$result = mysqli_query($dbc,"SELECT * FROM users WHERE user_id=$id")or die('couldn\'t get data');
//test if the query failed
if($result === FALSE) {
die(mysql_error());
echo("error");
}
// collect the array of results and print the ones required
while($row = mysql_fetch_array($result)) {
echo $row['first_name'];
}
?>
When I run the script, I get the message "could not get id", yet that query works in the MySQL command line and PHPMyAdmin.
Your code won't work for 2 reasons - $id will not magically turn into integer, but a mysqli result. And email is a string so it should be quoted.
But...
Why is all of that?
If you want to fetch all the data for user, for certain email, just make you second query fetch data by email and remove the first one:
SELECT * FROM users WHERE email='$email';
And don't forget to escape your input, because it's in cookie. Or, use prepared statements as suggested.
Your query is not valid, you should rewrite it with the following and make sure your you have mysqli_real_escape_string of the $email value before you put it into queries:
SELECT user_id FROM users WHERE email='$email'
Better approach is to rewrite your queries using MySQLi prepared statements:
Here how to get the $id value:
$stmt = mysqli_prepare($dbc, "SELECT user_id FROM users WHERE email = ?");
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id);
mysqli_stmt_fetch($stmt);
You wrote
mysqli_query($dbc,"SELECT user_id FROM users WHERE email=$email");
that is similar to
mysqli_query($dbc,"SELECT user_id FROM users WHERE email=example#example.com");
but it should be
mysqli_query($dbc,"SELECT user_id FROM users WHERE email='example#example.com'");
so you have to do this
mysqli_query($dbc,"SELECT user_id FROM users WHERE email='$email'");
or better
mysqli_query($dbc, 'SELECT user_id FROM users WHERE email=\'' . $email . '\'');
Beside this minor bug
You should be aware of SQL injection if someone changes the value of your cookie.
I am working on a friend list function and I can't figure out how to correctly receive the values.
My code looks like this:
$getuid = $mysqli->prepare("SELECT `uid` FROM `users` WHERE name = ? OR name = ?");
$getuid->bind_param("ss", $user, $friend);
$getuid->execute();
$getuid->bind_result($uid);
$getuid->fetch();
$getuid->close();
$resetpass = $mysqli->prepare("INSERT INTO `friendlist` SET `friend1`=?, `friend2`=?, `accept`=0");
$resetpass->bind_param("ss", $uid[0], $uid[1]);
With the first query I get exactly two uid values back. I want to use them in the second query. It seems like bind_result is not working, neither as array nor when using two values in bind_result. How can I do this using mysqli. I can't use get_result because I'm on PHP 5.2 .
Anyone able to help me?
I think you need something like this. I have not tested it and there are probably even better ways to do this. I just tried the quickest change i could make to your original code to get it to work.
$query = "SELECT uid FROM users WHERE name = '".$user."' OR name = '".$friend."'";
$getuid = $mysqli->query($query);
if($uid = $getuid->fetch_assoc())
{
$query = "INSERT INTO friendlist SET friend1= '".$uid['uid'][0]."', friend2='".$uid['uid'][1]."', accept=0";
$mysqli->query($query)
}
$getuid->close();
Okay I finally understood the concept of fetch.
In order to receive all the values I have to retrieve them in a while-loop.
Here is the solution:
$getuid = $mysqli->prepare("SELECT `uid` FROM `users` WHERE name = ? OR name = ?");
$getuid->bind_param("ss", $user, $friend);
$arra = array();
$getuid->execute();
$getuid->bind_result($uid);
while ($getuid->fetch()) {
$arra[] = $uid;
}
Now I can call the array values using $arra[0] and $arra[1]
I am trying to award a user a badge if their points are 10,000. There is a field in the table called badge1 with a default value set to locked and a points row. I am running and if statement that if the users points are 10,000 then UPDATE the badge1 row from locked to unlocked. My code seems correct but It is neither updating the the field nor showing any errors.
<?php
$db = new PDO('mysql:host=hostname;dbname=databasename;charset=UTF-8', 'username', 'password');
$username = $_SESSION['username'];
$q = "SELECT Points FROM login_users WHERE username ='$username'");
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$Points = $row['Points'];
if($Points == "10000") {
$awardBadge = $db->exec("UPDATE login_users SET badge1=unlocked WHERE username=?");
$Points->execute(array($username))
} else {
print "";
}
?>
UPDATE:
I managed to get it working.. however the problem is I am a bit new to converting old sql to PDO so this is not very secure but this is what works:
<?php
$connect = mysql_connect("host","username","password");
mysql_select_db("databasename");
$username = $_SESSION['jigowatt']['username'];
$q = "SELECT Points FROM login_users WHERE username = ('$username')";
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$Points = $row['Points'];
?>
// Place somewhere
<?php
if($Points >= "10000") {
$result = mysql_query("UPDATE login_users SET maneki='unlocked' WHERE username='$username'");
} else {
print "Badge has not been unlocked";
}
?>
"10000" string should be an 10000 int
And also, you might want to make a choice here too. You're using 2 types of setting up a mysql-database connection. the old-fashioned mysql_function() way and the new fancy PDO method.
I think working with the PDO version is safer, since newer PHP versions will not support the old methods anymore... That... and it just looks dirty ;P
Try this:
<?php
session_start();
$dbSession = new PDO('mysql:host=***;dbname=***', '***', '***');
$selectQuery = $dbSession->prepare('
SELECT `User`.`Points`
FROM `login_users` AS `User`
WHERE `User`.`username` = :username
');
$selectQuery->bindParam(':username', $_SESSION['username'], PDO::PARAM_STR);
$user = $selectQuery->fetch(PDO::FETCH_ASSOC);
if ( !empty($user) && $user['Points'] == 10000 ) {
$updateQuery = $dbSession->prepare('
UPDATE `login_users`
SET `badge1` = \'unlocked\'
WHERE `username` = :username');
$updateQuery->bindParam(':username', $_SESSION['username'], PDO::PARAM_STR);
$updateQuery->execute();
}
?>
Usefull resources:
PHP Database Objects (PDO)
PHP Sessions
MySQL Datamanipulation
MySQL SELECT syntax
MySQL UPDATE syntax
Better check if >= 10000 and not yet awarded. That could you also be done in SQL so you don't need that logic in PHP.
UPDATE login_users SET badge1=unlocked WHERE points >= 10000 and badget1 <> unlocked
The issue is caused by $point value which actually is not equal to 10000, but is NULL.
So I propose to always use var_dump() to get the actual value of the variable in such cases.
one tip: check the PDO docs, before you write php code! You use PDO and mysql commands on same time for same job!?? why???
Try this if($Points == 10000) instead of if($Points == "10000")
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.
if($Points==10000){
$awardBadge = $db->prepare("UPDATE login_users SET badge1=unlocked WHERE username=?");
$awardBadge->execute(array($username));
}
On login:
$result = mysql_query("SELECT `id`, `username`, `email` FROM `users`
WHERE `username` = '$username'
AND `password` = '$passwd'");
$userdata = array('id','username','email');
$_SESSION['user'] = mysql_result($result, 0, $userdata);
And when I want to print the users username:
echo $_SESSION['user']['username']
it only prints the first letter :/
What's wrong?
Debug your variables at each stage by using var_dump() to determine where the problem lies. Also, using mysql_result in that fashion is needless, I'd recommend using mysql_fetch_assoc() as it will do the same thing with less effort.
try this
$_SESSION['user']['id'] = mysql_result($result, 0, 'id');
$_SESSION['user']['username'] = mysql_result($result, 0, 'username');
$_SESSION['user']['email'] = mysql_result($result, 0, 'email');
also make sure the database itself doesn't contain only first letter initially.
I think you probably want to be using mysql_fetch_assoc() instead of mysql_result(). mysql_result() only gives you a single cell value from your result set, so when you assign $_SESSION['user'] = mysql_result($result,0,$userdata);, you are only getting the first cell value of the result row. Accessing it by an associative key (ie. $_SESSION['user']['username']) isn't possible, since it's not an array.
If you use mysql_fetch_assoc(), you'll have a key/value pair of your column names and values to work with:
$result = mysql_query("SELECT `id`, `username`, `email` FROM `users`
WHERE `username` = '".mysql_real_escape_string($username)."'
AND `password` = '".mysql_real_escape_string($passwd)."'");
$_SESSION['user'] = mysql_fetch_assoc($result);
As a side benefit, mysql_fetch_assoc() is much faster than mysql_result().
Note: I also put a mysql_real_escape_string() in there, as you must be sure to escape your query data somehow, unless you are sure it's safe.