Reputation: 2870
Hello I am trying to make multiple users in a CMS I made. I have all their data in a table and was using mysql_num_rows
check if the records matched and then use session_register()
to set a session. I have changed this to PDO commands.
I want to be able to track the user when they are using the CMS so that every record changed can have their usrID attached to it. So that at a later date I can see who made updates and eventually use this to show information about the author etc.
So for example when they use forms to update or add a new record a hidden input with have their session id echo'd into it which will be taken from their user record as they log in.
Is the best way to do this? Have a written the syntax in this login code correctly?
$con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$sql="SELECT * FROM $tbl_name WHERE the_username='$the_username' and the_password='$the_password'";
$result = $con->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn();
if($number_of_rows==1){
$info = $result->fetch(PDO::FETCH_ASSOC);
$_SESSION['username'] = $info['the_username'];
$_SESSION['id'] = $info['id'];
header('Location: admin.php');
}else{
echo "Wrong username or password, please refresh and <a href=\"login.php\">try again.</a>";
}
Would it perhaps be better to put?
if($number_of_rows==1 && $info = $result->fetch(PDO::FETCH_ASSOC)){MAKE SESSION}
Upvotes: 1
Views: 176
Reputation: 157887
Your usage of PDO functions is quite inconsistent, and it leads to some errors.
First of all, you cannot fetch the same data twice. And, as a matter of fact, you don't need such a double fetch at all.
Also, for some reason you are not using prepared statements which are the only reason for using PDO. So, the proper code would be
$sql="SELECT * FROM $tbl_name WHERE the_username=? and the_password=?";
$result = $con->prepare($sql);
$result->execute(array($the_username,$the_password));
# $number_of_rows = $result->fetchColumn(); <- don't need that
$info = $result->fetch();
if($info){
$_SESSION['username'] = $info['the_username'];
$_SESSION['id'] = $info['id'];
header('Location: admin.php');
}else{
echo "Wrong username or password, please refresh and <a href=\"login.php\">try again.</a>";
}
Upvotes: 1
Reputation: 11830
Yes the code and logic works fine. But don't use session_register() they are deprecated in new version of PHP.
Upvotes: 0