Create Profile Information Page in PHP/MySQL/PDO - php

Hi I am having an issue creating a profile page using PDO- I can get the one to work that is in the old mysql but I can't figure out how to change the data over to PDO- I have been at this for weeks now and just at a loss. Please be nice I am VERY new to all of this. Here is the code that works- the old way
<?php
require_once('connection.php');
$id=$_SESSION['SESS_MEMBER_ID'];
$result3 = mysql_query("SELECT * FROM member where mem_id='$id'");
while($row3 = mysql_fetch_array($result3))
{
$fname=$row3['fname'];
$lname=$row3['lname'];
$address=$row3['address'];
$contact=$row3['contact'];
$picture=$row3['picture'];
$gender=$row3['gender'];
}
?>
And this is what I have tried to come up with but I just get a blank screen
<?php
require_once('connectpdo.php');
$id=$_SESSION['SESS_MEMBER_ID'];
$result3 = $db->prepare("SELECT * FROM member where mem_id='$id'");
$row3 = $stmt->fetch (PDO::FETCH_ASSOC);
{
$fname=$row3['fname'];
$lname=$row3['lname'];
$address=$row3['address'];
$contact=$row3['contact'];
$picture=$row3['picture'];
$gender=$row3['gender'];
}
?>
The login works fine in both old MySql and in the PDO but I can not seem to get the user profile to come up in PDO
//Create query
$result = $conn->prepare("SELECT * FROM member WHERE username= :xtxt AND password= :ztzt");
$result->bindParam(':xtxt', $username);
$result->bindParam(':ztzt', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
//Check whether the query was successful or not
if($rows > 0) {
//Login Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['loggedin'] = true;
$_SESSION['SESS_MEMBER_ID'] = $member['mem_id'];
$_SESSION['SESS_FIRST_NAME'] = $member['firstname'];
$_SESSION['SESS_LAST_NAME'] = $member['password'];
$_SESSION['SESS_USERNAME'] = $member['username'];
session_write_close();
header("location: home.php");
exit();
I get PHP Warning: mysql_fetch_assoc() expects parameter 1 to be resource, object given in...from this line
$member = mysql_fetch_assoc($result);
I get Undefined variable: stmt in ...& PHP Fatal error: Call to a member function fetch() on a non-object in...from this line
$row3 = $stmt->fetch (PDO::FETCH_ASSOC);
As I mentioned before I am very new at this, and I have spent many weeks researching doing multiple tutorials, and trying to figure all this out. I was just learning MySql when I was getting the depreciated errors and now I'm switching over to PDO, I know in the future I will need to pull information from multiple databases for one logged in user. I am not using functions or classes. Thanks in advance, my dogs will appreciate your help.

Okay I solved it! I am going to post the code for any one else having this issue #Fred, Thanks!
And I do know that the code is really different because I managed to get it on my test site, in my login process page I changed this code:
// query
$result = $conn->prepare("SELECT * FROM customers WHERE username=:hjhjhjh AND customers_password= :asas");
$result->bindParam(':hjhjhjh', $username);
$result->bindParam(':asas', $customers_password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
if($rows > 0) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
$_SESSION['customers_id']=$row['customers_id'];
$_SESSION['SESS_CUSTOMERS_KENNEL'];//kwaon ang id sang may tyakto nga username kag password
header("location: http://localhost:8888/ShowMyDog/newtemplate/index.php?action=account");
}
And in the page I wanted the profile to show up I changed the code to:
<?Php
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
echo "Please log in first to see this page.";
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<?Php
error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR);
require "config.php"; // Database connection details.
$customers_id=$_SESSION['loggedin']; // Collecting one record with for user
$count=$dbo->prepare("select * from customers where customers_id=:customers_id");
$count->bindParam(":customers_id",$customers_id,PDO::PARAM_INT,1);
if($count->execute()){
echo " Success <br>";
$row = $count->fetch(PDO::FETCH_ASSOC);
print_r($row);
echo "<hr>";
echo "<br>Admin id = $row[customers_id]";
echo "<br>username = $row[username]";
echo "<br>password=$row[customers_password]";
echo "<br>kennel=$row[customers_kennel]";
echo "<br>first name=$row[customers_firstname]";
echo "<br>last name=$row[customers_lastname]";
echo "<br>email address=$row[customers_email_address]";
echo "<br> postcode=$row[customers_postcode]";
echo "<br> street address=$row[customers_street_address]";
echo "<br> gender=$row[customers_gender]";
}
?>
</body>
</html>
I know it is still a bit messy, but like I said I'm new at this

Related

Php & MYSQL Login Script - Trying to get property of non-object *** on line 11

I´m trying to create a simple login script for my Website (with PHP & Mysql). Created the original script with plain php & mysql commands and everything worked just fine. Now i wanted to exchange the old mysql commands with mysqli commands. Somehow i´m now getting the error "Trying to get property of non-object *** on line 11" when I test my script. Could somebody explain exactly to me what causes that problemn and how to solve it (because I dont really understand the error here)?
Login Script:
<?php
session_start();
?>
<?php
include_once "db_connect.php";
$username = $_POST["username"];
$password = md5($_POST["password"]);
$abfrage = "SELECT username, password FROM login WHERE username LIKE '$username' LIMIT 1";
$ergebnis = mysqli_query($verbindung,$abfrage);
$row = mysqli_fetch_assoc($ergebnis);
if ($row->password === $password) { <--- Line 11
$_SESSION["username"] = $username;
if ($username != "admin") {
echo "Login erfolgreich. <br> Geschützter Bereich";
}
else {
echo "Login erfolgreich. <br> Geschützter Bereich";
}
}
else {
echo "Benutzername und/oder Passwort sind falsch.";
}
?>
$row is an associative array, because you have used $row = mysqli_fetch_assoc($ergebnis); but you are treating $row as an object i.e.
$row->password
So try:
if ($row['password'] === $password)
<?php
session_start();
include_once "db_connect.php";
// either use require_once + bail-out code in db_connect.php
// or check the connection resource/object here.
if ( !$verbindung || $verbindung->connect_errno ) {
die('sorry, db error. try again later');
}
$password = md5($_POST["password"]); // md5, unsalted ...not secure anymore. see http://docs.php.net/password_hash
// see http://php.net/security.database.sql-injection
$abfrage = sprintf( // password is a reserved word in mysql -> backticks around the field id
"SELECT `username`, `password` FROM login WHERE username LIKE '%s' LIMIT 1",
mysqli_real_escape_string($verbindung, $_POST["username"])
);
$ergebnis = mysqli_query($verbindung,$abfrage);
// mysqli_query may fail at any time -> error handling required
if ( !$ergebnis ) {
echo 'db query failed'; // $verbindung->error should contain more information
}
else if ( !($row = mysqli_fetch_assoc($ergebnis)) ) {
echo 'no result'; // you probably shouldn't make a distinction between "no such record" and "wrong password" - just for illustration
}
else if ($row['password'] === $password) { // fetch_assoc returns an array, not an object
$_SESSION["username"] = $username;
}
use that like this
$row = mysqli_fetch_assoc($ergebnis);
if ($row['password'] === $password) {
Try with $row["password"]==$password
If it still shows the same thing, then var_dump $row and see if it returns a result.

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, array given line 10 of index.php

I would like to know how to check if user is logged in and if user privilege is correct using procedural style. I am new to PHP. The code I am trying to use is the follow but it does not work at all I don´t know why:
Here is the login script
<?php
session_start();
$local=$_POST["local"];
$locales = array('001', '002', '003', '004', '005', '006', '007', '008', '009', '010');
if (in_array($local, $locales)){include ''.$local.'/enlace.php';}
else {header('Location: index.php?error=7');}
$locatario=mysqli_real_escape_string($database,$_POST['personal']);
$seguridad=mysqli_real_escape_string($database,$_POST['clave']);
if (empty($locatario) || empty($seguridad)| empty($local)){header('Location: index.php?error=1');exit();}
if (preg_match("/[^A-Za-z0-9]/", $locatario)){header('Location: index.php?error=2');exit();}
if (preg_match("/[^A-Za-z0-9]/", $seguridad)){header('Location: index.php?error=3');exit();}
$locatarios = mysqli_query($database, "SELECT * FROM `locatarios` WHERE locatario='$locatario' LIMIT 1");
if(mysqli_num_rows($locatarios)==0){header('Location: index.php?error=4');exit;}
$informacion=mysqli_fetch_array($locatarios,MYSQL_ASSOC);
$criptologia=hash('sha256',$informacion['codificacion'].hash('sha256',$seguridad));
if($criptologia!=$informacion['seguridad']){header('Location: index.php?error=5');exit;}
$_SESSION['identificacion']=$informacion['locatario'];
if ($informacion['privilegio']=="VENTAS"){header('Location: '.$local.'/ventas/index.php?funcion=inicio');exit();}
else if($informacion['privilegio']=="ADMINISTRACION"){header('Location: '.$local.'/administracion/index.php?funcion=inicio');exit();}
else if($informacion['privilegio']=="BODEGA"){header('Location: '.$local.'/bodega/index.php?funcion=inicio');exit();}
else if($informacion['privilegio']=="SOPORTE"){header('Location: '.$local.'/soporte/index.php?funcion=inicio');exit();}
else if($informacion['privilegio']=="PROPIETARIO"){header('Location: '.$local.'/propietario/index.php?funcion=inicio');exit();}
else if($informacion['privilegio']=="CLIENTES"){header('Location: '.$local.'/clientes/index.php?funcion=inicio');exit();}
else {header('Location: index.php?error=6');exit();}
?>
After user is logged in we check for login session and privilege but I am getting error
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, array given in /home/local/public_html/001/propietario/index.php on line 10
<?php
session_start();
$identificar = $_SESSION['identificacion'];
include 'sistema/enlace.php';
$locatarios = mysqli_query($database, "SELECT * FROM `locatarios` WHERE locatario='$identificar' LIMIT 1");
$controlar = mysqli_fetch_array($locatarios, MYSQLI_ASSOC);
$privilegio = $controlar["privilegio"];
if ($privilegio=='PROPIETARIO'){}
else {header('Location: /no-privs.php');exit();}
while($locatario = mysqli_fetch_array($controlar))
{
?>
<html>
<head>
<title>ADMIN ZONE</title>
</head>
<body>
WELCOME <?php echo $locatario[privilegio]?>, YOU ARE ADMIN ON THIS SITE</div>
</body>
</html>
<?php
}
?>
Ok. Well there's no sense in re-explaining all this, it's already been done in comments.
Nota: You will need to modify the session array and how it's being populated as well as some other variables if required.
However, you should first check to see if the session array is set as outlined in comments already.
This I used in conjunction with your originally posted code, so you will have to modiy it to suit your actual code in your language.
Tested/working on my own server:
<?php
session_start();
$DB_HOST = 'xxx';
$DB_USER = 'xxx';
$DB_PASS = 'xxx';
$DB_NAME = 'xxx';
$database = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($database->connect_errno > 0) {
die('Connection failed [' . $database->connect_error . ']');
}
// here we check the user session name
$_SESSION['session_name'] = "John";
$identify_session = $_SESSION['session_name'];
$members = "SELECT * FROM `members` WHERE username='$identify_session' LIMIT 1";
$query = mysqli_query($database, $members);
$control = mysqli_fetch_array($query, MYSQLI_ASSOC);
// we check users privilege example ADMIN or MOD or USER
$privilege = $control["privileges"];
echo $privilege;
// because we are in admin page we show page or redirect him if no privilege
if ($privilege=='ADMIN')
{
// echo "You're in!";
}
else {
header('Location: /get_out.php');
exit();
}
if ($result = $database->query($members)) {
while ($locatario = $result->fetch_assoc())
{
?>
<html>
<head>
<title>ADMIN ZONE</title>
</head>
<body>
WELCOME <?php echo $locatario[username]?>, YOU ARE ADMIN ON THIS SITE</div>
</body>
</html>
<?php
} // brace for while loop
} // brace for if ($result = $database->query($members))
?>
Footnotes:
However, doing it this way leaves you open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.

Whats wrong with mysql_num_rows? It is Returning errors

I used this series and I'm up to this video and mysql_num_rows has been pissing me off ever since the start.
http://www.youtube.com/watch?v=HP75yyjHgTg
i have easily spent 5 hours simply trying to fix all these mysql_num_rows errors.
At the Moment I'm doing profile page and I'm getting an error.
The Error is:
Warning: mysql_num_rows() expects parameter 1 to be resource, null given in /home/ztechrel/public_html/TESTING/blarg/REMAKE/profile.php on line 8 (line one is the mysql_num_rows part)
The Code in profile.php is:
<?php include("inc/incfiles/header.php"); ?>
<?php
if(isset($_GET['u'])) {
$username = mysql_real_escape_string($_GET['u']);
if(ctype_alnum($username)) //check user exists
$check = mysql_query("SELECT username,first_name FROM users WHERE username='$username'");
if(mysql_num_rows($check)===1)
{
$get = mysql_fetch_assoc($check);
$username = $get['username'];
$firstname = $get['first_name'];
}
else
{
echo "<h2>User Does Not Exist</h2>";
exit();
}
}
?>
is there a way i can fix this?
Or does anyone know another way i can write this?
I wouldn't be surprised he uses mysql_num_rows again, is there something i can use instead which is easy to implement?
If you need any other info just ask.
use this for checking error in your query
$username = mysql_real_escape_string($_GET['u']);
if(ctype_alnum($username)) {
//check user exists
$check = mysql_query("SELECT username,first_name FROM users
WHERE username='$username'") or die(mysql_error());
if(mysql_num_rows($check)===1){
$get = mysql_fetch_assoc($check);
$username = $get['username'];
$firstname = $get['first_name'];
}
else
{
echo "<h2>User Does Not Exist</h2>";
exit();
}
}
Make sure you are capture errors from PHP.
It might be the previous statement mysql_query is not executed and hence result is not set.
Try with below if mysql_query is executing properly or note
$check = mysql_query("SELECT username,first_name FROM users WHERE username='$username'") or die(mysql_error()."<br>".$sql);
This means your query returns nothing. Put echo for your query and display it in browser. Then copy the query and run it in phpmyadmin or mysql query browser or some other mysql editor. Try to find whether $username has correct value or any field name is wrong in the query.
Make sure variable $username is not empty., ctype_alnum is returning false. So $query is empty.
<?php include("inc/incfiles/header.php"); ?>
<?php
if(isset($_GET['u'])) {
$username = mysql_real_escape_string($_GET['u']);
if ($username != "" && if(ctype_alnum($username))) {
$check = mysql_query("SELECT username,first_name FROM users WHERE username='$username'");
if(mysql_num_rows($check)===1)
{
$get = mysql_fetch_assoc($check);
$username = $get['username'];
$firstname = $get['first_name'];
}
else
{
echo "<h2>User Does Not Exist</h2>";
exit();
}
}
}
?>

PHP and Oracle Session Login

Here it's I have a problem with my PHP Code + Oracle Login form.
In this PHP file, I make login function. But I have an error like this :
Warning: oci_num_rows() expects parameter 1 to be resource, string given in C:\xampp\htdocs\developers\it\session.php on line 12
Wrong
-
<?php
session_start();
include ("config.php");
$username = $_POST['username'];
$password = $_POST['password'];
$do = $_GET['do'];
if($do=="login")
{
$cek = "SELECT PASSWORD, USER_LEVEL FROM T_USERS WHERE USERNAME='$username' AND PASSWORD='$password'";
$result = oci_parse($conn, $cek);
oci_execute($result);
if(oci_num_rows($cek)==1)
{
$c = oci_fetch_array($result);
$_SESSION['username'] = $c['username']; ociresult($c,"USERNAME");
$_SESSION['USER_LEVEL'] = $c['USER_LEVEL']; ociresult($c,"USER_LEVEL");
if($c['USER_LEVEL']=="ADMINISTRATOR")
{
header("location:supervisor.php");
}
else if($c['user_level']=="User")
{
header("location:user.php");
}
else if($c['user_level']=="Root")
{
header("location:administrator.php");
}
else if($c['user_level']=="Manager")
{
header("location:manager.php");
}
else if($c['user_level']=="Admin")
{
header("location:admin.php");
}
else if($c['user_level']=="Director")
{
header("location:director.php");
}
}
else
{
echo "Wrong";
}
}
?>
I have tried to search in google, but still don't find anything.
Someone knows, what's the problem ?
Thanks for advance.
According to your script instead of
if(oci_num_rows($cek)==1)
you should call
if(oci_num_rows($result)==1)
You probably want to use $result and not $cek when you're asking for the number of rows returned from oci_num_rows(). However, you really want to avoid using $username and $password directly in the string like that. It'll make you wide open for SQL injection attacks, so look into using oci_parse together with oci_bind_by_name.
After that you should also always call exit() after the sequence of redirects, as the script will continue running if you don't (and that might be a security issue other places).
I also got the same case, so I tricked it with a script like this, but I don't know whether there was an impact or not. because the session and validation went smoothly.
$username =$_POST['username'];
$password = $_POST['password'];
$conn = oci_connect('xxx', 'xxx', 'localhost/MYDB');
$pass_encription = md5($password);
$query = "SELECT * from *table_name* WHERE *field1*='".$username."' and *field2*='".$password."'";
$result = oci_parse($conn, $query);
oci_execute($result);
$exe = oci_fetch($result);
if ($exe > 0)
{
oci_close($conn);
oci_execute($result);
$row =oci_fetch_array($result);
$sid = $row['field_1_parameter'];
$snama = $row['field_2_parameter'];
$sjab = $row['field_3_parameter'];
$session = array (
'field_1_array' =>$sid,
'field_2_array' =>$snama,
'field_3_array' =>$sjab
);
if($sjab == 'Administrator')
{
$this->session->set_userdata($session);
redirect('redirecting_page');
}
`

Retrieving information from database

I am trying to check if the session username matches the record in my database and if it does, I want to include a file.
This is my code
<?php
$username = $_SESSION['username'];
echo $username;
include('connect.php');
mysqli_select_db($connect,"persons");
$sql = "SELECT * FROM users WHERE sessionusername='$username'";
$r = mysqli_query($connect,$sql) or die(mysqli_error($connect));
$geez = mysqli_fetch_array($r);
if($geez)
{
include('check.php');
}
else
{
echo "error";
}
?>
The session username does not match the record in my database, yet the file is being included. Why?
OH, I FOUND THE ISSUE. IT IS CONSIDERING MY USERNAME TO BE ROOT...BUT WHEN I SAY ECHO $_SESSION['USERNAME'] IT IS CRAIG#CRAIG.COM..WHY SO>
<?php
$username = $_SESSION['username'];
echo $username;
include('connect.php');
mysqli_select_db($connect,"persons");
$sql = "SELECT sessionusername FROM users WHERE sessionusername='$username'";
$r = mysqli_query($connect,$sql) or die(mysqli_error($connect));
$geez = mysqli_fetch_array($r);
if($geez["sessionusername"]==$username)
{
include('check.php');
}
else
{
echo "error";
}
?>
You are simply testing whether the array $geez is empty or not. If the array has anything in it, you if($geez) will return true. To stop this behaviour, please see ceteras' answer, particularly this part:
if($geez["sessionusername"]==$username)
{
include('check.php');
}
I believe that's the only part that has changed.
Thanks,
James

Categories