Insert a value into database based on Session's User ID - php

Attempting to insert a Score based on the User's Session ID and POST , I've set up the database to use the UserID as a foreign key constraint but dont know how to do an insert query.
enter image description here
Database Values ^^
My attempt below
<?php
include("php/functions.php");
include('connections/conn.php');
$userID = $_SESSION["userID"];
//echo "all good here";
$newsoanxscore = mysqli_real_escape_string($conn, $_POST['socanxscore']);
$insertquery = "INSERT INTO socanxscore(socialanxietyscore)" . "VALUES('$newsoanxscore')";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
mysqli_close($conn);
?>
My insert form
<form action="insertsoanxietyscore.php" method="post">
Insert your score <input type="number" name="socanxscore" /><br><br>
<input type="submit" />
</form>

There are a few things here that may be helpful.
Firstly, you are not passing the user ID into your insert query. which can be written in this case as.
$insertquery = "INSERT INTO socanxscore(socialanxietyscore, UserId) VALUES('$newsoanxscore', '$userID')";
Secondly, please take the time to explore prepared queries to prevent SQL injection when passing end-user input to a database table. You may find the following resource useful.
http://php.net/manual/en/mysqli.prepare.php

go for this:
<?php
session_start();
include("php/functions.php");
include('connections/conn.php');
$userID = $_SESSION["userID"];
if(isset($_POST["socanxscore"]))
{
$query=INSERT INTO socanxscore(socialanxietyscore) VALUES('$newsoanxscore') WHERE userID=$userID";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
}
else
{
ehco "error";
}
mysqli_close($conn);
?>

Related

How to write multiple insert in multiple tables using the same form PHP

I have a problem with inserting data into two different tables: When a new member is created, it will be insert into member and grade tables after getting the id course from course table. I used INSERT for both of them at the same time with a multi query function but it doesn't work.
Can you help me please?
The form:
<form>
<input type="text" name='m_fName'>
<input type="text" name='m_lName'>
<input type="text" name ='m_nId'>
</form>
Php
$id = $re['c_id']; //to get id of course that I want to insert
$sql="INSERT INTO member (m_fName, m_lName, m_nId)
VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');
INSERT INTO grade(c_id,m_nId)
VALUES( '$id','$_POST[m_nId]')";
mysqli_multi_query($conn,$sql);
$id = $re['c_id'];
$sql="INSERT INTO member (m_fName, m_lName, m_nId) VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');";
$sql .="INSERT INTO grade(c_id,m_nId) VALUES( '$id','$_POST[m_nId]')";
if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Hope this will help. but try to first validate the posted data. check if isset .you did not show in the are you using post and the page you are posting your data
Answer above is the correct one, alternative way is the code below
$id = $re['c_id']; //to get id of course that I want to insert
$sql="INSERT INTO member (m_fName, m_lName, m_nId) VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');";
$act = mysqli_query($conn,$sql);
if($act) {
$sql2 = "INSERT INTO grade(c_id,m_nId)
VALUES( '$id','$_POST[m_nId]')";
$act2 = mysqli_query($conn,$sql2);
}

how can i parse values from one php to other

Let's start that I am newbie in php, so still I am trying to learn. I have created a form on Wordpress and I want to insert the values on one table (data_test table, i have managed that) and then take all the columns from data_test table(id that is auto increment number,name,email,product, quantity that the user enter) and insert to other table. I used this html code for the form to parse the values:
<form action="../enter_data_insert.php" method="post" onsubmit="return form_validation()" name="myForm">
Name <input id="name" name="name" type="text" />
Email <input id="email" name="email" required type="email"/>
Product<input id="prod" name="prod" required type="text" />
Quantity<input id="quant" name="quant" required type="number" min="1" / >
<input type="submit" value="Submit" />
</form>
And then this php to take the values:
<?php
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["prod"]) && !empty($_POST["quant"])){
//connect with database
include "database_conn.php";
//get the form elements and store them in variables
session_start();
$name=$_POST["name"];
$email=$_POST["email"];
$prod=$_POST["prod"];
$quant=$_POST["quant"];
//insert data on data_test table
$sql="INSERT INTO `site_db`.`data_test` ( `name` , `email`, `prod`,`quant`) VALUES ( '$name','$email','$prod','$quant')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//retrieve data
$sql = "SELECT data_test_id FROM data_test WHERE prod='$prod'";
$result = mysqli_query($con,$sql);
if(!$result){
echo mysqli_error($con);
} else{
while($value = mysqli_fetch_object($result)){
$id = intval($value->id);
$_SESSION['myid'] = $value->id;
var_dump($value);
//insert data on data_test_ins table
$sql="INSERT INTO site_db.data_test_ins` ( id,name , email, prod,quant) VALUES ( $id,'$name','$email','$prod','$quant')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//Redirects to the specified page
// header("Location: http://localhost/site/");
}
}
}
}
}
?>
Now it inserts all the values except the id on data_test table, i guess that it is null because it must close the first insert on php and then i have to call a second insert (with //insert data on data_test_ins table) on other php?
But i am not sure, can anyone help me please? or just guide me what is the right way to do.
I start to think that i have to create two php to parse the values and take on the first table and then on the other php to insert the values?
Any thoughts are helpful! :-)
What you are doing is not right. It is not a good approach to add value to id field to the database manually. It should be generated automatically by the database. What I would recommend is, add another field to your data_test_ins table eg: test_id which points to the id of your data_test table. This is the concept of foreign key.
Read about the concept of foreign keys here
Your code would now be:-
<?php
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["prod"]) && !empty($_POST["quant"])){
//connect with database
include "database_conn.php";
//get the form elements and store them in variables
session_start();
$name=$_POST["name"];
$email=$_POST["email"];
$prod=$_POST["prod"];
$quant=$_POST["quant"];
//insert data on data_test table
$sql="INSERT INTO `site_db`.`data_test` ( `name` , `email`, `prod`,`quant`) VALUES ( '$name','$email','$prod','$quant')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//retrieve data
$sql = "SELECT data_test_id FROM data_test WHERE prod='$prod'";
$result = mysqli_query($con,$sql);
if(!$result){
echo mysqli_error($con);
} else{
while($value = mysqli_fetch_object($result)){
$id = $value->id;
//insert data on data_test_ins table
$sql="INSERT INTO `site_db`.`data_test_ins` ( `id`,`name` , `email`, `prod`,`quant`, `test_id`) VALUES ('$name','$email','$prod','$quant', '$id')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//Redirects to the specified page
header("Location: http://localhost/site/");
}
}
}
}
}
?>
have you tried passing $value->id into the query instead of $value?
its an object which has the current row of a result set, so you should only pass the id attribute of this object.
$sql="INSERT INTO `site_db`.`data_test_ins` ( `id`,`name` , `email`, `prod`,`quant`) VALUES ( '$value->id','$name','$email','$prod','$quant')";
Addition:
stop using the mysql deprecated library.
you should check the posted data if its isset or not
EDIT:
your code should looks like:
<?php
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["prod"]) && !empty($_POST["quant"])){
//connect with database
include "database_conn.php";
//get the form elements and store them in variables
session_start();
$name=$_POST["name"];
$email=$_POST["email"];
$prod=$_POST["prod"];
$quant=$_POST["quant"];
//insert data on data_test table
$sql="INSERT INTO `site_db`.`data_test` ( `name` , `email`, `prod`,`quant`) VALUES ( '$name','$email','$prod','$quant')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//retrieve data
$sql = "SELECT data_test_id FROM data_test WHERE prod='$prod'";
$result = mysqli_query($con,$sql);
if(!$result){
echo mysqli_error($con);
} else{
while($value = mysqli_fetch_object($result)){
$_SESSION['myid'] = $value->data_test_id;
$id = intval($value->data_test_id);
//insert data on data_test_ins table
$sql="INSERT INTO `site_db`.`data_test_ins` ( id,name , email, prod,quant) VALUES ( '$id','$name','$email','$prod','$quant')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//Redirects to the specified page
header("Location: http://localhost/site/");
}
}
}
}
}
?>

Updating specific column in a particular row in mysql using php?

I have been trying to create a reset password feature for my website, where the user can insert the already registered email and that will generate a random OTP and will be stored in the same column as the user's details such as
id firstname lastname username email resetpassword
1 name last user email OTP
this is my code but it's not working.
<?php
require 'dbh.php';
session_start();
$random = mt_rand(1000,1000000);
$email = $_POST['email'];
$sql = "SELECT Email FROM registeredusers WHERE Email='$email'";
$result = mysqli_query($connection,$sql);
$emailCheck = mysqli_num_rows($result);
if (empty($email))
{
echo "please fill out all the fields";
}
else{
$result = mysqli_query($connection,$sql);
$sql = "UPDATE registeredusers SET ResetPassword='$random' WHERE Email='$email'";
Header("Location: submitOTP.php");
}
?>
I am just trying this out so the form looks something like this
<form action="resetPassword.php" method="POST">
<input type="text" value="email" name="email"></input>
<input type="submit" value="submit"></input>
</form>
You should firts assigne the sql code and after execute the query
$sql = "UPDATE registeredusers SET ResetPassword='$random' WHERE Email='$email'";
$result = mysqli_query($connection,$sql);
otherwise you simply repeat the previous (select ) query ..
and be careful for avoid sql injection take a look at prepared query and binding param

SQL Select/ Insert / Update query PHP MySQL

I have a table with columns userID(int),timeIN(date),timeOUT(date)
I am inserting a record in mysql database. First I check if the userID is correct from the other table and if its correct it will add a new record of the userID and timeIN(date) whereas the timeOUT will be NULL, else it will display error if the userID is not correct. I want my code to be able to check if the user is currently timeIN so it will prevent a double entry. I would also like to insert or update timeOUT(date) if the values of userID is equals to the user input and timeIN is not null and timeOUT is null.
Please kindly help...thanks.
Here is my code for inserting userID and timeIN: IT WORKS when inserting into mysql database.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
require_once('dbConnect.php');
$userID = $_POST['userID'];
$sql = "SELECT * FROM employee WHERE userID='$userID'";
$result = mysqli_query($con,$sql);
$check = mysqli_fetch_array($result);
if(isset($check)){
$sql = "INSERT INTO dtr (userID,timeIN) VALUES ('$userID', now())";
mysqli_query($con, $sql);
echo 'Time IN Successful!';
}else{
echo 'Invalid USER ID. Please try again!';
}
mysqli_close($con);
}
?>
You should handle these checks inside the database. The current check you are doing in the database can be handled by a foreign key constraint:
alter table dtr add constraint fk_dtr_userId
foreign key (userId) references employee(userId);
The second means that you want only one row with a NULl value. Ideally, this could be handled with a unique constraint:
alter table dtr add constraint unq_dtr_userId_timeOut
unique (userId, timeOut);
Unfortunately (for this case), MySQL allows duplicate NULL values for unique constraints. So, you can do one of two things:
Use a default value, such as '2099-12-31' for time out.
Use a trigger to enforce uniqueness
In either case, the database itself will be validating the data, so you can be confident of data integrity regardless of how the data is inserted or updated.
I did it from my mobile not tested but you will get the idea of what is going on
if(isset($check))
{
$sql="SELECT * FROM dtr WHERE userID = $userID";
$result = mysqli_query($con,$sql);
$check = mysqli_fetch_array($result);
if(isset($check))
{
echo "Already in";
if(isset($check['timeIN']) && !isset($check['timeOUT']))
{
$sql = "UPDATE dtr SET timeOUT= now() WHERE userID=$userID";
mysqli_query($con, $sql);
mysqli_close($con);
}
}
else
{
$sql = "INSERT INTO dtr (userID,timeIN) VALUES ('$userID', now())";
mysqli_query($con, $sql);
mysqli_close($con);
echo 'Time IN Successful!';
}
}
else
{
echo 'Invalid USER ID. Please try again!';
mysqli_close($con);
}

Connecting html form to php page according to primary key

Ok so essentially what I'm trying to do is add a q&a component to my website (first website, so my current php knowledge is minimal). I have the html page where the user's input is recorded, and added to the database, but then I'm having trouble pulling that specific info from the database.
My current php page is pulling info where the questiondetail = the question detail (detail='$detail') in the database, but that could potentially present a problem if two users enter the same information as their question details (unlikely, but still possible, especially if the same person accidentally submits the question twice). What I want to do is have the page load according to the database's question_id (primary key) which is the only thing that will always be unique.
HTML CODE:
<form id="question_outline" action="process.php" method="get">
<p><textarea name="title" id="title_layout" type="text" placeholder="Question Title" ></textarea> </p>
<textarea name="detail" id= "detail_layout" type="text" placeholder="Question Details" ></textarea>
<div id="break"> </div>
<input id="submit_form" name="submit_question" value="Submit Question" type="submit" />
</form>
PROCESS.PHP CODE:
$name2 = $_GET['name2'];
$title = $_GET['title'];
$detail = $_GET['detail'];
$query= "INSERT INTO questions (title, detail) VALUES ('$title', '$detail')";
$result = mysql_query("SELECT * FROM questions where detail='$detail' ")
or die(mysql_error());
The info is being stored correctly in the database, and is being pulled out successfully when detail=$detail, but what I'm looking to do is have it pulled out according to the question_id because that is the only value that will always be unique. Any response will be greatly appreciated!
Updated Version
QUESTION_EXAMPLE.PHP CODE
<?php
$server_name = "my_servername";
$db_user_name ="my_username";
$db_password = "my_password";
$database = "my_database";
$submit = $_GET['submit'];
$title = $_GET['title'];
$detail = $_GET['detail'];
$conn = mysql_connect($server_name, $db_user_name, $db_password);
mysql_select_db($database) or die( "Unable to select database");
$result = mysql_query("SELECT title, detail FROM questions WHERE id =" .
mysql_real_escape_string($_GET["id"]), $conn);
$row = mysql_fetch_assoc($result);
mysql_close($conn);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
Firstly, if that is code to be used in production, please make sure you are escaping your SQL parameters before plugging them in to your statement. Nobody enjoys a SQL injection attack. I would recommend using PDO instead as it supports prepared statements and parameter binding which is much much safer.
How can I prevent SQL injection in PHP?
So you have a form...
[title]
[details]
[submit]
And that gets inserted into your database...
INSERT INTO questions (title, details) VALUES (?, ?)
You can get the last insert id using mysql_insert_id, http://php.net/manual/en/function.mysql-insert-id.php.
$id = mysql_insert_id();
Then you can get the record...
SELECT title, details FROM questions WHERE id = ?
And output it in a preview page.
I have written an example using PDO instead of the basic mysql functions.
form.php:
<form action="process.php" method="post">
<label for="question_title">Title</label>
<input id="question_title" name="title"/>
<label for="question_detail">Detail</label>
<input id="question_detail" name="detail"/>
<button type="submit">Submit</button>
</form>
process.php:
<?php
// Create a database connection
$pdo = new PDO("mysql:dbname=test");
// Prepare the insert statement and bind parameters
$stmt = $pdo->prepare("INSERT INTO questions (title, detail) VALUES (?, ?)");
$stmt->bindValue(1, $_POST["title"], PDO::PARAM_STR);
$stmt->bindValue(2, $_POST["detail"], PDO::PARAM_STR);
// Execute the insert statement
$stmt->execute();
// Retrieve the id
$id = $stmt->lastInsertId();
// Prepare a select statement and bind the id parameter
$stmt = $pdo->prepare("SELECT title, detail FROM questions WHERE id = ?");
$stmt->bindValue(1, $id, PDO::PARAM_INT);
// Execute the select statement
$stmt->execute();
// Retrieve the record as an associative array
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
Without PDO...
form.php:
<form action="process.php" method="post">
<label for="question_title">Title</label>
<input id="question_title" name="title"/>
<label for="question_detail">Detail</label>
<input id="question_detail" name="detail"/>
<button type="submit">Submit</button>
</form>
process.php:
<?php
// Create a database connection
$conn = mysql_connect();
// Execute the insert statement safely
mysql_query("INSERT INTO questions (title, detail) VALUES ('" .
mysql_real_escape_string($_POST["title"]) . "','" .
mysql_real_escape_string($_POST["detail"]) . "')", $conn);
// Retrieve the id
$id = mysql_insert_id($conn);
// Close the connection
mysql_close($conn);
header("Location: question_preview.php?id=$id");
question_preview.php:
<?php
// Create a database connection
$conn = mysql_connect();
// Execute a select statement safely
$result = mysql_query("SELECT title, detail FROM questions WHERE id = " .
mysql_real_escape_string($_GET["id"]), $conn);
// Retrieve the record as an associative array
$row = mysql_fetch_assoc($result);
// Close the connection
mysql_close($conn);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
I assume you want to sort the questions according to the question_id. You could try using the ORDER BY command
example -
$result = mysql_query("SELECT * FROM questions where detail='$detail' ORDER BY question_id")
For these type of examples, you need to run Transaction within database
below are the
http://dev.mysql.com/doc/refman/5.0/en/commit.html
Or else
Create an random variable stored in session and also insert into database and you call it from database and you can preview it easily.
id | question_code | q_title
question_code is the random value generated before insertion into database,
and save the question_code in a session and again call it for preview.

Categories