Set every username can choose the items in spinner one time - php

My case now is every username can select the items in spinner one time only. Mean if the spinner has 5 item, the user can choose all of them but all of them just can one time only. Below are my select data php:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$username = $_POST['username'];
$name = $_POST['name'];
//Creating an sql query
$sql = "INSERT INTO Selection (username, name) VALUES
('$username','$name')";
//Importing our db connection script
require_once('dbConnect.php');
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Select Successfully';
}else{
echo 'Sorry, You Already Select it Before';
}
//Closing the database
mysqli_close($con);
}
The name in this php means the item in spinner. I am no idea how to set every username can select all the item in spinner one time only. I am using localhost phpmyadmin.

You can specify unique constraint for username and name columns.
Alter the Selection table using this code:
ALTER TABLE `Selection` ADD UNIQUE `unique_index`(`username`, `name`);
Now if you try to insert any username and name pair that is already inserted, will fail.

Why are you not testing if the entry is already on database before you do insert? May be this (Untested) code might help:
if($_SERVER['REQUEST_METHOD']=='POST')
{
//Getting values
$username = $_POST['username'];
$name = $_POST['name'];
//Importing our db connection script
require_once('dbConnect.php');
//Creating an sql query
$check_sql = "SELECT * FROM Selection WHERE username='$username' AND name='$name' LIMIT 1";
$check_res = $mysqli->query($con,$check_sql);
if($check_res && mysqli_num_rows($check_res) >0)
{
echo 'Sorry, You Already Select it Before';
}
else
{
$sql = "INSERT INTO Selection (username, name) VALUES ('$username','$name')";
if(mysqli_query($con,$sql))
{
echo 'Select Successfully';
}
else
{
echo "Select failed for some other reason";
}
}
//Closing the database
mysqli_close($con);
}

I think for checking the user to spin it only once only you need to add a flag in your database structure such as
u_id | flag |
--------------
1 | 1
--------------
So that when retrieving or fetching or you can say while checking you just have to make sure that this particular u_id has already spin it once so further it can't be allowed.
So before inserting check the username or user_id of particular.
$sql = "SELECT u_id from user_spins table where u_id = 1 AND flag = 1";
//if yes then don't allow to proceed
//if no then insert into User_spins table
$sql = "INSERT INTO User_spins (u_id, name,flag) VALUES
('$username','$name',1)";
//Importing our db connection script
require_once('dbConnect.php');

Related

Find all values associated with certain value in a MySQL database

I'm creating a signup form and am onto the confirmation email part. I want to find all values associated with one other value in a database.
Ex. I get the "key" that is in the URL, then want to find all the values associated with it. In my database there are 4 columns: STR (the key), USERNAME, PASSWORD, and EMAIL. If I get STR I want to get the username, password, and email that are in the same row as the key and then insert it into another table in the same database.
verify.php:
<?php
$username = $_GET['username'];
$password = $_GET['password'];
$email = $_GET['email'];
$servername = "localhost";
$user = 'usernamelol';
$pass = 'passwordlol';
$dbname = 'vibemcform';
$str = $_GET['str'];
$conn = new mysqli($servername, $user, $pass, $dbname);
/* The variable query gets the "key" from the dont database. I want to compare that value with the other values associated with it. Ex. the variables in the same row as the key. */
$query = mysqli_query($conn, "SELECT * FROM `dont` WHERE STR='".$key."'");
/* Below is my attempt. Feel free to change whatever you want. */
$sql = "SELECT USERNAME, PASSWORD, EMAIL FROM dont";
$result = $conn->query($sql);
if (!$query) {
die('Error: ' . mysqli_error($con));
}
if (mysqli_num_rows($query) > 0) {
if ($result -> num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$sqltwo = "INSERT INTO data (USERNAME, PASSWORD, EMAIL) VALUES ($row["USERNAME"], $row["PASSWORD"], $row["EMAIL"])";
}
}
}
echo 'Successfully verified your email!'; exit;
?>
Why not simpy use the insert ... select syntax?
insert into data(username, password, email)
select username, password, email from dont where str = :key
You can run this query right ahead, and then check how many rows were affected:
If no row was affected, then it means that the select did not bring a row back: so the :key was not found in the database
If a row was affected, then the key was found and the executed row was inserted
Note that you should use parametrized queries so your code is safe from SQL injection (and more efficient as well); recommended reading How can I prevent SQL injection in PHP??

how to get data(user details) from one table to another when the user is logged in

How do i get details from a table to another table when a user is logged in. The details include their names (first, last), email and uid. The table that I want to fetch data is from the data entered when the user was registering. So does my code make any sense or is there any other way to achieve what I'm asking for? I have also attached pictures.
My purpose for this is to know which user entered the amount (bidamount)
Data comes from:
Data goes to:
<?php
if (isset($_POST['button'])) {
$bidamount = $_POST['bidamount'];
$ratings = $_POST['ratings'];
//TO ALERT SUBMISSION OF BLANK FIELDS(IT DOESN'T PREVENT SUBMISSION OF BLANK FIELD THOUGH)
if (!$bidamount) {
echo "can't submit blank fields";
}
//TO CONFIRM YOU ARE CONNECTED TO YOUR DATABASE (OPTIONAL)
$connection = mysqli_connect('localhost', 'root', '', 'tickmill_auctions');
if ($connection) {
echo "we are connected";
} else {
die("connection failed");
}
// TO INSERT USER DETAILS IN THE TABLE
if (isset($_SESSION['u_uid'])) {
$uid = $_SESSION['u_uid'];
$query = "SELECT * FROM tickmill_auctions WHERE user = '$uid'";
$result = mysqli_query($conn, $sql);
$resultcheck = mysqli_num_rows($result);
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$insert = mysql_query("INSERT INTO `son_of_man`
(`first`,
`last`,
`uid`,
`email`)
SELECT `first`,
`last`,
`uid`,
`email`
FROM `tickmill_auctions`
WHERE `user` = '$uid'");
}
}
//TO INSERT username and password from field to jossyusers database
$query = "INSERT INTO son_of_man(bidamount, ratings) VALUES('$bidamount','$ratings')";
$result = mysqli_query($connection, $query);
if (!$result) {
die("OOPPS! query failed" . mysqli_error($connection));
}
}
?>
You no need to add the full user detail in another table, read Normalization in SQL, just used the id of the user as foreign id to store the data in bid table. And then when you show the result on front view, you can use the JOINS to get the data from 2 tables.
And morevoer in query SELECT * FROM tickmill_auctions WHERE user = '$uid', there is no user field in any table.

Display the item selected by specific user in status page for that specific user

I would like to ask how to display the information based username? I mean when I login, it will lead me to select data page. My select data page has username, name and date. The name is the name of item in spinner, i put these item in spinner. For example, username which is john select item 1 in spinner and it will send to database. Then when go status page, it will only display the item selected by John only in John account. Same as other account, in their account only will display their own item selected.
Below is my select item php:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$username = $_POST['username'];
$name = $_POST['name'];
$date = $_POST['date'];
//Creating an sql query
$sql = "INSERT INTO Selection (username, name, date) VALUES
('$username','$name', '$date')";
//Importing our db connection script
require_once('dbConnect.php');
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Selected Successfully';
}else{
echo 'Sorry, You Already Select this item';
}
//Closing the database
mysqli_close($con);
}
?>
View Status Php:
<?php
//Importing Database Script
require_once('dbConnect.php');
//Creating sql query
$sql = "SELECT * FROM Selection";
//getting result
$r = mysqli_query($con,$sql);
//creating a blank array
$result = array();
//looping through all the records fetched
while($row = mysqli_fetch_array($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"id"=>$row['id'],
"username"=>$row['username'],
"name"=>$row['name'],
"date"=>$row['date']
)
);
}
//Displaying the array in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I am using localhost and phpmyadmin.
Table structure for Selection is below:-
id - primary key Not Null
username NOT NULL,
name NOT NULL,
date NOT NULL,
ALTER TABLE `Selection` ADD UNIQUE `unique_index`(`username`, `name`);
As you haven't mention the Schema of Spinner and Selection table, assuming a simple case for you, the solution would be like instructed below..
When user logs in, capture it's username (usually store it in session till he/she logs out).
In your Status.php your query would be
Select * from Selection where username = '$YOUR_USER_NAME_FROM_SESSION_HERE';
That should be enough as per your requirement.
NOTE: Using variable directly in your query will result in exposure of SQL injection. To prevent Sql injection, refer this answer too.
when the user logged in set the session using $_SESSION["name"] = "$username";
right now session is set then you can access the session variable from anywhere in the view page you retrieve the session using
$user= $_SESSION["name"].
now you fetch the items from the database
like
$sql = "SELECT * FROM Selection where username='$user'";
try it

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

Adding constant to values in Mysql and updating the values to the result

I have got MySQL table with three columns 'primary Key','debit_cash','user_id' So now i want to update the debit_cash values to the corresponding user_id by adding "15" to the value already present. The debit_cash is in VARCHAR so i tried converting to int and sum it , but still the values in MySQL is not changing .
Here is my code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$user_id = $_POST['user_id'];
//importing database connection script
require_once('dbConnect.php');
//Creating sql query
$sql = "SELECT cos_details.debit_cash AS debitCash,
(convert(int, debit_cash)+15) AS updatedDebitCash
FROM cos_details
UPDATE cos_details SET debit_cash = '$updatedDebitCash'
WHERE user_id = $user_id";
//Updating database table
if(mysqli_query($con,$sql)){
echo 'Updated Successfully';
}else{
echo 'Could Not Update Try Again';
}
//closing connection
mysqli_close($con);
}
Any one please help me.
Seems that you don't need the select but the update only
UPDATE cos_details SET debit_cash = cast( (convert(int, debit_cash)+15) as VARCHAR(20))
WHERE user_id = $user_id
could be that your user_id is a string too so you should surround the value with quote
UPDATE cos_details SET debit_cash = cast( (convert(int, debit_cash)+15) as VARCHAR(20))
WHERE user_id = '$user_id'

Categories