Storing info in a PostgreSQl database issue - php

Ok I am making a registry for my website.
First page asks for some personal info
if($error==false) {
$query = pg_query("INSERT INTO chatterlogins(firstName, lastName, gender, password, ageMonth, ageDay, ageYear, email, createDate) VALUES('$firstNameSignup', '$lastNameSignup', '$genderSignup', md5('$passwordSignup'), $monthSignup, $daySignup, $yearSignup, '$emailSignup', now());");
$query = pg_query("INSERT INTO chatterprofileinfo(email, lastLogin) VALUES('$emailSignup', now());");
$userNameSet = $emailSignup;
$_SESSION['$userNameSet'] = $userNameSet;
header('Location: signup_step2.php'.$rdruri);
}
The first query works. The second query works but doesn't save the email...
the session doesn't work but the header works and sends me to the next page
I get no errors even if I comment out header
next page
#session_start();
$conn = pg_connect("host=localhost dbname=brittains_db user=brittains password=XXXX" );
$signinCheck = false;
$checkForm = "";
if(isset($_SESSION['$userName'])) {
$userName = $_SESSION['$userName'];
$signinCheck = true;
$query = pg_query("UPDATE chatterprofileinfo SET lastLogin='now()' WHERE email='$userName'");
}
if(isset($_SESSION['$userNameSet'])) {
$userName = $_SESSION['$userNameSet'];
$signinCheck = true;
$query = pg_query("UPDATE chatterprofileinfo SET lastLogin='now()' WHERE email='$userName'");
}
This is the top starting the session depending on if your logged in or not.
then if I enter in the info here and put it through this
if($error==false) {
$query = pg_query("UPDATE chatterprofileinfo SET aboutSelf='$aboutSelf', hobbies='$hobbies', music='$music', tv='$tv', sports='$sports', lastLogin='now()' WHERE email='$userName'") or exit(pg_last_error());
//header('Location: signup_step3.php'.$rdruri);
}
nothing shows up for on my database from this.
I have no idea where I went wrong
the website is
http://opentech.durhamcollege.ca/~intn2201/brittains/chatter/

For starters, don't put things that aren't strings in single-quotes like that. 'now()' means a literal string "now()"
Also, if you're doing updates to your database you're better of using prepared statements to help prevent against sql injection. In your case, see http://www.php.net/manual/en/function.pg-prepare.php

Related

Trying to get property of non-object when using a SESSION variable in sql query

So I'm currently coding a system where when they log in, they get a specialized panel for their ranking.
By default they are called User, and the Admins get, well, Admin.
When I am trying to get the verification that they are an Admin.
error_reporting(E_ALL); // i've been trying to find the bugs with this
require_once('db.php'); //using the good ol $conn = new mysqli
session_start();
if(!isset($_SESSION['username']) || empty($_SESSION['username'])){
header("location: login.php");
exit;
//to detect if they are logged in or not
}
//here is a failed attempt where I tried to "escape" the $_SESSION variable
// which still doesn't work
$username = $conn->real_escape_string($_SESSION['username']);
// I've tried this query with the $_SESSION variable escaped, with it's alias
// etc.
$query1 = "SELECT * FROM `users` WHERE `rank` = Admin AND
`username`='".$username."'";
// preparing to execute
$result = $conn->query($query1);
// this is where I detect if there is a row, set it to use Admin things
// which I will code later, for now just var holders.
if ($result->num_rows > 0) {
$rank = 'Admin';
} else {
$rank = 'User';
}
I've looked everywhere about property of non-object, but I only find old 2008 posts, which I've tried to implement, but end up not working.
Using XAMPP (apache) with PHP 7
You need to correct your SQL
"SELECT * FROM `users` WHERE `rank` = Admin AND `username`='".$username."'"
to
"SELECT * FROM `users` WHERE `rank` = 'Admin' AND `username`='".$username."'"
Note: single quote between Admin
I would suggest, to use below SQL instead, and store the rank value to SESSION directly.
"SELECT rank FROM `users` WHERE `username`='".$username."'"
Since you are using mysqli consider using prepared statements. By concatenating the variable values into the query string you are prone to SQL injection!.
more on prepared statements here: php.net/prepared-statements.
You were also missing some ' ' in your query, although when using prepared statements you don't need to add any apostrophes on input variables, while the apostrophes around constant strings must be included (they are missing in your example rank='Admin').
Here is the corrected code:
Note: I moved the session_start() to the top of the document to ensure it works properly, since it will not work if any output occurs before calling the function.
session_start();
error_reporting(E_ALL);
require_once('db.php'); //using the good ol $conn = new mysqli
if(empty($_SESSION['username']))
{
header("location: login.php");
exit();
}
$query1 = $conn->prepare("SELECT * FROM users WHERE rank='Admin' AND username=?");
$query1->bind_param("s", $_SESSION['username']);
$query1->execute();
$query1->store_result();
$result = $query1->num_rows;
if ($result > 0)
{
$rank = 'Admin';
}
else
{
$rank = 'User';
}

PHP insert blank values instead of GET values

I have this script on my site:
<?php
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if($db_found) {
$SQL = "INSERT INTO users (user, address)
VALUES('".$_GET['username']."','".$_GET['password']."')";
$result = mysql_query($SQL);
mysql_close($db_handle);
print "Records added to the database";
}
else {
print "Database NOT found";
mysql_close($db_handle);
}
?>
I then open this url in my browser:
http://ringkapps.altervista.org/addToDatabase.php?user=ringk&address=test
But instead of inserting "ringk" and "test" in the table, it inserts this:
Can't understand why, any help would be greatly appreciated.
This code is wrong!
$SQL = "INSERT INTO users (user, address)
VALUES('".$_GET['username']."','".$_GET['password']."')";
Replace this.
$SQL = "INSERT INTO users (user, address)
VALUES('".$_GET['user']."','".$_GET['address']."')";
It's not working because you're calling
http://ringkapps.altervista.org/addToDatabase.php?user=ringk&address=test
Which creates $_GET["user"] and $_GET["address"] but you are trying to put in the db $_GET['username'] and $_GET['password'] which don't exist.
You should call:
http://ringkapps.altervista.org/addToDatabase.php?username=ringk&password=test
Plus, read something on security for PHP apps, your code is prone to a lot of vulnerabilities!!!
In the url : http://ringkapps.altervista.org/addToDatabase.php?user=ringk&address=test
We can see user = ringk and address = test.
Where user is the key and ringk it's value.
Where address is the key and test it's value.
You can print all the $_GET value by using var_dump($_GET) and see by yourself what's in it.
My guess is that what you want is to access
$_GET['user'] and $_GET['address']
then just replace the line :
VALUES('".$_GET['username']."','".$_GET['password']."')";
with
VALUES('".$_GET['user']."','".$_GET['address']."')";
or you could update the url to match the code.

Values are not being added to the database

I am very new to PHP and Mysql. I have made a registeration form but the values being inputted are not being saved in my database. I don't know why. I am connected to the database. Could anyone give me some insight? By the way, I know you are going to say "Mysql" is deprecated. But I am just starting out and learning how all of this works. As soon as I have a thorough understanding of the processes I am going to change my code to Mysqli...
<?php
//form data
$submit = strip_tags($_POST['submit']);
$fname = strip_tags($_POST['fname']);
$lname = strip_tags($_POST['lname']);
$usernamereg = strip_tags($_POST['usernamereg']);
$passwordreg = strip_tags($_POST['passwordreg']);
$email = strip_tags($_POST['email']);
$emailcheck = strip_tags($_POST['emailcheck']);
$date = date("Y-m-d");
if($submit)
{
//check for existence
if($fname&&$lname&&$usernamereg&&$passwordreg&&$email&&$emailcheck)
{
//encrypt password
$password = md5($passwordreg);
if(strlen($usernamereg)>25)
{
echo "Username must be 25 characters or less.";
}
else
{
//checks password length
if(strlen($passwordreg)<6)
{
echo "Passwords must be atleast 6 characters long";
}
else
{
if($email!=$emailcheck)
{
echo "emails to not match";
}
else
{
//open database
$connect = mysql_connect("localhost","root","clandestine");
mysql_select_db("user_db"); //selects database
$queryreg = mysql_query("INSERT INTO users VALUES('','$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck'");
echo "You have been registered!";
}
}
}
}
else
echo "Please fill in <b>all</b> fields!";
Try assigning the columns in the INSERT query.
$queryreg = mysql_query("INSERT INTO users (`randomField`, `date`, `first_name`, `last_name`, `username`, `password`, `email`, `email_check`) VALUES ('','$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck'");
What is the first column supposed to be?
Have you done any sanity checking? (ie, printing test data to the screen at certain points in the code to make sure your IF statements are evaluating to true?
Additionally, try saving your INSERT query as a variable string:
$query = "INSERT INTO.............";
and then printing it to the screen. Copy and paste that query into PHPMyAdmin (if you have access to it) and see if there are any errors with your statement. PMA will tell you what errors there are, if any.
EDIT: Also, please don't ever MD5 a password or other highly sensitive data. Use a secure algorithm and salt the password. If you're unsure of what this all means:
refer to this link
What do you get if you do:
$query = "INSERT INTO users
(date, first_name, last_name, username, password, email, email_check)
VALUES
('$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck')";
mysql_query($query)or die('Error: <br />'.$query.'<br />'.mysql_error());
Note the removal of the backticks was just to simplify the code. It's correct to leave them in but with no spaces etc in your column names it should work anyway. Oh, and this is NOT good practice for production, of course. Just really clear debug.

Problems updating MySQL, "username" in a table using PHP

I'm probably not using the best method to create a user system, but it doesn't need to be fancy. I also know that I'm not the most organized
The logins and everything are alright, but I'm having a problem updating the credentials.
For example, I'm allowing users to change their username. I have the "Change Username" (Not that name) form to submit to update-username.php.
I already have mysql_real_escape_string, in the function "cleanString" in another page. My textarea submitting already has the old text in it, so you can change and view it before hand.
$user_id = "";
if(isset($_POST['id']))
{
$user_id = $_POST['id'];
}
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if(!$results) { //Check to see if query failed
die(mysql_error());
}
$resultsfetch=mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = $_POST['usernameinput'];
if(isset($_POST['usernameinput'])) {
$usernamenew = cleanString($_POST['usernameinput']);
}
if($usernamenew !=$username){
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
mysql_query($submit);
if(!$submit) { //Check to see if query failed
die(mysql_error());
}
}
It's probably something stupid or simple that I missed, or something really huge. Mainly because I am absent minded.
$submit = sprintf("UPDATE users SET username = '%s' WHERE user_id = %d",mysql_real_escape_string($usernamenew),mysql_real_escape_string($user_id));
If the page is loaded, $user_id will be NULL so noting will be updated! Make sure that this page loads, by sending $_POST['id'] . if these things are correct, check this.
"Did the database user have any permission to update the table? "
I have re-arranged your code. added comments where i changed. Try this
if (isset($_POST['id'], $_POST['usernameinput'])) { // Check if both POST id and usernameinput is available
$user_id = (int)$_POST['id']; //assuming this is an integer
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if (!$results) {//Check to see if query failed
die(mysql_error());
}
if (mysql_num_rows($result) > 0) { //verify if there is really a user with such id
$resultsfetch = mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = cleanString($_POST['usernameinput']);
if ($usernamenew != $username) {
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
if (!mysql_query($submit)) {//Check to see if query failed
die(mysql_error());
}
}
}else{
die("no such user with userid=$user_id");
}
}
Warning: mysql_ function is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
So, I guess I figured it out. It's an issue with my code carrying over to the next page.
The code I had been shown only broke the page, whether it be missing an integer, or something else. I'm not 100% sure.
Thanks for all the help guys, but now I know the issue.
EDIT:
I had forgotten to echo the $user_id in my hidden field.

Trying to create login with cookies

I'm try to get cookies on to a browser. It's giving me parameter 1 error and parameter 3. This code works elsewhere on my site but not here. Can someone help me?
if ((!isset($_POST["uname"])) || (!isset($_POST["password"])))
{
header ("Location: wddnt/clients/'. $tattoo_extern_acct . '/index.html");
exit;
}
$userpass = md5($_POST['password']);
#$db = mysqli_connect("$dbc_ser", "$dbc_usr", "$dbc_pwd", "$dbc_db");
$sql = "SELECT id, name, company, job_title, cell_num, office_num, office_email,
login_right, first_run, attempts, locked_out FROM login
WHERE email = '".$_POST["email"]."'
AND password = PASSWORD('$userpass')";
if (mysqli_connect_errno())
{
echo 'Cannot connect to database: ' . mysqli_connect_error();
}
else
{
$result = mysqli_query($db, $sql);
while ($info = mysqli_fetch_array($result))
{
$id = stripslashes($info['id_files']);
$u_acct = stripslashes($info['uname']);
$name = stripslashes($info['name']);
$job_title = stripslashes($info['job_title']);
$location = stripslashes($info['company']);
$cell_num = stripslashes($info['cell_num']);
$office_num = stripslashes($info['office_num']);
$office_email = stripslashes($info['office_email']);
$login_right = stripslashes($info['login_right']);
$first_run = stripslashes($info['first_run']);
$attempts = stripslashes($info['attempts']);
$locked_out = stripslashes($info['locked_out']);
$land_page = stripslashes($info['land_page']);
}
}
Try debugging some of the individual variables. What is in $sql, for example? Is it correct?
Is the "Cannot connect" clause executed, or does it get to the query and fail there? (I am not sure what "parameter 1 error and parameter 3" means).
Don't forget to escape the 'email' value by the way - this code has an SQL injection hole.
header ("Location: wddnt/clients/'. $tattoo_extern_acct . '/index.html");
This is not going to work the way you expect.
$sql = "SELECT id, name, company, job_title, cell_num, office_num, office_email,
login_right, first_run, attempts, locked_out FROM login
WHERE email = '".$_POST["email"]."'
You need to read up on SQL injection.
while ($info = mysqli_fetch_array($result))
You allow multiple accounts with the same email address / password?????
It's giving me parameter 1 error and parameter 3
Couldn't you post the actual error message you get?
$id = stripslashes($info['id_files']);
WTF? Smartquotes?
I'm not sure i understand your question but the last time i checked anyone who wants to use cookies uses the $_COOKIE global variable, either for setting them or accessing them. $_POST is made to get stuffs from forms, not cookies.
Please check the manual for more details about $_COOKIE
Regards

Categories