php using $_get command to get foreign key - php

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");
}
}
?>

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- inserting data into the database

I am a beginner when we talk about PHP. SO I have no idea where I made a mistake using PHP.
<?php
require "conn.php";
$name = "yolo";
$surname = "yolo";
$nameOfFee= "asd";
$date = '2012-08-06';
$mysql_query = "(INSERT INTO Relation (Person_ID, Fee_ID, Date_of_fee)
SELECT Person.ID,Fee.ID,'$date'
FROM Person,Fee
WHERE Person.Name = '$name' AND Person.Surname = '$surname' AND Fee.Name_of_fee = '$nameOfFee');";
if($conn->query($mysql_query) === TRUE){
echo "Insert completed";
}
else{
echo "Insert not completed";
}
$conn->close();
?>
It always puts that Insert is not complete...
The Problems
There are a few syntax errors in this piece of code you have provided:
// here it starts, what is this "(" for before insert?
// Take note that your query is vulnerable to SQL attacks
$mysql_query = "(INSERT INTO Relation (Person_ID, Fee_ID, Date_of_fee)
SELECT Person.ID,Fee.ID,'$date'
FROM Person,Fee
WHERE Person.Name = '$name' AND Person.Surname = '$surname' AND Fee.Name_of_fee = '$nameOfFee');";
How to fix it
To fix these things I recommend you use the MySQLi OOP, like you are using now, but add prepared statements. I will walk through the new code with you so you can understand the process.
require "conn.php";
$name = "yolo";
$surname = "yolo";
$nameOfFee= "asd";
$date = '2012-08-06';
$sql = "INSERT INTO Relation (Person_ID, Fee_ID, Date_of_fee) VALUES (?, ?, ?)"; // rewrite your query with a preset number of values to prevent SQL Attacks
if($stmt = $conn->prepare( $sql ))
{ // before we run check to make sure the query worked
$stmt->bind_param('sss', $name, $nameOfFee, $date); // bind your variables so to know what goes where
$stmt->execute(); // execute the query
$stmt->close(); // close connection for safety
// message as an array for the user as feedback.
$message = array(
'is_error' => 'success',
'message' => 'Record was entered into database.'
);
}
else
{
$message = array(
'is_error' => 'danger',
'message' => 'Query Error, please revise the information.'
);
}

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);

PDO Querying database through sessions

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

SQL Query using PHP PDO

I'm trying to create a SQL query using PHP in which it checks to see if a row has already been submitted/set using the same date and user name. If it hasn't it inserts a new row. If it does find a match, it updates the row instead.
I can insert a new row fine, but when I use a pre-existing date and name, I receive no error in any of my logs, and the query appears to run without any problems. But when checking the database, I notice that there are no UPDATES actually set to the row. When I run the update command manually in SQL, it appears to work fine.
Having no logs/error data to go on, I was hoping to get some advice here. I'm sure there must be something I'm missing here. This is what I'm currently using:
require_once 'db-conn.php';
$name = $_POST['name'];
$email = $_POST['email'];
$date = $_POST['date'];
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$var3 = $_POST['var3'];
$var4 = $_POST['var4'];
$conn = db_connect ();
$sqlq = "SELECT * FROM tbl WHERE date = '$date' AND name = '$name'";
$nRows = $conn->query("$sqlq")->fetchColumn();
if ($nRows==0) {
try {
$sqli = "INSERT INTO tbl (name,email,date,var1,var2,var3,var4) VALUES (:name,:email,:date,:var1,:var2,:var3,:var4)";
$sql = $conn->prepare("$sqli");
$sql->execute(array(':name' => $name, ':email' => $email, ':date' => $date, ':var1' => $var1, ':var2' => $var2, ':var3' => $var3 ':var4' => $var4));
} catch(PDOException $e) {
die ('SQL Error');
}
}
else {
try {
$sqli = "UPDATE tbl SET email='$email', notes='$notes', var1='$var1', var2='$var2', var3='$var3' WHERE date='$date' AND name='$name'";
$sql = $conn->prepare("$sqli");
$sql->execute(array($name, $email, $date, $var1, $var2, $var3, $var4));
} catch(PDOException $e) {
die ('SQL Error');
}
}
You don't have the bound variables correct:
$sqli = "UPDATE tbl SET email=:email, notes=:notes, var1=:var1, var2=:var2, var3=:var3 WHERE date=:date AND name=:name";
$sql = $conn->prepare("$sqli");
$sql->execute(array(':name' => $name, ':email' => $email, ':date' => $date, ':var1' => $var1, ':var2' => $var2, ':var3' => $var3, ':notes'=>$notes));
You did it correct in the Insert statement but not in the update.
Not sure where you are getting $notes from though.
Plus not sure if it is intentional or not but you are not updating var4 in the update query.

Categories