PDO Querying database through sessions - php

I am trying to call data from my database to display on a users profile. I have the user session working correctly in the check user file. However the code below obviously isn; retrieving anything because it won't echo out in the echo statment i have in my HTML. Can someone please help???
require_once 'check.php';
if(isset($_GET['full_name'])){
$full_name = $_GET['full_name'];
$username = $_GET['username'];
$country = $_GET['country'];
$bio = $_GET['bio'];
$stmt = $dtb->prepare(" SELECT full_name=:full_name, username=:username, country=:country, bio=:bio FROM users WHERE id=:log_user_id AND username=:log_uname LIMIT 1");
$arr = array(
"full_name" => $full_name,
"username" => $username,
"bio" => $bio,
"country" => $country,
"log_user_id" => $log_user_id,
"log_uname" => $log_uname
);
ArrayBinder($stmt,$arr);
try{
$stmt->execute();
$dtb = null;
exit();
}
catch(PDOException $e){
echo $e->getMessage();
$dtb = null;
exit();
}
}

As it's absolutely IMPOSSIBLE to tell what are you trying to do from that mess you called "code" - so, just to give you an idea on the code you need to get user details from database based on id stored in a session:
$sql = "SELECT full_name,username,country,bio FROM users WHERE id=?";
$stmt = $dtb->prepare($sql);
$stmt->execute([$_SESSION['log_user_id']]);
$user = $stmt->fetch();
here in the $user array you should have name bio and stuff. Check session variable name

Related

What could cause a PHP insert into a MYSQL database to wrongly insert data from another user into a row?

A student of mine was saving her score for a learning game to a MySQL database but somehow a different person's name ended up being stored in her database row. How is this possible? Here is the PHP for the insert.
// Get Configuration file
require "configenzymatic.php";
// Connect to your server
$dbh = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
///////////////////////////////////////////////////////
// Status Checker
///////////////////////////////////////////////////////
if ($_GET["status"]) {
echo "online";
exit;
}
///////////////////////////////////////////////////////
// Upload new score
///////////////////////////////////////////////////////
//set POST data as data to be checked and updated
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$level1right = $_POST['level1right'];
$level1wrong = $_POST['level1wrong'];
$level2right = $_POST['level2right'];
$level2wrong = $_POST['level2wrong'];
$level3right = $_POST['level3right'];
$level3wrong = $_POST['level3wrong'];
$level4right = $_POST['level4right'];
$level4wrong = $_POST['level4wrong'];
// check for email and set hash variable
$stm = $dbh->prepare("SELECT * FROM $tname WHERE email=?");
$stm->bindValue(1, $email, PDO::PARAM_STR);
$stm->execute();
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$hashes = array($row['hash']);
$hash = $row['hash'];
$id = $row['id'];
foreach ($hashes as $hash) {
// If hash matches password, then...
if (password_verify($password, $hash)) {
// Everything is cool -- Insert the data into the database (update)
$stmt = $dbh->prepare("
UPDATE $tname
SET firstname = :firstname
, lastname = :lastname
, hash = :hash
, level1right = :level1right
, level1wrong = :level1wrong
, level2right = :level2right
, level2wrong = :level2wrong
, level3right = :level3right
, level3wrong = :level3wrong
, level4right = :level4right
, level4wrong = :level4wrong
WHERE email = :email
AND id = :id");
$stmt->execute(array($firstname, $lastname, $hash, $level1right, $level1wrong, $level2right, $level2wrong, $level3right, $level3wrong, $level4right, $level4wrong, $email, $id));
$affected_rows = $stmt->rowCount();
// check if row inserted
/* Return number of rows that were updated */
$count = $stmt->rowCount();
echo "$count";
}
}
}
The student inputted her name but someone else's name got inserted. I am totally baffled by this. Does anyone have any idea how this could occur? The person whose name was inserted in place of my student's added data at 12:30:44 today and my student added her data at 13:44:15. How did this data get mixed?
I'm not certain why you had your update wrapped in multiple loops, but it's entirely possible that users with the same password hash could exist, and (I think) would explain the behaviour you're seeing.
You are, presumably, looking to update the single user with the email and password submitted in the form? I assume you also have constraints on your table to ensure that email addresses are unique. So, you're grabbing the single user that matches that email, and checking their password. If it matches, update the single record with the same database ID. No loops!
// get password hash
$stm = $dbh->prepare("SELECT id, hash FROM $tname WHERE email=?");
$stm->execute([$_POST["email"]]);
$row = $stm->fetch(PDO::FETCH_ASSOC);
$hash = $row['hash'];
$id = $row['id'];
if (!password_verify($_POST["password"], $hash)) {
// verification failed, do something to present an error to the user
die();
}
$stmt = $dbh->prepare(
"UPDATE $tname
SET firstname=:firstname, lastname=:lastname,
level1right=:level1right, level1wrong=:level1wrong,
level2right=:level2right, level2wrong=:level2wrong,
level3right=:level3right, level3wrong=:level3wrong,
level4right=:level4right, level4wrong=:level4wrong
WHERE id=:id"
);
$stmt->execute([
":firstname" => $_POST["firstname"],
":lastname" => $_POST["lastname"],
":level1right" => $_POST["level1right"],
":level1wrong" => $_POST["level1wrong"],
":level2right" => $_POST["level2right"],
":level2wrong" => $_POST["level2wrong"],
":level3right" => $_POST["level3right"],
":level3wrong" => $_POST["level3wrong"],
":level4right" => $_POST["level4right"],
":level4wrong" => $_POST["level4wrong"],
":id" => $id
]);
$count = $stmt->rowCount();
echo "$count";
Also note that using named parameters in PDO requires the use of an associative array. Not sure how your original code would update anything at all without that.

Php webservice looping

I am about to lose my mind.I dont have any php experince and I am struggling about php web service.
Here is my code;
<?php
private $username2 = "";
private $password2 = "";
private $DB_CONNECTION;
private $servername = "localhost";
private $username = "root";
private $password = "";
private $dbname = "dptest";
function __construct()
{
$this->DB_CONNECTION = mysqli_connect($this->servername, $this->username,
$this->password, $this->dbname);
}
function getUserType(){
$sql = "SELECT usertype FROM `login_test` WHERE username = '". $this->username2."'AND password = '".$this->password2."'";
$result = mysqli_query($this->DB_CONNECTION,$sql);
//$value = mysqli_fetch_array($result);
while(!is_null($value = mysqli_fetch_array($result))){
return $value['usertype'];
}
}
}
This is my function code.The other is my login code;
<?php
include_once 'Authentication.php';
use user\Authentication;
$auth = new Authentication();
$auth->prepare($_POST);
$userStatus = $auth->isUserValidToLogIn();
if ($userStatus) {
// user existed
// So log him to main page
$json['success'] = 1;
$json['message'] = 'access granted';
$json['usertype'] = $auth->getUserType();
echo json_encode($json);
} else {
$json['success'] = 0;
$json['message'] = 'error!';
echo json_encode($json);
}
I am trying to get the user's type but when try to get the data form phpmyadmin local database it only gives the first column's usertype.When I try to get 2nd,3rd,4th so on.. user's usertype it doesnt return anything and blank page shows up on postman app.
Also my database looks like this;
usertype username password
admin despro 1234
client test 1234
client despro2 1234
client despro3 1234
The reason you are only getting one column back is because you only request the one column. In order to get the columns you want you need to explicitly request them in your query or use '*' in order to get all columns back. So your query should look like this in order to get all columns from the data table:
$sql = "SELECT * FROM `login_test` WHERE username = '". $this->username2."'AND password = '".$this->password2."'";
In general, I highly recommend that you stop using MySQLi extension and start using PHP Data Objects (PDO). It makes it easy to use prepared statements. Which also makes your code safer.
Then your query could look something like this (this is NOT the complete code):
// connecting to db
$pdo = new PDO($dsn, $user, $pass, $opt);
$sql = 'SELECT *
FROM login_test
WHERE userName = :username
AND pass = :password;';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $username2, PDO::PARAM_STR);
$stmt->bindParam(':password', $password2, PDO::PARAM_STR);
$res = $stmt->execute();
if ($res) {
$response["userdata"] = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$myData = array();
$myData["usertype"] = $row["usertype"];
$myData["username"] = $row["username"];
array_push($response["userdata"], $myData);
}
}
Note that the code above is for returning multiple rows of data. If you just want the one row then use something like this:
if ($res) {
$response["userdata"] = array();
$myData = array();
$myData["usertype"] = $row["usertype"];
$myData["username"] = $row["username"];
array_push($response["userdata"], $myData);
}
removing the 'while' statement.
You might want to take a look at this answer I gave, recently. It is a comprehensive example of using a webservice from an Android app.
How to insert all the SQL table data into an array in java [android studio]

php using $_get command to get foreign key

The users are registered in the db. When I submit from inputting the necessary info on the web, it would refresh and won't store the data in the db. I think there is something wrong with the $_get command. I'm trying to receive the id that is a foreign key of that table and store the data into the db.
<? include_once 'session.php';
include_once 'newtryconn.php';
include_once 'utilities.php';
if(isset($_POST['preferences'])){
$religion = $_POST['religion'];
$home = $_POST['home'];
$occuption = $_POST['occuption'];
$roommates = $_POST['roommates'];
$phone = $_POST['phone'];
if(isset($_GET['id'])) {
$id = $_GET['id'];
$sqlInsert = "INSERT INTO preferences (religion, home, occuption, roommates, phone, id)
VALUES (:religion, :home, :occuption, :roommates, :phone, :id)";
//use PDO prepared to sanitize data
$statement = $db->prepare($sqlInsert);
//add the data into the database
$statement->execute(array(':religion' => $religion, ':home' => $home, ':occuption' => $occuption, ':roommates' => $roommates, ':phone' => $phone, ':id' => $id));
header("location: homepage.php");
}
}
?>

Save Form Data Temporarily in SQL

I am building a form that allow users to save their data temporarily and complete later.
My problem is there are some Session variables that are used in the database, and so no column for them. The sql runs, and quits when the column is not found.
Is there a better way to implement what I'm trying to achieve?
foreach ($SESSION as $key => $value) {
$userInput1 = "UPDATE userform SET $key=:value WHERE username=:username AND email=:email" ;
$userInput2 = $dbusage->prepare($userInput1);
$userInput2->execute(array(
':value' => $value,
':username' => $_SESSION['username'],
':email' => $_SESSION['email']
));
}
if($userInput2->errno)
{
echo "An Error Occured".$userInput2->error;
}else{
header('Location: profile.php');
$userInput2->close();
exit;
}
Add a column saved_session to the table. Then serialize the whole $_SESSION variable and store it there.
$stmt = $dbusage->prepare("UPDATE userform SET saved_session = :session WHERE username=:username AND email=:email");
$stmt->execute(array(
':session' => serialize($_SESSION);
':username' => $_SESSION['username'],
':email' => $_SESSION['email']
));
Then when they come back, you get it out and do
$_SESSION = array_merge(unserialize($row['saved_session']), $_SESSION);

mysql update not working.. needs help on update code

I'm using $_POST to data to my php page to update the mysql database. I'm trying to use the customer id to pick the row and update the company name and fname(firstname). When I figure this out, I'll add the rest to be updated. I've also included what I've tried via the "//" Thank you
-----dbconnect-----
$id= $_POST['id'];
$company= $_POST['company'];
$fname = $_POST['fname'];
echo $id;
echo $company;
echo $fname;
//$sql = mysqli_query($con,"UPDATE customer SET company = $company WHERE id= '.$id.'")
//$sql = "UPDATE customer SET company ='".mysql_real_escape_string($_POST['company'])."WHERE id='".mysql_real_escape_string($_POST['id'])."'";
$sql = "UPDATE customer SET company = $company WHERE id= '1'";
mysqli_select_db('customer');
$retval = mysqli_query( $sql, $con );
if(! $retval )
{
die('Could not update data: ' . mysqli_error());
}
echo "Updated data successfully\n";
mysqli_close($conn);
}
Making a few assumptions here but try this out...
// make mysqli throw exceptions on error
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// assuming your connection looks something like this
// you can pass the database name as the fourth argument instead of using select_db()
$con = new mysqli('localhost', 'user', 'pass', 'customer');
// $id = $_POST['id'], etc
// use a prepared statement with parameter placeholders.
// for more info see http://php.net/manual/mysqli.quickstart.prepared-statements.php
$stmt = $con->prepare('UPDATE customer SET company = ? WHERE id = ?');
// bind parameter variables and execute
$stmt->bind_param('si', $company, $id);
$stmt->execute();
echo 'Updated data successfully', PHP_EOL;

Categories