Executing this query if user has a row in DB, else not - php

I have a table called user_bio, this table has one row, which was inserted manually:
id: 1
age: 30
studying: Business
language: English
relationship_status: Single
username: conor
about_me: This is conor's bio.
I have a page called account_settings_bio.php, from where the logged in user ($username) can edit their details. At the moment, when I log in as conor, I can UPDATE my data, but say for example I log in as Alice, Alice has no row in the database, therefore, I would have to INSERT data for her, but it doesn't seem to insert a new row for her.
Here is my approach:
if ($update_bio){
/*************************/
// need to check if the username has data already in the db, if so, then we update the data, otherwise we insert data.
$get_bio = mysqli_query($connect, "SELECT * FROM user_bio WHERE username ='$username'");
$row_returned = mysqli_num_rows($get_bio);
if ($row_returned == 1){
$update_details_query = mysqli_query ($connect, "UPDATE user_bio SET studying ='$new_studying', language ='$new_lang',
relationship_status = '$new_rel', about_me = '$about_me' WHERE username ='$username'");
} if ($row_returned == 0) {
$insert_query = mysqli_query ($connect, "INSERT INTO user_bio VALUES ('', '$age', '$new_lang','$new_rel', '$username', '$about_me'");
}
echo " <div class='details_updated'>
<p> Details updated successfully! </p>
</div>";
}
The UPDATE query works fine, when logged in as conor, data does change in the db, its just the INSERT which is not working.

The order of the inserted columns is not the same as in the database and there are missing some (studying).
To be sure, you could rewrite your insert SQL to be more explicit:
INSERT INTO user_bio (id, age, studying, language, relationship_status, username, about_me) VALUES (NULL, '$age', '$new_studying', '$new_lang','$new_rel', '$username', '$about_me'"
Note: why not use if($row_returned==0){ /* INSERT */ } else { /* UPDATE */ } instead of a double if?

Related

Ensure username and email address are unique

I am trying to verify whether or not a username and email address exist in my database and have tried to do a if, elseif, else statement to no avail.
I want to first run a check to see if the username is fine - obviously if not, an echo statement will appear. If the username doesn't exist, run an elseif statement to see if the email address is unique - again if not, another echo statement will appear. For the final statement, if all other conditions return false, I want to run the below code so that the user's input is submitted to the database.
I initially tried to declare two variables with a statement to check if the username=$username and email_address=$email_address then check to see if the number of rows returned from a mysqli_query is more than 1 for the username. I entered an elseif statement with the same but for email address but then I had an else statement with the below code in {} brackets.
I have deleted the original code because too many errors were thrown up, and was probably too convoluted and messy when a more elegant way to do what I was exists.
Any help would be appreciated.
if(isset($_POST['submit']))
{
$sql = "INSERT INTO users (first_name, last_name, username, email_address, password, gender, city, country, verification_code, verified, sign_up_date) VALUES (
'$first_name',
'$last_name',
'$username',
'$email_address',
'$password',
'$gender',
'$city',
'$country',
'$verification_code',
'1',
'$sign_up_date')";
$result = mysqli_query($conn,$sql);
header("Location:confirmation.php");
}
What you want is an integrity check on the data. You should do this check inside the database. The simplest way is with unique constraints/indexes:
create unique index unq_users_username on users(username);
create unique index unq_users_email on users(email);
If you attempt to insert or update a row so it violates these constraints, then your data modification step will fail with an error.
You need to create an index for them.
Use The following command to create the index:
CREATE UNIQUE INDEX index_name ON table_name (column_name)
Check This Link for more info: https://www.w3schools.com/sql/sql_create_index.asp
You could write a function to check your database first for example:
$errors = []; // you can add errors to this array.
if (isset($_POST['submit']))
{
// first do your validation here against empty values and invalid email
$sql = "SELECT * from users where email='$email' and username='$username'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$errors[] = "Username and email has been taken.";
}
if (!empty($errors))
{
// loop through your errors and echo them
} else {
// insert your values into the database
}
}

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

mysql insert into creates 2 records in table row

Ok .. I'm stuck. I tried several codes from topics here, but still not working for me so I need a little help please.
I want to log if a user is logged in for the first time and want to update that same record if the user returns. The update part works, but when my function is executed the first time, it insert a total blank record and a record with all the data provided by variables. The last_login column is NULL for the first vist and is nicely updated with the last login.
But what I can't figure out is why the first login creates these extra records.
Here is the function code I created:
function log_users($userId, $username, $achternaam, $district, $gemeente, $ipaddress)
{
global $connection;
$sql = mysqli_query($connection, "SELECT * FROM logfile_sap WHERE user_id = '{$userId}'");
if(mysqli_num_rows($sql) > 0)
{
$sql = "UPDATE logfile_sap SET last_login = NOW() WHERE user_id = '{$userId}'";
$query = mysqli_query($connection, $sql);
}
else
{
$sql = "INSERT INTO logfile_sap
(user_id, username, achternaam, district, gemeente, ipaddress, first_login)
VALUES
('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW())";
$query = mysqli_query($connection, $sql);
}
}
So as you can see I am checking if the user already exists in the logfile_sap table and if it does NOT exist I want to insert the user (which works but with an extra row) and if the user already exists the record is updated.
This is the code I use on top of the page that needs to check and adds the data in the table:
<?php log_users($userId, $username, $achternaam, $district, $gemeente, $ipaddress); ?>
I hope some has a brighter idea than me ;-)
++++++++++++++++++++++++++++++++++++++++++++
Problem SOLVED. I had an epiphany !!!
I called my function OUTSIDE my if(isset($_SESSION['id'])) statement.
After I've put it INSIDE the if(isset($_SESSION['id'])) statement, there was only one record inserted into the table !!
Problem SOLVED. I had an epiphany !!!
I called my function OUTSIDE my if(isset($_SESSION['id'])) statement.
After I've put it INSIDE the if(isset($_SESSION['id'])) statement, there was only one record inserted into the table !!

Trying to update column value for specific row only?

I am having some problems with a script, I am basically inputting data into a MySQL table. This data will be inserted in the table as 1 row.
Upon a row of data being entered into the table I want the current/specific row currently being entered to have the column 'account_type' to be updated from its default value 'member' to 'client'.
It's a long story why I need to do it this way but I do not want to simply just enter the value 'client' it must be updated from 'member' to client.
The script I have (which is the bit at the bottom) is currently doing just this but it is affecting all rows in the table, is there a way I can add a where clause to the update to say only affect the current row being entered and do not update all other rows in the table?
<?php ob_start();
// CONNECT TO THE DATABASE
require('../../includes/_config/connection.php');
// LOAD FUNCTIONS
require('../../includes/functions.php');
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$number = $_POST['number'];
$dob = $_POST['dob'];
$accounttype = $_POST['accounttype'];
$query="INSERT INTO ptb_registrations (
username,
password,
firstname,
lastname,
email,
number,
dob,
accounttype,
date_created )
VALUES(
'".$username."',
'".$password."',
'".$firstname."',
'".$lastname."',
'".$email."',
'".$number."',
'".$dob."',
'".$accounttype."',
now()
)";
mysql_query($query) or die();
$query="INSERT INTO ptb_users (
first_name,
last_name,
email,
password )
VALUES(
'".$firstname."',
'".$lastname."',
'".$email."',
MD5('".$password."')
)";
mysql_query($query) or dieerr();
$result = mysql_query("UPDATE ptb_users SET ptb_users.user_id = ptb_users.id,
ptb_users.account_type = 'Client'");
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You can use the MySQL function LAST_INSERT_ID() to do this.
The old ext/MySQL extension exposes this functionality through mysql_insert_id(), but you can also access it directly, and more cleanly, and safely, in a query.
So you can do something like this:
$result = mysql_query("
UPDATE ptb_users
SET ptb_users.user_id = ptb_users.id,
ptb_users.account_type = 'Client'
WHERE id = LAST_INSERT_ID()
");
I know you say "it's a long story..." But what you are doing makes little-to-no sense. I can only imagine you are doing this because of a trigger - and that demonstrates quite nicely why triggers are generally a bad idea ;-)
Please try and re-think your design if at all possible.
Get the inserted ID after your first query then use it in the update (assuming you have a primary key with auto-increment).
Try With WHERE Condition on unique coloumn
mysql_query("UPDATE ptb_users SET ptb_users.user_id = ptb_users.id,
ptb_users.account_type = 'Client'" WHERE ptb_user.email='$email');

how to add a if confition to a mysql query?

i am trying to add an if statement to a mysql query so that it checks the user exists from a table called ptb_users in the user_id column before the query runs.
users can write on other users walls and before a user can write on a users wall / before the query inserts into ptb_wallposts, i want it to check that the from_user_id = the ptb_users.user_id.
i am trying to do this but i get syntax errors all over my page can someone please can someone show me how i would need to structure this:
<?php
// check if the review form has been sent
if(isset($_POST['review_content']))
{
$content = $_POST['review_content'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$content = stripslashes($content);
}
//We check if all the fields are filled
if($_POST['review_content']!='')
{
if exists (select user_id from ptb_users where user_id = #id)
begin
{
$sql = "INSERT INTO ptb_wallposts (id, from_user_id, to_user_id, content) VALUES (NULL, '".$_SESSION['user_id']."', '".$profile_id."', '".$content."');";
mysql_query($sql, $connection);
$_SESSION['message']="<div class=\"infobox-wallpost\"><strong>Wall Post Added</strong> - Your comment was posted to {$profile[2]}'s wall.</div><div class=\"infobox-close4\"></div>";
header("Location: {$_SERVER['HTTP_REFERER']}");
} }
}
end
else
begin
echo "error user doesnt exist"
end
?>
Here's an example of if statement (from MySQL Reference)
IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF
Let me explain a little more better, i'll compare between PHP and SQL if statements
PHP:
IF(variable > 0){
anything..
}
SQL:
IF variable > 0 THEN anything..
Read more:MySQL Reference - IF STATEMENT

Categories