array with sessions, only prints one letter - php

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.

Related

No getting result from query on host database

On my test machine the query for finding a users last_name and id works fine. I cannot figure out why it will not work on my host.
For this table
students(
id VARCHAR(5) NOT NULL,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(40) NOT NULL,
grade SMALLINT UNSIGNED NOT NULL,
PRIMARY KEY (id)
);
I run this query and there is no problem.
$sql="SELECT * FROM $tbl_name WHERE last_name ='$myusername' and id ='$mypassword'";
$result = #mysqli_query ($dbc, $sql);
mysqli_close($dbc);
if(!is_object($result) || $result->num_rows != 1)
{
$errors[] = 'No entries found, maybe capitalize your last name.';
}
else
{
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['username'] = $_POST['username']; //last name
$_SESSION['firstName'] = $row['first_name'] ;
}
On the host though, there is no rows in the result.
However, I ran this set of code and all the entries show up. Why does the query not work?
$sql="SELECT * FROM $tbl_name";
$num_results = mysqli_num_rows($result);
for ($i=0; $i<$num_results; $i++)
{
$row = mysqli_fetch_assoc ($result);
print stripslashes($row['last_name'])." ".stripslashes($row['id']);
}
By the way, the username is a persons last name and their password is their id. I am not that experienced with PHP and MySql, but this logically does not make sense to me.
Should be using mysqli_query.
Just please be sure to change $link with the connection result (of mysqli_connect).
Code:
$sql = "SELECT * FROM $tbl_name";
$result = mysqli_query($link, $sql);
$num_results = mysqli_num_rows($result);
$i = 0;
while ($row = mysqli_fetch_assoc ($result)) {
print stripslashes($row['last_name'])." ".stripslashes($row['id']);
$i++;
}
I am not sure about it, but I think you're using the wrong language for a mysql host, for example the loop isn't supposed to be in SQL language. As far as I know, this looks like C or C++ (it could depend of what kind of database you're currently using).
But what you need to know is that with this query you need to know the exact name and the exact password. Just in case, do this.
The query in SQL language, should be written it as it follow :
SELECT * FROM students WHERE last_name = "ifyouknowit" OR password="ifyouknowit";
You'll be sure to have at least one result, and it would show up the whole concerned lines as you're calling the " * ". So you don't really need a parameter, as the password is supposed to be unique to everyone.. (Theorically).
In another case, try to add one more column and call it USERID or something like this, to set a unique referent number. So you'll be sure not to be confusing between two people having the same name and last name which could happen easily.
Also, be sure to use the write syntax correctly about the name (like the capital letters are important somehow).
And I notice also that you don't have any password column in this table. Where is it stored? In anycase, with this query you'll still have results.
"students(
id VARCHAR(5) NOT NULL,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(40) NOT NULL,
grade SMALLINT UNSIGNED NOT NULL,
PRIMARY KEY (id)
);"
You should call the password database from where it's stored. Put more informations about the other tables and then I'll write a complete query for you.
This code was clearing the variables values so nothing was being searched for in the query. I thought this was standard code that should be used, apparently not.
//prohibit sql injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

MySql statement returning incorrect results

I am trying to receive an Id from my user table.
I have:
$retrieve_id = "SELECT userid FROM tb_users WHERE username = '$username'";
$user_id = intval(mysql_query($retrieve_id));
The statement should return 1 since that is the value in the table. However, it returns 6 which is the length of the column name (userid). This happens when I'm querying other tables too.
How can I retrieve the value from the table ONLY?
You need to fetch the actual result from the query, either using mysql_result or mysql_fetch_*.
$result = mysql_query("SELECT userid FROM tb_users WHERE username = '$username'");
if (!$result) {
die('Could not query:' . mysql_error());
}
$user_id = mysql_result($result, 0); // outputs first row
Note that all mysql_ functions are deprecated and you should use mysqli_ or PDO. Your query is also open to SQL injection.
http://php.net/manual/en/function.mysql-query.php
mysql_query returns a resource not the value.
$retrieve_id = "SELECT userid FROM tb_users WHERE username = '$username'";
$result = mysql_fetch_assoc(mysql_query($retrieve_id));
$user = $result['userid'];
A) mysql_* is deprecated
B) make sure you're parameterizing your inputs
C) try this:
$result = mysql_query($retrieve_id);
$user_id=$result["userid"];
function mysql_query returns resource type for a select query. For results you have to use mysql_fetch_array or mysql_fetch_assoc functions.
$retrieve_id = "SELECT userid FROM tb_users WHERE username = '$username'";
$result = mysql_query($retrieve_id));
$row = mysql_fetch_assoc($result)) {
echo $row['userid'];
Check the php docs on mysql_query(). It actually returns a resource, not simply the value you are querying for.
But you shouldn't even be using mysql_query() as it's deprecated in PHP 5.5, and you don't want to have to redo your code when you upgrade, do you?
Instead, use mysqli_query(), which will return a mysqli_result object. Then from that object, you can retrieve the values you're looking for with fetch_field()

echo data from database PDO

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

Receive multiple columns from one sql request in PHP

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]

Fetching bit field with mysql_query()

Here's my code:
$query = "SELECT Username, EmailVerified, Blocked FROM user";
$result = mysql_query($query, $link);
$row = mysql_fetch_assoc($result);
print_r($row);
Field Username is string and EmailVerified and Blocked are of type bit. The line print_r($row) displays the value of Username field but not the other two. I tried mysql_fetch_object(), mysql_fetch_row(), mysql_fetch_array() also, but same result.
Can't we fetch bit fields with mysql_query()?
I think you need to cast the BIT field to an integer ->
SELECT Username, CAST(EmailVerified AS unsigned integer) AS EmailV, CAST(Blocked AS unsigned integer) AS Block FROM User
Yes you can but they are retrieved as strings, and most likely end up being unprintable characters. You can get the values as numbers like so:
$query = "SELECT Username, EmailVerified, Blocked FROM user";
$result = mysql_query($query, $link);
$row = mysql_fetch_assoc($result);
$row['EmailVerified'] = ord( $row['EmailVerified'] );
$row['Blocked'] = ord( $row['Blocked'] );
print_r($row);
Instead of using BIT and converting it each time you need to use, you can use BOOL (which is already a TINYINT) and store TRUE (1) or FALSE (0) values.

Categories